branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>Jasmine9003/BFS-1<file_sep>/BFSTraversal.java
// Time Complexity :
// Space Complexity :
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this :
// Your code here along with comments explaining your approach
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans=new ArrayList<>();
compute(ans,root,0);
return ans;
}
public void compute(List<List<Integer>> ans,TreeNode curr,int level)
{
if(curr==null) return;
if(ans.size()==level)
ans.add(new ArrayList<Integer>());
ans.get(level).add(curr.val);
compute(ans,curr.left,level+1);
compute(ans,curr.right,level+1);
}
}
| 3d488cb903020c4c4f39b377d0f86afb456e1f9e | [
"Java"
] | 1 | Java | Jasmine9003/BFS-1 | d41db5da7316a1944c5f351007f7ce4d42b9df57 | e17a5c5521aea80769bdc81bf5f5f54f207d956d |
refs/heads/master | <repo_name>oaztech/debugger_dumper-whoops-samfony_on-wordpress-as-plugin<file_sep>/index.php
<?php
/**
* Plugin Name: Oaz Debugger
* Description: This plugin give you the power of debugging by using whoops package of Symfony for handling and trance errors
* and the dump function to print on web browser information contained on the variable passed on parameters and more
* infos with ergonomic design to take development more friendly.
* Version: 1.0.0
* Author: <NAME>
* Author URI: https://github.com/oaztech
* Php version: 7.4.9
*/
$_ENV['_APP_PATH'] = dirname(__FILE__);
$_ENV['_APP_URL'] = plugins_url() . '/' . basename(dirname(__FILE__));
$_ENV['_DB_PREFIX'] = $GLOBALS['table_prefix'];
require plugin_dir_path(__FILE__) . '/vendor/autoload.php';
(new \Whoops\Run)->pushHandler(new \Whoops\Handler\PrettyPageHandler)->register();
require_once $_ENV['_APP_PATH'] . '/config.php';
add_shortcode('oaz_debug', function (){
?>
<h1>I am the oaz debug plugin as a shortcode</h1>
<?php
});
<file_sep>/config.php
<?php
add_action('admin_menu', function () {
// main menu
add_menu_page('OazTecH Debugger', 'Oaz Debugger', 'manage_options', 'debug_area',
null, 'dashicons-admin-tools', 5);
// sub menus
add_submenu_page(
'debug_area',
'Debugging area',
'Debugging area',
'manage_options',
'debug_area',
fn() => require_once $_ENV['_APP_PATH'] . '/views/Debug_area.php');
add_submenu_page(
'debug_area',
'Setting',
'Setting',
'manage_options',
'setting',
fn() => require_once $_ENV['_APP_PATH'] . '/views/setting.php');
});
add_action('admin_enqueue_scripts', function () {
$currentPage = $_GET["page"] ?? 0;
$authorizedPage = [
'setting',
'debug_area',
];
// if page not authorized exit function
if (!in_array($currentPage, $authorizedPage)) return;
//wp_enqueue_style('l1', plugin_dir_url(__FILE__) . '/assets/css/app.fb0c6e1c.css');
wp_enqueue_script($currentPage, $_ENV['_APP_URL'] . "/assets/js/$currentPage.app.js", [], '', true);
});
| bc3e965d255cd4a37620d111e10aa4eb18a74808 | [
"PHP"
] | 2 | PHP | oaztech/debugger_dumper-whoops-samfony_on-wordpress-as-plugin | bca4f652c545a9eecb70480567e9e437dee1ba0b | 7fe1bbfa9d415fadee0b3fc9e89580511de7a5c2 |
refs/heads/master | <repo_name>DaryaFedkovich/homework_2<file_sep>/js/script4.js
var a = prompt('Задание 4: введите число: ', "");
if (a > 0)
alert("верно");
else
alert("неверно");<file_sep>/js/script8.js
var day = prompt("Задание 8: введите число", "");
if (day >= 1 && day <= 10)
alert("первая декада месяца");
else if (day >= 11 && day <= 20)
alert("вторая декада месяца");
else if (day >= 21 && day <= 31)
alert("третья декада месяца");
else
alert("Число вне диапозона");<file_sep>/js/script7.js
var n = prompt("Задание 7: Ввведите число", "");
if (n >= 0 && n < 15)
alert("первая четверть часа");
else if (n >= 15 && n < 30)
alert("вторая четверть часа");
else if (n >= 30 && n < 45)
alert("третья четверть часа");
else if (n >= 45 && n < 60)
alert("четвертая четверть часа");
else
alert("Число вне диапозона");<file_sep>/js/script9.js
var day = prompt("Задание 9: введите количество дней", "");
var year = day / 365,
mounth = day / 31,
week = day / 7,
our = day * 24,
minutes = day * 1440,
secunds = day * 86400;
if (day < 365)
document.write("количество лет: меньше года<br/>");
else
document.write("количество лет: " + year + "<br/>");
if (day < 31)
document.write("количество месяцев: меньше месяца<br/>")
else
document.write("количество месяцев: " + mounth + "<br/>");
if (day < 7)
document.write("количество недель: меньше недели<br/>");
else
document.write("количество недель: " + week + "<br/>");
document.write("количество часов: " + our + "<br/>", "количество минут: " + minutes + "<br/>", "количество секунд: " + secunds + "<br/>");
<file_sep>/js/script10.js
var day = prompt("Задание 10 введите число: ", "");
/*
january 1-31
fabruary 32-59
march 60-90
april 91-121
may 122-152
june 153-183
jule 184-214
august 215-244
sptember 245-274
october 275-305
november 306-335
decenmer 336-365
*/
if(day >= 1 && day <= 31){
document.write("January <br />");
}
else if( day >= 32 && day <= 59){
document.write("February <br />");
}
else if( day >= 60 && day <= 90){
document.write("March <br />");
}
else if( day >= 91 && day <= 121){
document.write("April <br />");
}
else if( day >= 122 && day <= 152){
document.write("May <br />");
}
else if( day >= 153 && day <= 183){
document.write("June <br />");
}
else if( day >= 184 && day <= 214){
document.write("Jule <br />");
}
else if( day >= 215 && day <= 244){
document.write("August <br />");
}
else if( day >= 245 && day <= 274){
document.write("September <br />");
}
else if( day >= 275 && day <= 305){
document.write("October <br />");
}
else if( day >= 306 && day <= 335){
document.write("November <br />");
}
else if( day >= 336 && day <= 365){
document.write("December <br />");
}
switch(true){
case day >= 1 && day <= 59 || day >= 336 && day <= 365:
document.write("Winter");
break;
case day >= 60 && day <= 152:
document.write("Spring");
break;
case day >= 153 && day <= 244:
document.write("Summer");
break;
case day >= 245 && day <= 335:
document.write("Autum");
break;
default:
document.write("Число вне диапозона");
break;
}
<file_sep>/js/script6.js
if ((a > 2 && a < 11) || (b >= 6 && b < 14))
alert("задание 6: верно");
else
alert("задание 6: неверно");<file_sep>/js/script5.js
var a = 10,
b = 2;
var sum = a + b;
var raznost1 = a - b;
var raznost2 = b - a;
var proizved = a * b;
var chastnoe1 = a / b;
var chastnoe2 = b / a;
var kvadrat = 0;
document.write("Задание 5 <br/>");
document.write("суммa = " + sum + "<br/>");
document.write("разность(a-b) = " + raznost1 + "<br/>");
document.write("разность(b-a) = " + raznost2 + "<br/>");
document.write("произведение = " + proizved + "<br/>");
document.write("частное(a/b) = " + chastnoe1 + "<br/>");
document.write("частное(b/a) = " + chastnoe2 + "<br/>");
if (sum > 1)
kvadrat = Math.pow(sum, 2);
document.write("квадрат суммы = " + kvadrat + "<br/>"); | 0b1aded6bfd5984bc15e7cae6d573402850c9089 | [
"JavaScript"
] | 7 | JavaScript | DaryaFedkovich/homework_2 | 11e0860a60b5fc438669836169a7eb43d820abd4 | b1ae94bca9328941af238ff642c13a4204a5e36f |
refs/heads/main | <repo_name>TeaCoffeeBreak/Tensorflow_dev_cert<file_sep>/ASL_CNN_datagen(wjson).py
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.keras as k
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, MaxPool2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy, sparse_categorical_crossentropy
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
'''import json
with open('data.json', 'r') as f:
train = json.load(f)
'''
data_dir = 'data/asl_alphabet_train'
batch_size = 500
resize = (50,50)
datagen = training_datagen = ImageDataGenerator()
'''rescale = 1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.4,
horizontal_flip=True,
fill_mode='nearest')'''
train_gen = datagen.flow_from_directory(
data_dir, class_mode= 'categorical', batch_size= batch_size,target_size= resize,color_mode= 'grayscale'
)
model = Sequential([
Conv2D(32, (3,3), input_shape=(50,50,1)),
MaxPool2D(pool_size=(3,3), padding = 'same'),
#Conv2D(16,(3,3)),
#MaxPool2D((3,3)),
Flatten(),
#Dense(16, activation='relu'),
Dense(units=29, activation='softmax')
])
model.compile(optimizer= Adam(lr = 0.001), loss = categorical_crossentropy, metrics= ['accuracy'])
history = model.fit(train_gen, epochs = 20 , shuffle = True)
acc = history.history['accuracy']
#val_acc = history.history['val_accuracy']
#loss = history.history['loss']
#val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)
plt.show()<file_sep>/todo.txt
Models to create for TF Cert Test
- model that imports from JSON filetype
-predictive text model
-predictive time series model using conv and lstms/grus
- use learningratescheduler callback
- <file_sep>/CFAR100_CNN.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.model_selection import train_test_split as tts
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Dropout, Activation,Flatten, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy, sparse_categorical_crossentropy
import math
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()#label_mode = 'coarse')
print(len(x_train), len(y_train), len(x_test), len(y_test))
print(y_train[0]) #(50000, 32, 32, 3)
#x_train, x_test = np.expand_dims(x_train, axis = 1), np.expand_dims(x_test, axis = 1)
model = Sequential([
Conv2D(filters = 64, kernel_size= (3,3), input_shape= (32,32,3), activation = 'relu', padding= 'same'),
BatchNormalization(),
MaxPool2D(pool_size= (3,3), strides=(3), padding= 'same'),
Dropout(0.25),
Conv2D(filters = 64, kernel_size= (3,3), activation = 'relu', padding= 'same'),
#BatchNormalization(),
MaxPool2D(pool_size= (3,3), strides=(3), padding= 'same'),
Dropout(0.25),
Conv2D(filters = 64, kernel_size= (3,3), activation = 'relu', padding= 'same'),
MaxPool2D(pool_size= (3,3), strides=(3), padding= 'same'),
Conv2D(filters = 64, kernel_size= (3,3), activation = 'relu', padding= 'same'),
MaxPool2D(pool_size= (3,3), strides=(3), padding= 'same'),
Flatten(),
Dense(units = 64, activation= 'relu'),
Dense(units = 32, activation = 'relu'),
Dense(units=(10), activation=('softmax'))
])
my_callbacks = [
tf.keras.callbacks.EarlyStopping(monitor= 'val_loss', min_delta= 0.01, patience=10, restore_best_weights= True, verbose = 2),
tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, min_delta = 0.05, patience=5, min_lr=0.0001, verbose=2)
]
model.compile(optimizer= Adam(lr = 0.001), metrics = 'accuracy', loss = sparse_categorical_crossentropy)
history = model.fit(x_train, y_train, validation_data=(x_test, y_test), callbacks = my_callbacks, epochs= 30, shuffle = True, batch_size= 100)
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
epochs = range(len(acc))
plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)
plt.show()<file_sep>/CFAR10 Transfer Models.py
import tensorflow as tf
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split as tts
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, BatchNormalization, Conv2D, MaxPool2D, Dropout, Flatten
from tensorflow.keras.optimizers import SGD, RMSprop, Adam
from tensorflow.keras.metrics import categorical_crossentropy, sparse_categorical_crossentropy, mean_absolute_percentage_error
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()#label_mode = 'coarse')
def preprocess_data1(x,y):
xx = tf.keras.applications.resnet.preprocess_input(x)
yy = tf.keras.utils.to_categorical(y)
return xx,yy
def resnet1(x_tr, y_tr,x_te,y_te, save = False):
x_tr, y_tr = preprocess_data1(x_tr, y_tr)
x_te, y_te = preprocess_data1(x_te, y_te)
from tensorflow.keras.applications import ResNet50 as RN
#create and assign input tensor
input_t = tf.keras.Input(32,32,3)
mymodel = RN(include_top= False, input_shape= (32,32,3), weights = 'imagenet')
print(len(mymodel.layers))
mymodel.summary()
for layer in mymodel.layers[:143]:
layer.trainable = False
model = Sequential()
model.add(mymodel)
model.add(Flatten())
model.add(Dense(units=10, activation='softmax'))
model.compile(optimizer=Adam(lr = 0.001), metrics=['accuracy'], loss = categorical_crossentropy)
history = model.fit(x_tr, y_tr, validation_data=(x_te, y_te), shuffle=True, batch_size=100, epochs=5)
#################################
def preprocess_data2(x,y):
xx = tf.keras.applications.resnet_v2.preprocess_input(x)
yy = tf.keras.utils.to_categorical(y)
return xx,yy
def resnet2(x_tr, y_tr,x_te,y_te, save = False):#dont run this shit, takes fucking ages
x_tr, y_tr = preprocess_data2(x_tr, y_tr)
x_te, y_te = preprocess_data2(x_te, y_te)
from tensorflow.keras.applications import ResNet152V2 as RN
#create and assign input tensor
input_t = tf.keras.Input(32,32,3)
mymodel = RN(include_top= False, input_shape= (32,32,3), weights = 'imagenet')
print(len(mymodel.layers))
mymodel.summary()
for layer in mymodel.layers[:-36]:
layer.trainable = False
model = Sequential()
model.add(mymodel)
model.add(Flatten())
model.add(Dense(units=10, activation='softmax'))
model.compile(optimizer=Adam(lr = 0.001), metrics=['accuracy'], loss = categorical_crossentropy)
history = model.fit(x_tr, y_tr, validation_data=(x_te, y_te), shuffle=True, batch_size=100, epochs=20 )
#resnet1(x_train,y_train, x_test, y_test)
#528
<file_sep>/Cryptoseries.py
from bs4 import BeautifulSoup
import requests
import pandas as pd
import json
import time
print('b')
cmc= requests.get('https://coinmarketcap.com/')
soup = BeautifulSoup(cmc.content, 'html.parser')
#print(soup.prettify())
data = soup.find('script', id = "__NEXT_DATA__", type = "application/json")
coins = {}
coin_data = json.loads(data.contents[0])
listings = coin_data['props']['initialState']['cryptocurrency']['listingLatest']['data']
for i in listings:
coins[str(i['id'])] = i['slug']
#for i in coins:
page = requests.get(f'https://coinmarketcap.com/currencies/{coins[i]}/historical-data/?start=20200101&end=20200630')
soup = BeautifulSoup(page.content, 'html.parser')
data = soup.find('script', id = "__NEXT_DATA__", type = "application/json")
historical_data = json.loads(data.contents[0])
quotes = historical_data['props']['initialState']['cryptocurrency']['ohlcvHistorical'][i]['quotes']
info = historical_data['props']['initialState']['cryptocurrency']['ohlcvHistorical'][i]
market_cap = []
volume = []
timestamp = []
name = []
symbol= []
slug = []
print('a')<file_sep>/Eth_TS_predict_RNN.py
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras as k
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GRU, Bidirectional, Flatten, Dense, Dropout, Conv1D, Lambda
from tensorflow.keras.optimizers import Adam
data = pd.read_csv('data/ethdata.csv')#, delimiter=',')
print(float('671.20'))
def volumefn(volstr):
#print(volstr[:-1])
num = float(volstr[:-1])
pred = volstr[-1]
if(pred == 'M'):
val = num * 1e6
elif(pred == 'K'):
val = num * 1e3
return val
def pricefn(pricestr):
pricestr = pricestr.replace(',','')
return float(pricestr)
data['Vol.'] = data['Vol.'].apply(volumefn)
data['Price'] = data['Price'].apply(pricefn)
data['Open'] = data['Open'].apply(pricefn)
data['High'] = data['High'].apply(pricefn)
data['Low'] = data['Low'].apply(pricefn)
data['series'] = list(zip(data['Price'].to_list(), data['Vol.'].to_list()))
data1 = data['Price'].to_list()
data = data['series'].to_list()
splitratio = 0.9
leng = int(len(data1) * splitratio)
data1_train = data1[:leng]
data1_test = data1[leng:]
def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
dataset = tf.data.Dataset.from_tensor_slices(series)
dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1]))
dataset = dataset.batch(batch_size).prefetch(1)
return dataset
window_size = 20
batch_size = 1
shuffle_buffer_size = 1000
dataset = windowed_dataset(data, window_size, batch_size,shuffle_buffer_size )
dataset1 = windowed_dataset(data1_train, window_size, batch_size,shuffle_buffer_size )
print(len(data1))
#for element in dataset.as_numpy_iterator():
# print(element)
model = Sequential([
Lambda(lambda x: tf.expand_dims(x, axis=-1),input_shape=[20]),
Bidirectional(GRU(32,return_sequences=True)),# input_shape = (20,)),
Bidirectional(GRU(32)),
Dense(32),
Dense(32),
Dense(1),
Lambda(lambda x: x*50)
])
model.compile(loss="mse", optimizer=Adam(lr = 0.0001))
print('compiled')
model.fit(dataset1, shuffle= False, epochs=25)
forecast=[]
for time in range(len(data1) - window_size):
#print(time,time + window_size)
print(time, len(data1) - window_size)
forecast.append(model.predict(data1[time:time + window_size]))#[np.newaxis]
forecast = forecast#[leng-window_size:]
results = np.array(forecast)[:, 0, 0]#
plt.plot(results, label = 'predicted')
plt.plot(data1, label = 'true')
plt.legend()
plt.show()<file_sep>/MNIST_CNN_callbacks.py
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Conv2D, Activation, Flatten, MaxPool2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy, sparse_categorical_crossentropy
from sklearn.model_selection import train_test_split as tts
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import math
import os
(train_x, train_y), (test_x, test_y) = keras.datasets.mnist.load_data()
train_x = np.expand_dims(train_x, axis = 3)
test_x = np.expand_dims(test_x, axis = 3)
print(train_x.shape) #(60000, 28, 28, 1)
model = Sequential([
Conv2D(filters=16, kernel_size= (2,2), activation= 'relu', input_shape=(28,28,1), padding = 'same'),
MaxPool2D(pool_size= (2,2), strides = 2),
Flatten(),
Dense(units = 10, activation = 'softmax')
])
model.compile(optimizer= Adam(learning_rate = 0.001), loss = sparse_categorical_crossentropy, metrics = ['accuracy'])
#Callbacks: https://keras.io/api/callbacks/
my_callbacks = [
tf.keras.callbacks.EarlyStopping(monitor= 'val_loss', min_delta= 0.01, patience=4, restore_best_weights= True),
tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, min_delta = 0.05, patience=3, min_lr=0.0001)
]
history = model.fit(train_x,train_y, validation_data= (test_x,test_y), epochs = 5, shuffle = True, batch_size=10, callbacks = my_callbacks)
print(history.history['val_accuracy'])
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
epochs = range(len(acc))
plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)
plt.show()
#TODO: plot history, add callbacks, maybe make the model a bit better<file_sep>/Starwars_textgen.py
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional, GRU
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import numpy as np
import pandas as pd
tok = Tokenizer(char_level= False)
data = open('Data/SW_EpisodeIV.txt').read()
data2 = open('Data/SW_EpisodeV.txt').read()
data3 = open('Data/SW_EpisodeVI.txt').read()
data = data + data2 + data3
txt = list(filter(lambda x: (x != 'dialogue') and (x != ' '),data.split('"')[::3]))
print((txt))
tok.fit_on_texts(txt)
total_words = len(tok.word_index) + 1
print(tok.word_index)
print(total_words)
input_sequences = []
for line in txt:
token_list = tok.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
input_sequences.append(n_gram_sequence)
#print(len(input_sequences), input_sequences)
#now to pad sequences, make predictors + label
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen= max_sequence_len, padding= 'pre'))
xs, labels = input_sequences[:,:-1], input_sequences[:,-1]
ys = tf.keras.utils.to_categorical(labels, num_classes= total_words)
model = Sequential()
model.add(Embedding(total_words, 100, input_length=max_sequence_len-1))
model.add((GRU(128, return_sequences= True)))
#model.add((GRU(128, return_sequences= True)))
model.add((GRU(128)))
model.add(Dense(128))
model.add(Dense(total_words, activation='softmax'))
adam = Adam(lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
#earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')
history = model.fit(xs, ys, epochs=50)
#print model.summary()
print(model)
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.xlabel("Epochs")
plt.ylabel(string)
plot_graphs(history, 'accuracy')
plt.show()
model.save('models/sw_predict.h5')<file_sep>/fakenews_nlp.py
import tensorflow.keras as k
import pandas as pd
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, GRU, Bidirectional, Conv1D, Flatten, Embedding
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy, sparse_categorical_crossentropy, binary_crossentropy
from sklearn.model_selection import train_test_split as tts
realdat= pd.read_csv('data/True.csv')
fakedat= pd.read_csv('data/Fake.csv')
realnum = len(realdat['title'].values)
fakenum = len(fakedat['title'].values)
x = np.array(realdat['title'].to_list() + fakedat['title'].to_list())
y = np.array([1 for i in range(realnum)] + [0 for i in range(fakenum)])
x_train, x_test, y_train, y_test = tts(x,y, shuffle= True, random_state= 0)
print(x_train,'apple', x_train[0])
tokenizer = Tokenizer(oov_token= '<OOV>')
tokenizer.fit_on_texts(x)
maxlen = 200
embdim = 8
total_words = len(tokenizer.word_index) + 1
xs_train = tokenizer.texts_to_sequences(x_train)
xs_train = pad_sequences(xs_train, padding = 'post', maxlen= maxlen)
xs_test = tokenizer.texts_to_sequences(x_test)
xs_test = pad_sequences(xs_test, padding = 'post', maxlen= maxlen)
#print(xs_test)
#print(xs_train)
model = Sequential([
Embedding(input_dim=total_words ,output_dim=embdim, input_length=maxlen ),
Bidirectional(GRU(16, return_sequences= True)),
Bidirectional(GRU(16)),
Flatten(),
Dense(16, activation= 'relu'),
Dense(1, activation= 'sigmoid')
])
model.compile(optimizer= Adam(lr = 0.001), metrics=['accuracy'], loss = binary_crossentropy)
#history = model.fit(xs_train, y_train, validation_data=(xs_test, y_test), batch_size= 64, shuffle= True, epochs = 10)
<file_sep>/text_predict.py
import numpy as np
import tensorflow as tf
from tensorflow import keras
model = keras.models.load_model('models/sw_predict.h5')
seed_text = "I've got"
next_words = 25
################################################
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional, GRU
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import numpy as np
import pandas as pd
tok = Tokenizer(char_level= False)
data = open('Data/SW_EpisodeIV.txt').read()
data2 = open('Data/SW_EpisodeV.txt').read()
data3 = open('Data/SW_EpisodeVI.txt').read()
data = data + data2 + data3
txt = list(filter(lambda x: (x != 'dialogue') and (x != ' '),data.split('"')[::3]))
print((txt))
tok.fit_on_texts(txt)
total_words = len(tok.word_index) + 1
print(tok.word_index)
print(total_words)
input_sequences = []
for line in txt:
token_list = tok.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
input_sequences.append(n_gram_sequence)
#print(len(input_sequences), input_sequences)
#now to pad sequences, make predictors + label
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen= max_sequence_len, padding= 'pre'))
################################################################
for _ in range(next_words):
token_list = tok.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tok.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)<file_sep>/IMDB_nlp.py
import tensorflow as tf
import pandas as pd
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Dropout, Activation,Flatten, BatchNormalization, Embedding, Bidirectional
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy, sparse_categorical_crossentropy,BinaryCrossentropy
import math
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data()
#print(y_train)
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
'''tokenizer = Tokenizer(num_words= 10000, oov_token= '<OOV>' ) #ITS ALREADY TOKENIZED!
tokenizer.fit_on_texts(x_train)
windex = tokenizer.word_index
sequences = tokenizer.texts_to_sequences(x_train)'''
paddedseq = pad_sequences(x_train, maxlen = 150, truncating= 'post')
#test_sequences = tokenizer.texts_to_sequences(x_test)
test_paddedseq = pad_sequences(x_test, maxlen = 150)
vocab = 88585
emd_dim = 8
max_length = 150
model = Sequential([
Embedding(vocab, emd_dim, input_length=max_length ),
Bidirectional(tf.keras.layers.LSTM(8, return_sequences=True)),
Bidirectional(tf.keras.layers.LSTM(14)),
#Flatten(),
Dense(units = 8, activation='relu'),
Dense(units = 1, activation='sigmoid')
])
model.compile(loss = 'binary_crossentropy', optimizer=Adam(lr = 0.001), metrics = ['accuracy'])
history = model.fit(paddedseq, y_train, batch_size=100, validation_data=(test_paddedseq, y_test), shuffle=True, epochs = 10)
#print(np.unique(paddedseq.flatten())) | 37a7538c5ec41c895127739e1cfb0673798168a6 | [
"Python",
"Text"
] | 11 | Python | TeaCoffeeBreak/Tensorflow_dev_cert | 0321b94f654b8ce502496f7c41a6b5fa69b097a8 | 90d9134b9624aa1a623741dcf80dac9aba515ce3 |
refs/heads/main | <file_sep><?php
namespace ziya\RedisRateLimiter;
use yii\redis\Connection;
use ziya\RedisRateLimiter\exceptions\LimitExceeded;
class Limiter
{
/**
* @var string
*/
private $key_prefix;
/**
* @var int
*/
private $count;
/**
* @var int
*/
private $interval;
/**
* @var Connection
*/
private $redis;
/**
* Limiter constructor.
* @param string $key_prefix
* @param int $count
* @param int $interval
*/
public function __construct(string $key_prefix, int $count, int $interval)
{
$this->key_prefix = $key_prefix;
$this->count = $count;
$this->interval = $interval;
}
public function setConnection(Connection $redis)
{
$this->redis = $redis;
}
/**
* @throws LimitExceeded
*/
public function limit(): void
{
if ($this->redis == null) {
$this->redis = \Yii::$app->redis;
}
$key = "{$this->interval}--{$this->key_prefix}";
$requestCount = (int)$this->redis->get($key);
if ($requestCount >= $this->count) {
throw new LimitExceeded($this->count, $this->interval);
}
$this->updateValue($key, $this->interval);
}
private function updateValue(string $key, int $interval)
{
$requestCount = (int)$this->redis->incr($key);
if ($requestCount === 1) {
$this->redis->expire($key, $interval);
}
return $requestCount;
}
}<file_sep><?php
namespace ziya\RedisRateLimiter\exceptions;
use Throwable;
class LimitExceeded extends \Exception
{
private $count;
private $interval;
/**
* LimitExceeded constructor.
* @param $count
* @param $interval
*/
public function __construct(int $count, int $interval)
{
parent::__construct("Limit of requests exceeded", 429);
$this->count = $count;
$this->interval = $interval;
}
public function getCount(): int
{
return $this->count;
}
public function getInterval(): int
{
return $this->interval;
}
}<file_sep># yii2-redis-rate-limiter
##
**Example code**
```php
use ziya\RedisRateLimiter\exceptions\LimitExceeded;
use ziya\RedisRateLimiter\Limiter;
$key = 'api_request_{user_id}'; //Unique key identifier
$count = 60; // Request count in given amount of time
$interval = 60; //Request interval time
$limiter = new Limiter($key,$count,$interval);
//Set connection is optional. By default it get connection from Yii::$app->redis
// $limiter->setConnection(Yii::$app->redis);
try {
$limiter->limit();
//limit not exceeded
} catch (LimitExceeded $exception) {
//limit exceeded
}
```
| bd073c314ed03798574b4804c6fae103e22c1835 | [
"Markdown",
"PHP"
] | 3 | PHP | ZiyaVakhobov/yii2-redis-rate-limiter | 8c2df839e9d4fd36576aed86d39554b5c2b57839 | 202e386897c49cbc8ca440ca5c2ffbd1359d6a30 |
refs/heads/master | <file_sep># _Ping-Pong_
#### _A basic website that takes a user input number, counts to that number, replaces numbers that meet certain criteria and then outputs the result back to the user. 5.12.17_
#### By _**<NAME>**_
## Description
_This webpage demonstrates my knowledge of basic for loop functions. The user should enter a number into the input field provided and submit the form. Upon submit the program will count up from 1 to the number input replacing numbers evenly divisible by 3 with "Ping", numbers evenly divisible by 5 with "Pong" and numbers evenly divisible by 15 with "Ping-Pong". The generated list should then be ouput back to the user._
## Specs
_If user inputs a non number character they receive a prompt to make sure they input a number with no non number characters. Ex. input: a, Ex. output: Please make sure that you've input a number!_
_When user submits a number this page outputs a list of numbers counting from 1 up to the input number. Ex. input: 12, Ex. output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12._
_When a number is evenly divisible by 3 it is replaced with "Pong". Ex. input: 6, Ex. output: 1, 2, Ping, 4, 5, Ping._
_When a number is evenly divisible by 5 it is replaced with "Pong" Ex. input: 6, Ex. output: 1, 2, Ping, 4, Pong, Ping._
_When a number is evenly divisible by 15 it is replaced with "Ping Pong" Ex. input: 15, Ex. output: 1, 2, Ping, 4, Pong, Ping, 7, 8, Ping, Pong, 11, Ping, 13, 14, Ping Pong.q_
## Setup/Installation Requirements
* _Clone repository to your lacal machine and open index.html with your preferred browser._
* _input a number into the user input and submit_
## Known Bugs
_Spec 1 not passing, Could not evaluate input after parseInt is applied_
## Technologies Used
_Basic HTML, CSS and JavaScript along with Bootstrap and jQuery libraries_
### License
Copyright (c) 2016 **_<NAME>_**
<file_sep>
function arrayNumber(inputNumber) {
var numberArray = [];
// if (inputNumber.charAt(0) !== typeof "number") {
// return alert("nooo");
// }
// console.log(typeof inputNumber);
for(var index = 1; index <= inputNumber; index += 1) {
if (index % 15 === 0) {
numberArray.push("Ping Pong");
} else if (index % 5 === 0) {
numberArray.push("Pong");
} else if (index % 3 === 0) {
numberArray.push("Ping");
} else {
numberArray.push(index);
}
};
return numberArray;
};
$(function() {
$("form#user-input").submit(function(event) {
event.preventDefault();
var inputNumber = parseInt($("input#inputNumber").val());
var results = arrayNumber(inputNumber);
$("input#inputNumber").val("")
$("ul#output").html("");
results.forEach(function(result) {
$("ul#output").append("<li>" + result + "</li>");
});
});
});
| 5467af4fca3ba20aae402e0b97632280c5391800 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Jdmysliwiec/ping-pong | 27365e47ff41deaa6907b57defbc2191bb14c152 | eac93720b3393779ce788e2fa84f33e9388a40a5 |
refs/heads/master | <repo_name>forxn9/SSL_socket<file_sep>/README.md
三个c文件能够实现普通socket到ssl加密socket的转化。
文件里有三个c文件,两个脚本文件,一个makefile。
client.c 为普通客户端程序;
ssl.c 为普通socket到ssl_socket的转化器程序;
ssl_server.c 为ssl加密服务端程序;
make_key.sh 为制作证书和私钥的脚本;
run_server.sh 为ssl_server服务端的执行脚本;
注意:ssl.c编译时会出现两个警告,并不影响程序执行,还没找到解决办法。
./make_key.sh
./ssl
./run_server.sh
./client 127.0.0.1 执行客户端
<file_sep>/makefile
all:clean
@gcc ssl_server.c -o ssl_server -lpthread -lssl -lcrypto
@gcc client.c -o client
@gcc ssl.c -o ssl -lpthread -lssl -lcrypto
clean:
rm -f ssl_server client ssl
<file_sep>/client.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <errno.h>
#include <stdlib.h>
#define MAXLINE 1024
#define SERV_PORT 8848
int main(int argc, char *argv[])
{
char sendbuf[MAXLINE],receivebuf[MAXLINE];
struct sockaddr_in servaddr; //定义sockaddr类型结构体servaddr
int client_sockfd;
int rec_len;
// 判断命令端输入的参数是否正确
if( argc != 2)
{
printf("usage: ./client <ipaddress>\n");
exit(0);
}
// 调用socket函数
if((client_sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");//调用perror函数,该函数会自行打印出错信息
exit(0);
}
//初始化结构体
memset(&servaddr,0,sizeof(servaddr)); //数据初始化-清零
servaddr.sin_family = AF_INET; //设置IPv4通信
servaddr.sin_port = htons(SERV_PORT); //设置服务器端口号
// IP地址转换函数inet_pton,将点分十进制转换为二进制
if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
{
printf("inet_pton error for %s\n",argv[1]);
exit(0);
}
//调用connect函数
if( connect(client_sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))<0)
{
perror("connected failed");
exit(0);
}
//循环发送接收数据,send发送数据,recv接收数据
while(1)
{
printf("send msg to server: \n");
fgets(sendbuf, 1024, stdin);//从标准输入读数据
// 向服务器端发送数据
sendbuf[sizeof(sendbuf)]='\0';
printf("\n=======to server========>>\n");
if( send(client_sockfd, sendbuf, strlen(sendbuf), 0) < 0)
{
printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
exit(0);
}
// 接受服务器端传过来的数据
if((rec_len = recv(client_sockfd,receivebuf, MAXLINE,0)) == -1)
{
perror("recv error");
exit(1);
}
printf("\nResponse from server: \n");
printf("%s\n<<======from server=======\n",receivebuf);
}
//关闭套接字
close(client_sockfd);
return 0;
}
<file_sep>/ssl_server.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <pthread.h>
#define MAXBUF 1024
void *thread_worker(void *arg);
int main(int argc, char **argv)
{
int sockfd, new_fd;
socklen_t len;
struct sockaddr_in my_addr, their_addr;
unsigned int myport, lisnum;
char buf[MAXBUF + 1];
SSL_CTX *ctx;
int opt = 1;
if (argv[1])
myport = atoi(argv[1]);
else
myport = 7838;
if (argv[2])
lisnum = atoi(argv[2]);
else
lisnum = 2;
/* SSL 库初始化 */
SSL_library_init();
/* 载入所有 SSL 算法 */
OpenSSL_add_all_algorithms();
/* 载入所有 SSL 错误消息 */
SSL_load_error_strings();
/* 以 SSL V2 和 V3 标准兼容方式产生一个 SSL_CTX ,即 SSL Content Text */
ctx = SSL_CTX_new(SSLv23_server_method());
/* 也可以用 SSLv2_server_method() 或 SSLv3_server_method() 单独表示 V2 或 V3标准 */
if (ctx == NULL) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 载入用户的数字证书, 此证书用来发送给客户端。 证书里包含有公钥 */
if (SSL_CTX_use_certificate_file(ctx, argv[4], SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 载入用户私钥 */
if (SSL_CTX_use_PrivateKey_file(ctx, argv[5], SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 检查用户私钥是否正确 */
if (!SSL_CTX_check_private_key(ctx)) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 开启一个 socket 监听 */
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket failure");
exit(1);
}
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = PF_INET;
my_addr.sin_port = htons(myport);
if (argv[3])
my_addr.sin_addr.s_addr = inet_addr(argv[3]);
else
my_addr.sin_addr.s_addr = INADDR_ANY;
setsockopt( sockfd, SOL_SOCKET,SO_REUSEADDR, (const void *)&opt, sizeof(opt) );
if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) < 0)
{
perror("bind failure");
exit(1);
}
if (listen(sockfd, lisnum) < 0)
{
perror("listen failure");
exit(1);
}
printf("Start SSL accept\n");
while (1)
{
SSL *ssl;
pthread_t tid;
len = sizeof(struct sockaddr);
printf("SSL Server start new accept\n");
/* 等待客户端连上来 */
if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &len)) == -1)
{
perror("accept\n");
exit(errno);
}
else
{
printf("SSL server: got connection from %s, port %d, socket %d\n",
inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd);
}
/* 基于 ctx 产生一个新的 SSL */
ssl = SSL_new(ctx);
/* 将连接用户的 socket 加入到 SSL */
SSL_set_fd(ssl, new_fd);
/* 建立 SSL 连接 */
if (SSL_accept(ssl) == -1) {
perror("accept\n");
close(new_fd);
break;
}
else
{
printf("Start create thread worker\n");
pthread_create(&tid, NULL,thread_worker, (void *)ssl);
// pthread_join(tid, NULL);
}
printf("Thread worker create over\n");
}
/* 关闭监听的 socket */
close(sockfd);
/* 释放 CTX */
SSL_CTX_free(ctx);
return 0;
}
void *thread_worker(void *arg)
{
char buf[MAXBUF];
socklen_t len;
SSL *ssl=(SSL *)arg;
while(1)
{
bzero(buf, MAXBUF );
len = SSL_read(ssl, buf, MAXBUF);
buf[strlen(buf)-1]='\0';
if (len > 0)
{
printf("memsage received successful! total %d bytes data received\n%s\n=======from client=======\n", len,buf);
}
else
{
printf ("receive memsage failure!error number %d,error reason:'%s'\n", errno, strerror(errno));
}
bzero(buf, MAXBUF );
printf("please input data to client:\n");
fgets(buf,MAXBUF, stdin);
buf[strlen(buf)-1]='\0';
len = SSL_write(ssl, buf, strlen(buf));
if (len <= 0)
{
printf
("memsage'%s'send failure!error number:%d,error reason:'%s'\n", buf, errno, strerror(errno));
SSL_shutdown(ssl);
SSL_free(ssl);
}
else
{
printf("memsage send successful! total send %d bytes data!\n %s\n=======to client========\n", len,buf);
}
}
}
<file_sep>/ssl.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
void ShowCerts (SSL* ssl);
void *thread_worker(void *arg);
int main(int argc, char **argv)
{
int socket_fd, connect_fd = -1;
struct sockaddr_in serv_addr;
pthread_t tid;
int opt = 1;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if(socket_fd < 0 )
{
printf("create socket failure: %s\n", strerror(errno));
return -1;
}
printf("socket create fd[%d]\n", socket_fd);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8848);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
setsockopt( socket_fd, SOL_SOCKET,SO_REUSEADDR, (const void *)&opt, sizeof(opt) );//地址复用
if( bind(socket_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0 )
{
printf("create socket failure: %s\n", strerror(errno));
return -2;
}
printf("socket bind ok\n", socket_fd);
listen(socket_fd, 13);
printf("listen fd ok\n", socket_fd);
while(1)
{
printf("waiting for client's connection......\n", socket_fd);
connect_fd = accept(socket_fd, NULL, NULL);
if(connect_fd < 0)
{
printf("accept new socket failure: %s\n", strerror(errno));
return -2;
}
printf("accept newfd= %d, start create new worker\n", connect_fd);
pthread_create (&tid, NULL,thread_worker, (void *)connect_fd);
}
close(socket_fd);
}
void *thread_worker(void *arg)
{
char buf[1024];
int cli_fd=(int)arg;
int sockfd,len;
struct sockaddr_in dest;
SSL_CTX *ctx;//定义两个结构体数据https://www.cnblogs.com/274914765qq/p/4513236.html
SSL *ssl;
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ctx=SSL_CTX_new(SSLv23_client_method());
if(ctx==NULL)
{
ERR_print_errors_fp(stdout);// 将错误打印到FILE中
exit(1);
}
//创建socket用于tcp通信
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
exit(errno);
}
printf("socket create ok\n");
memset(&dest,0,sizeof(struct sockaddr_in));
dest.sin_family=AF_INET;
dest.sin_port=htons(7838);//ascii to integer 字符串转化为整形数
//inet_aton 将字符串IP地址转化为32位的网络序列地址
if(inet_aton("127.0.0.1",(struct in_addr *)&dest.sin_addr.s_addr)==0)
{
printf("error ");
exit(errno);
}
//连接服务器
printf("socket start connect to SSL server\n");
if(connect(sockfd,(struct sockaddr*)&dest,sizeof(dest))!=0)
{
perror("Connect ");
exit(errno);
}
printf("socket server connected\n");
//基于ctx产生一个新的ssl,建立SSL连接
ssl=SSL_new(ctx);
SSL_set_fd(ssl,sockfd);
if(SSL_connect(ssl)==-1)
ERR_print_errors_fp(stderr);
else
{
printf("connect with %s encryption\n",SSL_get_cipher(ssl));
ShowCerts(ssl);
}
printf("SSL connect to server ok\n");
while(1)
{
memset(buf, 0, sizeof(buf));
read(cli_fd, buf, sizeof(buf));
len=SSL_write(ssl,buf,strlen(buf));
if(len<0)
printf("memsage send failure");
else
printf("SSL_write successful\n==================>>\n%s\n=================>>\n",buf);
memset(buf,0,sizeof(buf));
SSL_read(ssl,buf,sizeof(buf));
printf("SSL_read ok\n");
len=write(cli_fd,buf,len);
if(len>0)
{
printf("write successful\n<<=================\n%s\n<<=================\n",buf);
memset(buf,0,sizeof(buf));
}
}
goto finish;
finish:
SSL_shutdown(ssl);
SSL_free(ssl);
close(sockfd);
SSL_CTX_free(ctx);
return 0;
}
void ShowCerts (SSL* ssl)
{
X509 *cert;
char *line;
cert=SSL_get_peer_certificate(ssl);
if(cert !=NULL){
printf("数字证书信息:\n");
line=X509_NAME_oneline(X509_get_subject_name(cert),0,0);
printf("证书:%s\n",line);
free(line);
line=X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
printf("颁发者:%s\n",line);
free(line);
X509_free(cert);
}else
printf("无证书信息!\n");
}
| d64d9c2c52211b57f3b2c3bb89152dbd8c04bcef | [
"Markdown",
"C",
"Makefile"
] | 5 | Markdown | forxn9/SSL_socket | 8c814748d1a4cda6e1c156ccf31079e1bdd3fa6e | 488653bdf74dc5bc3cf0a9be28676117bb1a46b0 |
refs/heads/main | <file_sep># pageRestaurante
Second website I'm developing using HTML and CSS technologies for the purpose of learning.
Segundo website que estou desenvolvendo como forma de aprendizado de HTML e CSS
| a7e33e7ce4b106e5884eff76e4ce18b2b49f36c6 | [
"Markdown"
] | 1 | Markdown | igorovisk/pageRestaurante | 712517272021a687dfe92c2915549270f5a67c86 | 1ffba56b5c90838c44fec89b1e56b6d5cad9ef86 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\mail\newMail;
class mailController extends Controller
{
public function send()
{
Mail::send(new newMail());
}
public function emial()
{
return view('email');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class Pagination extends Controller
{
public function users() {
$users = User::paginate(3);
return view('pagination', compact('users'));
}
}
| 6a8badda9da9586c05ede14546ff9b0d0b099deb | [
"PHP"
] | 2 | PHP | DmitriyBaran/laravel_loc | 65954b1a776c6f078817587049adc5b1f090e665 | 6a8c5bc292aa9a20a216644d2cf799f8517f5d3c |
refs/heads/master | <repo_name>thabear/intern-hw-example<file_sep>/src/FilterOption.js
import React from "react";
export default class FilterOption extends React.Component {
render() {
return (
<button
onClick={(e) => this.props.onFilterOptionClick(e)}
>
{this.props.name}
</button>
);
}
}<file_sep>/src/FilterOptionsContainer.js
import React from 'react';
import FilterOption from './FilterOption';
export default class FilterOptionsContainer extends React.Component {
render() {
return (
<div>
<FilterOption
onFilterOptionClick={this.props.onFilterOptionClickHandler}
name="A-Z"
/>
<FilterOption
onFilterOptionClick={this.props.onFilterOptionClickHandler}
name="Z-A"
/>
<FilterOption
onFilterOptionClick={this.props.onFilterOptionClickHandler}
name="Random"
/>
<FilterOption
onFilterOptionClick={this.props.onFilterOptionClickHandler}
name="Chronological"
/>
<FilterOption
onFilterOptionClick={this.props.onFilterOptionClickHandler}
name="Reverse Chronological"
/>
<FilterOption
onFilterOptionClick={this.props.onFilterOptionClickHandler}
name="Priority"
/>
</div>
);
}
}<file_sep>/src/AddListItemForm.js
import React from 'react';
import "./AddListItemForm.css";
const AddListItemForm = (props) => {
return (
<div>
<form onSubmit={props.onAddItemClick}>
<input name="fName" placeholder="<NAME>" />
<input name="date" placeholder="YYYY-MM-DD" />
<input name="priority" placeholder="Low, Med, or High" />
<input type="submit" value="Add Item" />
</form>
</div>
);
}
export default AddListItemForm;<file_sep>/src/AppContainer.js
import {connect} from 'react-redux';
import ACTIONS from './action.js';
import App from './App.js';
const mapStateToProps = state => ({
nameList: state.nameList,
highestIndex: state.highestIndex,
quote: state.quote
});
const mapDispatchToProps = dispatch => ({
doneItem: (itemId) => dispatch(ACTIONS.doneItem(itemId)),
addItem: (newNameList, newIndex) => dispatch(ACTIONS.addItem(newNameList, newIndex))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);<file_sep>/src/action.js
const TYPES = {
BEGIN_DONE_ITEM: "BEGIN_DONE_ITEM",
SUCCESS_DONE_ITEM: "SUCCESS_DONE_ITEM",
ADD_ITEM: "ADD_ITEM"
}
const beginDoneItem = (id) => ({
type: TYPES.BEGIN_DONE_ITEM,
payload: id
});
const successDoneItem = (quote) => ({
type: TYPES.SUCCESS_DONE_ITEM,
payload: quote
})
const addItem = (nameList, highestIndex) => ({
type: TYPES.ADD_ITEM,
payload: {
nameList,
highestIndex
}
});
function doneItem(itemId) {
// fetch('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1')
// .then((response) => {
// return response.json();
// })
// .then((quote) => {
// return JSON.stringify(quote[0].content);
// });
console.log(itemId);
return (dispatch) => {
dispatch(beginDoneItem(itemId));
// let response = await fetch('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1');
// let quote = await response.json();
fetch('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', {cache: 'no-cache'})
.then((response) => {
return response.json();
})
.then((quote) => {
dispatch(successDoneItem(JSON.stringify(quote[0].content)));
});
// return (dispatch) => {
// console.log('here')
// dispatch(successDoneItem(quote[0].content))
// };
}
}
export default {
doneItem,
addItem,
TYPES
}; | fb2492fda6381483cf71042d5836f86a5519dea0 | [
"JavaScript"
] | 5 | JavaScript | thabear/intern-hw-example | 058baf2b9986480fe5004d4524b4b8e03bd58a21 | 8f0fc05bafc9e14047aaedc80d5777761bcecce1 |
refs/heads/master | <file_sep>package execmd
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewSSHCmd(t *testing.T) {
assert := assert.New(t)
const sshHost = "localhost"
srv := NewSSHCmd(sshHost)
res, err := srv.Run("VAR=world; echo Hello stdout $VAR; echo Hello stderr $VAR >&2")
assert.NoError(err)
assert.EqualValues("Hello stdout world\n", res.Stdout.String())
assert.EqualValues("Hello stderr world\n", res.Stderr.String())
res, err = srv.Run("i-am-not-exist")
assert.Error(err)
assert.Contains(res.Stderr.String(), "i-am-not-exist")
srv.Cwd = <PASSWORD>"
res, err = srv.Run("pwd")
assert.NoError(err)
assert.EqualValues(res.Stdout.String(), "/tmp\n", "no working dir change")
srv = NewSSHCmd(sshHost)
srv.Cwd = <PASSWORD>"
res, err = srv.Run("pwd")
assert.Error(err)
assert.Contains(res.Stderr.String(), "/i-am-nowhere", "no error when nonexisting working dir change")
}
<file_sep>package execmd
import (
"bytes"
"io"
"log"
"strings"
)
/*
pStream is a writer wrapper which:
1. copy input stream to `data` field (if `saveData` = true)
2. split input stream into lines and write them to `logger` with `prefix`
See: https://github.com/kvz/logstreamer
*/
type pStream struct {
Logger *log.Logger
buf *bytes.Buffer
prefix string
saveData bool
data *bytes.Buffer
}
func newPStream(logger *log.Logger, prefix string, saveData bool) *pStream {
return &pStream{
Logger: logger,
buf: bytes.NewBuffer([]byte("")),
prefix: prefix,
saveData: saveData,
data: bytes.NewBuffer([]byte("")),
}
}
func (p *pStream) Write(b []byte) (n int, err error) {
if n, err = p.buf.Write(b); err != nil {
return
}
err = p.OutputLines()
return
}
func (p *pStream) Close() error {
if err := p.Flush(); err != nil {
return err
}
p.buf = bytes.NewBuffer([]byte(""))
return nil
}
func (p *pStream) Flush() error {
var b []byte
if _, err := p.buf.Read(b); err != nil {
return err
}
p.out(string(b))
return nil
}
func (p *pStream) OutputLines() error {
for {
line, err := p.buf.ReadString('\n')
if len(line) > 0 {
if strings.HasSuffix(line, "\n") {
p.out(line)
} else {
// put back into buffer, it's not a complete line yet
// Close() or Flush() have to be used to flush out
// the last remaining line if it does not end with a newline
if _, err := p.buf.WriteString(line); err != nil {
return err
}
}
}
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return nil
}
func (p *pStream) FlushData() {
p.data.Reset()
}
func (p *pStream) Get() *bytes.Buffer {
return p.data
}
func (p *pStream) out(str string) {
if len(str) < 1 {
return
}
if p.saveData {
p.data.WriteString(str)
}
str = p.prefix + str
p.Logger.Print(str)
}
<file_sep>package execmd
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestColor(t *testing.T) {
str := "i am green"
green := colorOK(str)
assert.Contains(t, green, str)
}
<file_sep>package execmd
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewClusterSSHCmd(t *testing.T) {
assert := assert.New(t)
sshHosts := []string{"localhost", "127.0.0.1"}
cluster := NewClusterSSHCmd(sshHosts)
// parallel
res, err := cluster.Run("VAR=world; echo Parallel stdout $VAR; echo Parallel stderr $VAR >&2")
assert.NoError(err)
assert.EqualValues(len(sshHosts), len(res), "Run: number of results not equals to hosts number")
for i := range res {
assert.EqualValues("Parallel stdout world\n", res[i].Res.Stdout.String())
assert.EqualValues("Parallel stderr world\n", res[i].Res.Stderr.String())
}
res, err = cluster.Run("give-me-error")
assert.Error(err)
assert.EqualValues(len(sshHosts), len(res), "Run with error: number of results not equals to hosts number")
for i := range res {
assert.Contains(res[i].Res.Stderr.String(), "give-me-error")
}
// serial
res, err = cluster.RunOneByOne("VAR=world; echo Serial stdout $VAR; echo Serial stderr $VAR >&2")
assert.NoError(err)
assert.EqualValues(len(sshHosts), len(res), "RunOneByOne: number of results not equals to hosts number")
for i := range res {
assert.EqualValues("Serial stdout world\n", res[i].Res.Stdout.String())
assert.EqualValues("Serial stderr world\n", res[i].Res.Stderr.String())
}
cluster.StopOnError = true
res, err = cluster.RunOneByOne("give-me-error")
assert.Error(err)
assert.EqualValues(1, len(res), "RunOneByOne with stop on error: more than one result returned")
assert.Contains(res[0].Res.Stderr.String(), "give-me-error")
h := []string{}
h = append(h, sshHosts[0], sshHosts[0])
twinCluster := NewClusterSSHCmd(h)
res, err = twinCluster.RunOneByOne("FILE=.dp_remove_me; [[ -f $FILE ]] || (touch $FILE; echo 1) && (echo 2; rm $FILE)")
assert.NoError(err)
for i := range res {
assert.EqualValues("1\n2\n", res[i].Res.Stdout.String())
}
// check results are saved between executions
res1, err1 := cluster.Run("echo res1")
assert.NoError(err1)
res2, err2 := cluster.Run("echo res2")
assert.NoError(err2)
assert.EqualValues(len(sshHosts), len(res), "number of results not equals to hosts number")
for i := range res1 {
assert.EqualValues("res1\n", res1[i].Res.Stdout.String())
assert.EqualValues("res2\n", res2[i].Res.Stdout.String())
}
// check cwd changing
cluster.Cwd = "/tmp"
res, err = cluster.Run("pwd")
assert.NoError(err)
for i := range res {
assert.EqualValues("/tmp\n", res[i].Res.Stdout.String(), "no working dir change")
}
}
<file_sep>/*
Wrapper for https://golang.org/pkg/os/exec/ to invoke command in shell,
pipe stdout, stderr to console with prefixes,
record output buffers
Copyright(c) 2018 mink0
*/
package execmd
import (
"bytes"
"fmt"
"log"
"os"
"os/exec"
)
// Path to system shell binary
// Could be overridden by setting `SHELL` env variable
var shellPathList = []string{os.Getenv("SHELL"), "bash", "sh"}
// Cmd is wrapper struct around exec.Cmd
// Stream buffers will be saved with Record[Stdout|Stderr] == true
// Mute options turns off console output
type Cmd struct {
ShellPath string
Interactive bool
LoginShell bool
RecordStdout bool
RecordStderr bool
MuteStdout bool
MuteStderr bool
MuteCmd bool
PrefixStdout string // printing prefixes
PrefixStderr string //
PrefixCmd string //
Cmd *exec.Cmd // os.Exec instance
}
// CmdRes resulting struct
type CmdRes struct {
Stdout *bytes.Buffer
Stderr *bytes.Buffer
}
// NewCmd initializes Cmd with defaults
func NewCmd() *Cmd {
cmd := Cmd{
RecordStdout: true,
RecordStderr: true,
PrefixCmd: "$ ",
PrefixStdout: colorOK("> "),
PrefixStderr: colorErr("@err "),
}
// try to find shell binary
if shellPath, err := findPath(shellPathList); err == nil {
cmd.ShellPath = shellPath
}
return &cmd
}
// Wait is a exec.Wait wrapper with buffer flushes
func (c *Cmd) Wait() (err error) {
err = c.Cmd.Wait()
// flush last line
c.Cmd.Stderr.(*pStream).Close()
c.Cmd.Stdout.(*pStream).Close()
return
}
// Run is exec.Run() wrapper: runs command and blocking wait for result
func (c *Cmd) Run(command string) (res CmdRes, err error) {
if res, err = c.Start(command); err != nil {
return
}
err = c.Wait()
return
}
// Start is exec.Start() wrapper with system shell and output buffers initialization
func (c *Cmd) Start(command string) (res CmdRes, err error) {
args := []string{}
if c.Interactive {
args = append(args, "-i")
}
if c.LoginShell {
args = append(args, "-l")
}
args = append(args, "-c", command)
c.Cmd = exec.Command(c.ShellPath, args...)
// FIXME: rewrite to use raw buffers only when mute == true
stdoutLogFile := log.New(os.Stdout, "", 0)
if c.MuteStdout {
stdoutLogFile = log.New(bytes.NewBuffer([]byte("")), "", 0)
}
stderrLogFile := log.New(os.Stderr, "", 0)
if c.MuteStderr {
stderrLogFile = log.New(bytes.NewBuffer([]byte("")), "", 0)
}
stdoutStream := newPStream(stdoutLogFile, c.PrefixStdout, c.RecordStdout)
c.Cmd.Stdout = stdoutStream
stderrStream := newPStream(stderrLogFile, c.PrefixStderr, c.RecordStderr)
c.Cmd.Stderr = stderrStream
if c.Interactive {
c.Cmd.Stdin = os.Stdin
}
if !c.MuteCmd {
fmt.Printf("%s%s\n", c.PrefixCmd, colorStrong(command))
}
err = c.Cmd.Start()
res.Stdout = stdoutStream.Get()
res.Stderr = stderrStream.Get()
return
}
func findPath(paths []string) (path string, err error) {
for _, p := range paths {
path, err = exec.LookPath(p)
if err == nil {
break
}
}
return
}
<file_sep>// Copyright(c) 2018 by Mink0. All rights reserved.
/*
Package execmd is a Golang library providing a simple interface to shell commands execution
Features
- execute commands in system shell
- you could use shell variables, pipes, redirections
- execute remote shell commands
- interface is based on os/exec
- realtime `stdout` and `stderr` output with fancy colors and prefixes
- remote commands execution is implemented by wrapping standart OpenSSH client
- all your ssh configuration (including ssh agent forwarding) works
- parallel and serial remote command execution supported
Documentation
See https://github.com/mink0/exec-cmd/blob/master/README.md for full documentation
*/
package execmd
<file_sep>package execmd
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestInteractive(t *testing.T) {
assert := assert.New(t)
cmd := NewCmd()
cmd.Interactive = true
res, err := cmd.Run("echo Hello stdout $USER; echo Hello stderr $USER >&2")
assert.NoError(err)
assert.EqualValues(res.Stdout.String(), "Hello stdout "+os.Getenv("USER")+"\n")
}
func TestNewCmd(t *testing.T) {
assert := assert.New(t)
cmd := NewCmd()
res, err := cmd.Run("echo Hello stdout $USER; echo Hello stderr $USER >&2")
assert.NoError(err)
assert.EqualValues(res.Stdout.String(), "Hello stdout "+os.Getenv("USER")+"\n")
assert.EqualValues(res.Stderr.String(), "Hello stderr "+os.Getenv("USER")+"\n")
cmd = NewCmd()
res, err = cmd.Run("i-am-not-exist")
assert.Error(err)
assert.Contains(res.Stderr.String(), "i-am-not-exist")
}
<file_sep>module github.com/mink0/exec-cmd.git
go 1.14
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fatih/color v1.13.0
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/pkg/errors v0.9.1
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
golang.org/x/sys v0.0.0-20220405052023-b1e9470b6e64 // indirect
)
<file_sep>/*
Wrapper for Cmd to invoke ssh commands via OpenSSH binary
Copyright(c) 2018 mink0
*/
package execmd
import (
"os"
"strings"
"github.com/pkg/errors"
)
// SSHCmd is a wrapper on Cmd
type SSHCmd struct {
Cmd *Cmd
Interactive bool
SSHExecutable string
Host string
User string
Port string
KeyPath string
Cwd string
}
// NewSSHCmd initializes SSHCmd with defaults
func NewSSHCmd(host string) *SSHCmd {
ssh := SSHCmd{
Host: host,
SSHExecutable: "ssh",
}
ssh.Cmd = NewCmd()
ssh.Cmd.PrefixStdout = color(host) + " "
ssh.Cmd.PrefixStderr = color(host) + colorErr("@err ")
// Path to ssh binary could be overridden by setting `SSH_EXECUTABLE` env variable
if sshEnvExec, ok := os.LookupEnv("SSH_EXECUTABLE"); ok {
ssh.SSHExecutable = sshEnvExec
}
// User detect from user@host
if arr := strings.Split(host, "@"); len(arr) == 2 {
ssh.User = arr[0]
ssh.Host = arr[1]
}
return &ssh
}
// Wait wraps Cmd.Wait()
func (s *SSHCmd) Wait() error {
return s.Cmd.Wait()
}
// Run wraps Cmd.Run()
func (s *SSHCmd) Run(command string) (res CmdRes, err error) {
if res, err = s.Start(command); err != nil {
return
}
err = s.Wait()
return
}
// Start wraps Cmd.Start() with ssh invocation
func (s *SSHCmd) Start(command string) (res CmdRes, err error) {
if s.Host == "" {
err = errors.New("no host to run ssh command")
return
}
sshArgs := s.warpInSSH(command)
res, err = s.Cmd.Start(strings.Join(sshArgs, " "))
return
}
// transform `command` into ssh-compatible argument string
func (s *SSHCmd) warpInSSH(command string) (sshArgs []string) {
sshArgs = append(sshArgs, s.SSHExecutable)
hostWithUser := s.Host
if s.User != "" {
hostWithUser = s.User + "@" + s.Host
}
sshArgs = append(sshArgs, hostWithUser)
if s.Interactive || strings.Contains(command, "sudo") {
sshArgs = append(sshArgs, "-tt")
s.Cmd.Interactive = true
}
if s.Port != "" {
sshArgs = append(sshArgs, "-p", s.Port)
}
if s.KeyPath != "" {
sshArgs = append(sshArgs, "-i", s.KeyPath)
}
if s.Cwd != "" {
command = "cd " + s.Cwd + " && " + command
}
// escape single quotes for shell encapsulation
sshArgs = append(sshArgs, "'"+strings.Replace(command, "'", "'\\''", -1)+"'")
return
}
<file_sep>package execmd
// ClusterSSHCmd is a wrapper on SSHCmd
type ClusterSSHCmd struct {
Cmds []ClusterCmd
Cwd string
StopOnError bool
}
// ClusterCmd wraps SSHCmd and preserves host name and saves error from .start() for .Wait() method
type ClusterCmd struct {
SSHCmd SSHCmd
Host string
}
// ClusterRes contains results of command execution
type ClusterRes struct {
Host string
Err error
Res CmdRes
}
// NewClusterSSHCmd inits ClusterSSHCmd with defaults
func NewClusterSSHCmd(hosts []string) *ClusterSSHCmd {
c := ClusterSSHCmd{}
c.StopOnError = false
c.Cmds = make([]ClusterCmd, len(hosts))
for i, host := range hosts {
c.Cmds[i].Host = host
c.Cmds[i].SSHCmd = *NewSSHCmd(host)
}
return &c
}
// Loops through the hosts and runs .Start() or .Run() method (depends on `parallel` flag)
func (c *ClusterSSHCmd) start(command string, parallel bool) ([]ClusterRes, error) {
results := make([]ClusterRes, len(c.Cmds))
for i, cmd := range c.Cmds {
// set cluster common variables
if c.Cwd != "" {
cmd.SSHCmd.Cwd = c.Cwd
}
results[i].Host = cmd.Host
// no need to implement interfaces here, we always have only: .Start() and .Run() methods
exec := cmd.SSHCmd.Start
if !parallel {
exec = cmd.SSHCmd.Run
}
results[i].Res, results[i].Err = exec(command)
if c.StopOnError && results[i].Err != nil {
return results[:i+1], results[i].Err
}
}
return results, nil
}
// Wait calls SSHCmd.Wait for the list of Cmds []ClusterCmd
// you should access `.Cmds` to see exact where error occurs
func (c *ClusterSSHCmd) Wait() (err error) {
for _, cmd := range c.Cmds {
err = cmd.SSHCmd.Wait()
if c.StopOnError && err != nil {
return
}
}
return
}
// Run executes command in parallel and waits for the results. Command starts simultaneously at each of the hosts.
func (c *ClusterSSHCmd) Run(command string) (results []ClusterRes, err error) {
if results, err = c.Start(command); err != nil {
return
}
err = c.Wait()
return
}
// RunOneByOne executes command in series: run at first host, then run at second host, then...
func (c *ClusterSSHCmd) RunOneByOne(command string) (results []ClusterRes, err error) {
return c.start(command, false)
}
// Start executes command in parallel, no wait for the results
func (c *ClusterSSHCmd) Start(command string) (results []ClusterRes, err error) {
return c.start(command, true)
}
<file_sep>package execmd
import (
"hash/fnv"
fcolor "github.com/fatih/color"
)
var defaultColors = []fcolor.Attribute{
fcolor.FgCyan,
fcolor.FgYellow,
fcolor.FgMagenta,
fcolor.FgBlue,
fcolor.FgHiGreen,
fcolor.FgHiYellow,
fcolor.FgHiBlue,
fcolor.FgHiMagenta,
fcolor.FgHiCyan,
}
func color(str string) (coloredStr string) {
hash := fnv.New32a()
hash.Write([]byte(str))
colorAtrr := defaultColors[hash.Sum32()%uint32(len(defaultColors))]
coloredStr = fcolor.New(colorAtrr).SprintFunc()(str)
return
}
func colorErr(str string) string {
return fcolor.New(fcolor.FgRed).SprintFunc()(str)
}
func colorOK(str string) string {
return fcolor.New(fcolor.FgGreen).SprintFunc()(str)
}
func colorStrong(str string) string {
return fcolor.New(fcolor.Bold).SprintFunc()(str)
}
<file_sep># execmd
`execmd` is a simple Go package providing an interface for shell command execution.
It wraps [exec](https://golang.org/pkg/os/exec/) to invoke command in a system shell and redirects multiple `stdout`, `stderr` into a single `stdout` using prefixes. It supports both local and remote commands execution, remote commands are implemented by invoking [OpenSSH](https://www.openssh.com/) binary.
## Key features
* local and remote commands execution
* simple interface similar to [exec](https://golang.org/pkg/os/exec/)
* shell environment variables, pipes and redirection are supported
* system ssh configuration is supported (including `ssh-agent` forwarding)
* you can run single command on multiple hosts (for cluster operations): parallel and serial execution is supported
* real time `stdout` and `stderr` output with fancy coloring and prefixing
* output buffers could be captured to access them programmatically
## Installation
* using go modules:
go mod vendor
* using `go get`:
go get -u "github.com/mink0/exec-cmd"
Then import `exec-cmd` in your application:
```go
import "github.com/mink0/exec-cmd"
```
## Examples
### Local command execution
```go
package main
import "github.com/mink0/exec-cmd"
func main() {
execmd.NewCmd().Run("ps aux | grep go")
}
```
```sh
$ ps aux | grep go
> mink0 9203 0.6 0.0 558434044 2220 s001 S+ 3:11PM 0:00.01 ./go-dp
> mink0 1934 0.0 0.2 558459904 15744 ?? S 11:20AM 0:01.71 /Users/mink0/go/bin/gocode -s -sock unix -addr 127.0.0.1:37373
```
### Remote command execution
```go
package main
import "github.com/mink0/exec-cmd"
func main() {
remote := execmd.NewSSHCmd("192.168.1.194")
res, err := remote.Run(`VAR="$(hostname)"; echo "hello $VAR"`)
if err == nil {
fmt.Printf("saved output: %s", res.Stdout)
}
}
```
```sh
$ /usr/bin/ssh 192.168.1.194 'VAR="$(hostname)"; echo "hello $VAR"'
192.168.1.194 hello host-01.local
saved output: hello host-01.local
```
### Remote cluster command execution
```go
package main
import "github.com/mink0/exec-cmd"
cluster := execmd.NewClusterSSHCmd([]string{"host-01", "host-02", "host-03"})
func main() {
// execute in parallel order
res, err := cluster.Run(`VAR=std; echo "Hello $VAR out"; echo Hello $VAR err >&2`)
if err == nil {
fmt.Printf("saved output: %v", res)
}
// execute in serial order
res, err = cluster.RunOneByOne(`VAR=std; echo "Hello $VAR out"`)
}
```
Parallel execution results:
```sh
$ /usr/bin/ssh host-01 'VAR=std; echo "Hello $VAR out"; echo "Hello $VAR err" >&2'
$ /usr/bin/ssh host-02 'VAR=std; echo "Hello $VAR out"; echo "Hello $VAR err" >&2'
$ /usr/bin/ssh host-03 'VAR=std; echo "Hello $VAR out"; echo "Hello $VAR err" >&2'
host-01 Hello std out
host-01@err Hello std err
host-03@err Hello std err
host-03 Hello std out
host-02 Hello std out
host-02@err Hello std err
```
Serial execution results:
```sh
$ /usr/bin/ssh host-01 'VAR=std; echo "Hello $VAR out"; echo Hello $VAR err >&2'
host-01 Hello std out
host-01@err Hello std err
$ /usr/bin/ssh host-02 'VAR=std; echo "Hello $VAR out"; echo Hello $VAR err >&2'
host-02@err Hello std err
host-02 Hello std out
$ /usr/bin/ssh host-03 'VAR=std; echo "Hello $VAR out"; echo Hello $VAR err >&2'
host-03@err Hello std err
host-03 Hello std out
```
## Testing
You should enable `SSH` server locally and add your personal ssh key to `known_hosts` to avoid password prompting:
```sh
ssh-copy-id 127.0.0.1
ssh-copy-id localhost
```
Run tests:
go test
| 74f30166a3caf0a6befdb617462cc4535fbfe79d | [
"Markdown",
"Go Module",
"Go"
] | 12 | Go | mink0/exec-cmd | 8eab3559541cd66f7dafd53577bc873b123d9214 | 84223677a2b68d07b1080a13aace848dac65bf3d |
refs/heads/master | <repo_name>wgy504/BIRMM-RTU100-GPRS<file_sep>/User/main.c
/**
******************************************************************************
* @file main.c
* @author casic 203
* @version V1.0
* @date 2016-07-27
* @brief
* @attention
*
******************************************************************************
*/
#include "stm32f10x.h"
#include "stdlib.h"
#include "time.h"
#include "misc.h"
#include "stm32f10x_it.h"
#include "bsp_usart.h"
#include "bsp_TiMbase.h"
#include "modbus.h"
#include "bsp_SysTick.h"
#include "string.h"
#include "gprs.h"
#include "bsp_rtc.h"
#include "bsp_date.h"
#include "WatchDog.h"
#include "AiderProtocol.h"
#include "SPI_Flash.h"
#include "common.h"
#include "DS2780.h"
#include "test.h"
#include "sensor-adc.h"
#include "SensorInit.h"
#define COLLECT_NUM 10 //一次采集需要采集的数据
#define PREPARE_TIME 180 //传感器需要预热180S
#define SENSOR_COLLECT_TIME 0.5 //两组数据之间的采集间隔
struct rtc_time systmtime; //RTC时钟设置结构体
uint32_t Start_time; //传感器预热开始时间
uint32_t End_time; //传感器预热结束时间
struct Sensor_Set DeviceConfig ={0x00}; //配置信息结构体
struct SMS_Config_RegPara ConfigData ={0x00}; //与FLASH交互的结构体,方便在系统进入休眠模式之前写入FLASH
uint16_t WWDOG_Feed =0x1FFF; //窗口看门狗复位周期为:XX*1.8s = 7.6min
char SendData_Flag=0; //发送数据成功标志位,发送成为为1,不成功为0;
u8 ReadData_flag=0; //读取传感器成功标志位,成功为1,失败为0;
char TcpConnect_Flag=0; //TCP连接成功标志位,连接成功为1,不成功为0;
char PowerOffReset =0; //掉电重启标志位
u8 Send_Request_flag=0; //发送数据至上位机后收到反馈
uint8_t LiquidDataSend_Flag =0; //数据发送完成标志位
uint8_t SensorCollectNumber=0; //一次上报需要进行数据采集的数量 采集数量=上报周期/采集周期
uint8_t DataCollectCount ; //数据采集计数器 每次初始化需要读取该值,采集完数据后写入FLASH
struct SenserData PerceptionData; //传感器数据 “u16采集时间 float传感器数据 u8采集数量”
char Usart1_recev_buff[300] ={'\0'}; //USART1接收缓存
uint16_t Usart1_recev_count =0; //USART1发送计数器
extern char Usart3_recev_buff[1000];
extern uint16_t Usart3_recev_count;
extern uint8_t CSQ_OK ; //信号质量标志变量
uint8_t DMA_UART3_RECEV_FLAG =0; //USART3 DMA接收标志变量
extern uint8_t DMA_USART3_RecevBuff[RECEIVEBUFF_SIZE];
extern struct DMA_USART3_RecevConfig DMA_USART3_RecevIndicator;
extern __IO uint16_t ADC1ConvertedValue;
/***********************************函数申明***************************************************/
unsigned char DMA_UART3_RecevDetect(unsigned char RecevFlag,u8* pDeviceID, u16 sNodeAddress); //USART3接收数据监测与数据解析
void PeripheralInit( void); //初始化外围设备
void DataMessageSend(void); // 通过短信发送液位数据
int DMA_UART3_RecevDataGet(void); //获取串口3的DMA数据
float ReadSensorData(uint16_t data); //将ADC采集的整数数据转换为小数
float Filter(float Original[],int num); //对采集的数据进行滤波处理
void error_handle(u8* pDevID, u16 NodeAddr); //异常处理函数
void Display(void);
/*******************************************************************************
* Function Name : int DMA_UART3_RecevDataGet(void)
* Description : 从DMA接收存储器中提取有效数据,放入Usart3_recev_buff[],便于后续数据解析
* Input : None
* Output : None
* Return : 接收数据长度
*******************************************************************************/
int DMA_UART3_RecevDataGet(void)
{
int i=0,j=0;
u16 DMA_RecevLength =0;
memset(Usart3_recev_buff, 0x00, sizeof(Usart3_recev_buff));
DMA_USART3_RecevIndicator.CurrentDataStartNum = DMA_USART3_RecevIndicator.NextDataStartNum ;
i = RECEIVEBUFF_SIZE - DMA_GetCurrDataCounter(DMA1_Channel6);
if(DMA_USART3_RecevIndicator.DMA_RecevCount <i)
{
DMA_RecevLength =i -DMA_USART3_RecevIndicator.DMA_RecevCount;
}
else
{
DMA_RecevLength = RECEIVEBUFF_SIZE -DMA_USART3_RecevIndicator.DMA_RecevCount + i;
}
DMA_USART3_RecevIndicator.DMA_RecevCount = i;
if((DMA_USART3_RecevIndicator.CurrentDataStartNum + DMA_RecevLength-1) < RECEIVEBUFF_SIZE)
{
DMA_USART3_RecevIndicator.CurrentDataEndNum =DMA_USART3_RecevIndicator.CurrentDataStartNum +DMA_RecevLength-1;
}
else
{
DMA_USART3_RecevIndicator.CurrentDataEndNum =(DMA_USART3_RecevIndicator.CurrentDataStartNum +DMA_RecevLength-1) -RECEIVEBUFF_SIZE;
}
#if DEBUG_TEST
printf("\r\nDMA UART2 Recev Data Start Num:%d----End Num: %d\r\n",DMA_USART3_RecevIndicator.CurrentDataStartNum,DMA_USART3_RecevIndicator.CurrentDataEndNum); //数据起始位置与终止位置
#endif
if(DMA_USART3_RecevIndicator.CurrentDataEndNum ==(RECEIVEBUFF_SIZE-1))
{
DMA_USART3_RecevIndicator.NextDataStartNum = 0;
}
else
{
DMA_USART3_RecevIndicator.NextDataStartNum = DMA_USART3_RecevIndicator.CurrentDataEndNum + 1;
}
/*************************************Data Copy*********************************************************/
if(DMA_RecevLength !=0)
{
j =DMA_USART3_RecevIndicator.CurrentDataStartNum;
if(DMA_USART3_RecevIndicator.CurrentDataEndNum >DMA_USART3_RecevIndicator.CurrentDataStartNum)
{
for(i=0; i<DMA_RecevLength; i++,j++)
{
Usart3_recev_buff[i] =DMA_USART3_RecevBuff[j];
}
}
else
{
for(i=0; i<DMA_RecevLength; i++)
{
if( j<(RECEIVEBUFF_SIZE-1) )
{
Usart3_recev_buff[i] =DMA_USART3_RecevBuff[j];
j++;
}
else if( j==(RECEIVEBUFF_SIZE-1) )
{
Usart3_recev_buff[i] =DMA_USART3_RecevBuff[j];
j =0;
}
}
}
}
return DMA_RecevLength;
}
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
unsigned char DMA_UART3_RecevDetect(unsigned char RecevFlag,u8* pDeviceID, u16 sNodeAddress)
{
int DataLength =0;
int i=0;
unsigned char StateFlag =0;
if(DMA_UART3_RECEV_FLAG==1)
{
DataLength = DMA_UART3_RecevDataGet();
if(DataLength>0)
{
for(i=0;i<DataLength;i++)
{
printf(" %x ",Usart3_recev_buff[i]); //测试使用 将串口3接收到的数据以16进制打印出来
}
if(RecevFlag ==NETLOGIN)
{
StateFlag =GPRS_Receive_NetLogin(); //上网注册状态检验,当返回为1时注册成功,返回为0时注册失败
}
else if(RecevFlag ==TCPCONNECT)
{
StateFlag =GPRS_Receive_TcpConnect(); //SOCKET连接: 当返回为1时SOCKET连接成功,返回为0时连接失败
}
else if(RecevFlag ==DATARECEV )
{
StateFlag =GPRS_Receive_DataAnalysis(pDeviceID, sNodeAddress); //进行接收数据分析
}
}
else
{
printf("\r\nNo data\r\n");
}
memset(DMA_USART3_RecevBuff,0x00,RECEIVEBUFF_SIZE); //复位DMA数据接收BUFF
DMA_UART3_RECEV_FLAG =0;
}
return StateFlag;
}
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void DataMessageSend(void) // 通过短信发送传感器数据
{
char SensorDataInquire[50] ={0x00};
unsigned char readdata[7];
uint8_t i;
uint8_t flash_num; //保证能够读出FLASH内的数据
struct SenserData messagedata;
/////////////////////确定当前采集的数据所处位置,进行FLASH读取////////////////////////////////////
if(DataCollectCount == 0)
{
flash_num = SensorCollectNumber;
}
else
{
flash_num = DataCollectCount;
}
DataRead_From_Flash(1,flash_num,0, readdata ,sizeof(readdata));
for(i=0;i<4;i++)
messagedata.Ch4Data .Data_Hex [i] = readdata[2+i];
snprintf( SensorDataInquire,sizeof(SensorDataInquire),"\r Current sensor data is: %0.2f !\r", messagedata.Ch4Data .Data_Float );
printf("\r\nSend to Phone: %s \r\n",SensorDataInquire); //将发送的短信内容显示出来
//Sms_Send( SensorDataInquire );
Delay_ms(2000); //延时2s
AlarmSMS_Send(SensorDataInquire );
Delay_ms(1000); //延时2s
}
/*******************************************************************************
* Function Name : float ReadSensorData(uint16_t data)
* Description : 将ADC采集的数据进行转换为FLOAT
* Input : ADC采集的数据
* Output : ADC采集的小数形式
* Return : None
*******************************************************************************/
float ReadSensorData(uint16_t data)
{
float ADC_Data;
float Result_Data;
#if DEBUG_TEST
printf("\r\nThe Original ADC data is %d \r\n",data); //读取ADC的原始值
#endif
ADC_Data = (float)data/4096*3.3; //电压的浮点形式
Result_Data = ADC_Data * 40; //利用2.5V进行转换
if(Result_Data<0)
Result_Data=0; //进行零漂处理
else if(Result_Data>100.0)
Result_Data=100.0; //进行上限处理
#if DEBUG_TEST
printf("\rThe Sensor Data is %0.2f\r\n",Result_Data);
#endif
return(Result_Data);
}
/*******************************************************************************
* Function Name : 平均数法Filter
* Description : 对传感器采集的数据进行滤波处理
* Input : 采集的数据
* Output : 滤波后的数据
* Return : None
*******************************************************************************/
float Filter(float Original[],int num)
{
float max=0; //最大的数
float min=0; //最小的数
float sum=0; //总和
float averge=0; //平均数输出
int i;
//判断输入参数
if( num>10 )
printf("\r\nTHE INPUT NUMBER IS MORE THAN 10,THIS FUNCTION WILL NOT WORK!\r\n");
else if(num < 3)
printf("\r\nTHE INPUT NUMBER IS LESS THAN 3,THIS FUNCTION WILL NOT WORK!\r\n");
else
{
max=Original[0];
min=Original[0]; //进行初始化
for(i=0;i<num;i++)
{
if(max<Original[i])
max=Original[i];
if(min>Original[i])
min=Original[i];
} //求出数组的最大项和最小项
printf("\r\n THE MAX is %0.2f, The MIN is %0.2f",max,min);
if(max-min>8.0) //进行数据筛选
{
for(i=1;i<num-1;i++)
sum=sum+Original[i];
averge=sum /(num-2); //去掉最大值和最小值
}
else
{
for(i=0;i<num;i++)
sum=sum+Original[i];
averge=sum /num; //所有数据的平均数
}
printf("\r\nTHE averge is %0.2f\r\n",averge);
return averge;
}
}
/////////////////////////传感器采集数据////////////////////////////////////////////
void SenserDataCollect(struct SenserData* pGetData, u8* pDevID, u16 NodeAddr)
{
u32 TimCount_Current =0;
u32 Prepare_time; //传感器预热时间
char Alarm_Flag=0;
struct TagStruct AlarmTAG; //报警结构体
uint8_t sensordata[7]={0x00}; //将传感器数据写入FLASH
u8 i=0; //测试使用
float result[COLLECT_NUM];
TimCount_Current = RTC_GetCounter();
End_time=TimCount_Current; //开始预热
Prepare_time=End_time -Start_time; //计算预热时间
#if DEBUG_TEST
printf("\r\nTHE SENSOR HAS WORKING %d S!\r\n",Prepare_time); //输出准备时间
#endif
if(Prepare_time< PREPARE_TIME)
{
#if DEBUG_TEST
printf("\r\nTHE SENSOR NEED WAIT 180 S BEFORE COLLECT DATA!\r\n"); //传感器预热时间
#endif
Delay_ms( (PREPARE_TIME - Prepare_time)*1000 ); //进行延迟,以达到准备时间
}
for(i=0;i<COLLECT_NUM;i++)
{
result[i]=ReadSensorData(ADC1ConvertedValue); //每间隔1秒进行采集
printf("\r\nNO:%d sensor_collect: %0.2f",i,result[i]); //将采集的数据进行打印
Delay_ms( (SENSOR_COLLECT_TIME) *1000); //间隔1S进行采数
}
PowerOFF_Sensor(); //当数据采集完成时,关闭超声波探头电源
pGetData->Ch4Data.Data_Float = Filter(result,COLLECT_NUM);
pGetData->CollectTime =(DeviceConfig.Time_Hour)*60 +(DeviceConfig.Time_Min); //第一组数据采集时间
#if DEBUG_TEST
printf("\r\npGetData->CollectTime:%d\r\n",pGetData->CollectTime);
#endif
pGetData->DataCount = DataCollectCount+1; //当前采集的个数
Delay_ms(500);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
DataCollectCount = pGetData->DataCount;
ConfigData.CollectNum = DataCollectCount;
DataWrite_To_Flash(0,9,0,&ConfigData.CollectNum,1);
////////////////////////////////将采集的传感器数据写入FLASH///////////////////////////////////////////////////
sensordata[0]= pGetData->CollectTime >> 8;
sensordata[1]= pGetData->CollectTime & 0xff;
for(i=0;i<4;i++)
{
sensordata[2+i] = pGetData->Ch4Data.Data_Hex[i];
}
sensordata[6] = pGetData->DataCount;
DataWrite_To_Flash(1,pGetData->DataCount,0,(uint8_t*)sensordata,sizeof(sensordata)); //数据从Sector1开始写入
ReadData_flag=1; //采集数据完成
#if DEBUG_TEST
printf("\r\nthe sensor data already send NO.%d to flash!\r\n",pGetData->DataCount);
#endif
//////////////如果监测的气体浓度达到了报警阈值,立即报警,无需等到上报时间的到来///////////////////////
if((pGetData->Ch4Data.Data_Float >=DeviceConfig.HighAlarmLevel .Data_Float) ||(pGetData->Ch4Data.Data_Float>=DeviceConfig.LowAlarmLevel .Data_Float) )
{
//DataMessageSend(); //短信发送 ,目前注释掉
Alarm_Flag=1; //报警信号
TCP_Connect(); //重新建立TCP连接
AlarmTAG.OID_Command=(DeviceConfig.CollectPeriod<<11)+pGetData->CollectTime +((0xC0 + REPORTDATA )<<24);
AlarmTAG.OID_Command=ntohl(AlarmTAG.OID_Command);
AlarmTAG.Width=4;
for(i=0;i<AlarmTAG.Width;i++)
AlarmTAG.Value[i]=pGetData->Ch4Data.Data_Hex[i]; //组成报警的TAG
SendDataToServ(TRAPREQUEST,&AlarmTAG,1,pDevID); //433模块主动上传数据
//AlarmTrap(Usart3_send_buff, pDevID, NodeAddr, &PerceptionData); //3G模块主动上传数据
Send_Request_flag = DMA_UART3_RecevDetect(DATARECEV,pDevID, NodeAddr); //每隔5秒发送一次,共发送3次,收到数据时
if(Send_Request_flag == 1)
{
Send_Request_flag = 0;
}
TCP_Disconnect(); //配置下发完成,断开TCP连接
LiquidDataSend_Flag=1; //液位数据成功发送到服务器标志变量
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
//printf("\r\nthe sensor end collect data! waiting for send!\r\n"); //测试显示
if(DataCollectCount < SensorCollectNumber)
{
Sms_Consult(pDevID, NodeAddr );
if(Alarm_Flag==0)
{ SendData_Flag=1; } //没有报警或者达到上报时间设置发送成功
else
{
//SendData_Flag=0;
} //有报警信号时发送不成功
gotoSleep(DeviceConfig.CollectPeriod );
} //如果未达到上报时间,以采集时间睡眠
else
if( DataCollectCount == SensorCollectNumber) //采集完毕,进行数据上报 ;当采集次数到达时,先判断是否阈值上报过一次
{
Sms_Consult(pDevID, NodeAddr ); //查阅短信,更新配置参数,便于需要时及时上传数据
Delay_ms(100);
DeviceConfig.BatteryCapacity = DS2780_Test(); //监测电池电量
//////////////////////////////////////////////////////////////////////
if(ConfigData.SensorDataInquireFlag ==1)
{
ConfigData.SensorDataInquireFlag =0;
//DataMessageSend(); //目前不短信发送
}
TCP_Connect(); //重新建立TCP连接
TrapData(pDevID);
Send_Request_flag = DMA_UART3_RecevDetect(DATARECEV,pDevID, NodeAddr); //每隔5秒发送一次,共发送5次,收到数据时断开TCP连接
if(Send_Request_flag == 1)
{
Send_Request_flag = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//Delay_ms(1000);
TCP_Disconnect(); //配置下发完成,断开TCP连接
LiquidDataSend_Flag=1; //数据成功发送到服务器标志变量
gotoSleep(DeviceConfig.CollectPeriod);
}
}
/*******************************************************************************
* Function Name : error_handle(void)
* Description : 异常处理
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void error_handle(u8* pDevID, u16 NodeAddr)
{
u8 state[2];
//u8 readdata[7];
int i;
//************************************首先判断上次工作状态,采数和发送********************************************************
DataRead_From_Flash(2,1,0, state ,2); //读取采数状态和发送状态
if(state[0] ==0 ) //判断是否采集数据,如采集,进入下一步,否则进行采集,采集后睡眠
{
printf("\r\nTHE DEVICE HAS NOT COLLECTED DATA! \r\n");
if(DataCollectCount < SensorCollectNumber) //当已采集的数据小于共采集数量
{
printf("\r\nThe Sensor Has DataCollectCount is %d \r\n",DataCollectCount); //
SenserDataCollect(&PerceptionData, pDevID, NodeAddr); //获取传感器数据
}
else //采集完成后,完成数据的备份
{
if(DataCollectCount == SensorCollectNumber) //完成数据采集后,开始上传数据
//printf("The Sensor Flash DataCollectCount is %d ",DataCollectCount); //
DataCollectCount=0; //对数据进行清零,重新采集
printf("\r\nThe Sensor Has DataCollectCount is %d \r\n",DataCollectCount); //
SenserDataCollect(&PerceptionData, pDevID, NodeAddr); //获取传感器数据
}
}
else
{
printf("\r\nTHE DEVICE COLLECT DONE!\r\n");
}
if(state[1] ==0) //判断是否进行上报成功,继续上报
{
printf("\r\nTHE DEVICE HAS NOT SENT DATA! \r\n");
PowerOFF_Sensor(); //当数据采集完成时,关闭超声波探头电源
if( DataCollectCount == SensorCollectNumber) //采集完毕,进行数据上报 ;当采集次数到达时,先判断是否阈值上报过一次
{
//Sms_Consult(pDevID, NodeAddr ); //查阅短信,更新配置参数,便于需要时及时上传液位数据
PowerOFF_Sensor(); //当液位数据采集完成时,关闭超声波探头电源
TCP_Connect(); //重新建立TCP连接
for(i=0;i<2 ;i++)
{
TrapData(pDevID); //3G模块主动上传数据
//Send_Request_flag = DMA_UART3_RecevDetect(DATARECEV,pDevID, NodeAddr); //每隔5秒发送一次,共发送5次,收到数据时断开TCP连接
if(SendData_Flag == 1)
{
//Send_Request_flag = 0;
break;
}
Delay_ms(5000);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//Delay_ms(1000);
TCP_Disconnect(); //配置下发完成,断开TCP连接
LiquidDataSend_Flag=1; //液位数据成功发送到服务器标志变量
}
else
{
TCP_Connect(); //重新建立TCP连接
TCP_Disconnect(); //配置下发完成,断开TCP连接
}
}
else
{
printf("\r\nTHE DEVICE SEND DONE!\r\n");
}
//gotoSleep(DeviceConfig.CollectPeriod);
}
/*******************************************************************************
* Function Name : int main(void)
* Description : 主函数
* Input : None
* Output : None
* Return : None
*******************************************************************************/
int main( void )
{
u8 i=0,j=0;
u8 DeviceID[6] =SENSORID; //初始化设备ID号
u16 NodeAddr =0x0000; //提取设备ID号最后面两个字节作为节点地址
NodeAddr=DeviceID[4]*256 +DeviceID[5];
PeripheralInit(); //初始化
//***********************************对采集数量进行处理,一次最多传15个数*****************************************************
SensorCollectNumber = DeviceConfig.SendCount / DeviceConfig.CollectPeriod ;
if(SensorCollectNumber>15)
{ SensorCollectNumber=15; }
DataRead_From_Flash(0,9,0, &(DeviceConfig.CollectNum ) ,1); //读取已采集的数据量
DataCollectCount = DeviceConfig.CollectNum ;
if(DataCollectCount > SensorCollectNumber) //如果已采集的数量大于需要采集的数量,将已采集数量归零
{
DataCollectCount=0;
}
#if DEBUG_TEST
printf("\r\n The Data Collect Number is %d \r\n",DeviceConfig.CollectNum );
#endif
//error_handle(DeviceID, NodeAddr); //异常处理函数
Sms_Consult(DeviceID, NodeAddr);
TCP_Connect(); //重新建立TCP连接
SendDataToServ(STARTUPREQUEST,NULL,0,DeviceID); //开机上报信息
Delay_ms(1000);
TCP_Disconnect(); //配置下发完成,断开TCP连接
while(1)
{
WWDOG_Feed =0x1FFF; //窗口看门狗喂狗,定时4分20秒,第二字节约1秒变化一次,即0x09AF变到0x099F约耗时1秒
for(i=0;i<5;i++)
{
Delay_ms(200); //参考探头上电后数据稳定时间,作相应调整
if(DMA_UART3_RECEV_FLAG==1) //查询数据接收情况
{
DMA_UART3_RecevDetect(DATARECEV,DeviceID, NodeAddr);
break;
}
}
// Sms_Consult(DeviceID, NodeAddr);
if(DataCollectCount < SensorCollectNumber) //当已采集的数据小于共采集数量
{
#if DEBUG_TEST
printf("\r\nThe Sensor Has DataCollectCount is %d \r\n",DataCollectCount);
#endif
SenserDataCollect(&PerceptionData, DeviceID, NodeAddr); //获取传感器数据
}
else //采集完成后,完成数据的备份
{
if(DataCollectCount == SensorCollectNumber) //完成数据采集后,开始上传数据
//printf("The Sensor Flash DataCollectCount is %d ",DataCollectCount); //
DataCollectCount=0; //对数据进行清零,重新采集
}
if(LiquidDataSend_Flag ==1)
{
gotoSleep(DeviceConfig.CollectPeriod );
//Sms_Consult(DeviceID, NodeAddr); //目前注释
}
}
}
/*******************************************************************************
* Function Name : void PeripheralInit( void )
* Description : 初始化端口及外设
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void PeripheralInit( void )
{
WWDG_Init(0x7F,0X5F,WWDG_Prescaler_8); //首先开启窗口看门狗,计数器值为7f,窗口寄存器为5f,分频数为8
SysTick_Init(); //初始化时钟
USART1_Config(); /* USART1 配置模式为 9600 8-N-1, 中断接收 */ //用于串口调试助手
Delay_ms(200);
// USART2_Config(); /* USART2 配置模式为 9600 8-N-1,中断接收 */ //用于433通信方式
USART3_Config(); /* USART3 配置模式为 115200 8-N-1,中断接收 */ //用于3G模块通信方式
UART_NVIC_Configuration();
USART3_DMA_Config();
RTC_NVIC_Config(); /* 配置RTC秒中断优先级 */
RTC_CheckAndConfig(&systmtime);
ADCconfig(); //进行ADC初始化
PowerON_GPRS(); //打开GPRS模块电源 3.8V
PowerON_Sensor(); //打开传感器电压 12V
Delay_ms(500);
Start_time=RTC_GetCounter(); //记录传感器打开时间
Display();
ConfigData_Init(&DeviceConfig);
if (PowerOffReset ==1)
{
printf("\r\n掉电重启,重新初始化库仑计\r\n"); //测试使用
DS2780_CapacityInit(); //掉电后重新写电池容量
Set_register_ds2780(); //掉电后对库仑计重新初始化
set_ACR(1000); //掉电后对库仑计重新初始化
}
//GPRS_Init(); //暂时屏蔽
GPRS_Config();
Delay_ms(5000); //等待短信接收
//Sms_Consult(pDeviceID, sNodeAddress);
}
/*******************************************************************************
* Function Name : void Display( void )
* Description : 打印出厂信息
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void Display(void)
{
u32 TimCount_Current =0;
u8 DeviceID[6] = SENSORID ;
TimCount_Current = RTC_GetCounter();
printf("\r\n********* 北京航天科瑞电子有限公司 *********");
printf("\r\n************* 燃气智能监测终端 ***********");
printf("\r\n************* BIRMM-RTU100 ***********");
printf("\r\n************* 设备ID号:%x %x %x %x %x %x***********",DeviceID[0],DeviceID[1],DeviceID[2],DeviceID[3],DeviceID[4],DeviceID[5]);
printf("\r\n************** 硬件类型: 433版本 **********");
printf("\r\n************** 硬件版本号: %x ***********",HARDVERSION);
printf("\r\n************** 软件版本号: %x **************\r\n\r\n",SOFTVERSION);
Time_Display(TimCount_Current,&systmtime);
DeviceConfig.Time_Sec =systmtime.tm_sec;
DeviceConfig.Time_Min =systmtime.tm_min;
DeviceConfig.Time_Hour =systmtime.tm_hour;
DeviceConfig.Time_Mday =systmtime.tm_mday;
DeviceConfig.Time_Mon =systmtime.tm_mon;
DeviceConfig.Time_Year =systmtime.tm_year-2000; //对上传年份去基数修正
printf("**************当前时间:%0.4d-%0.2d-%0.2d %0.2d:%0.2d:%0.2d***********\r\n",systmtime.tm_year,systmtime.tm_mon, //测试使用
systmtime.tm_mday,systmtime.tm_hour,systmtime.tm_min,systmtime.tm_sec); //测试使用
Delay_ms(3000);
}
#ifdef DEBUG
/*******************************************************************************
* Function Name : assert_failed
* Description : Reports the name of the source file and the source line number
* where the assert error has occurred.
* Input : - file: pointer to the source file name
* - line: assert error line source number
* Output : None
* Return : None
*******************************************************************************/
void assert_failed(u8* file, u32 line)
{
/* User can add his own implementation to report the file name and line number */
printf("\n\r Wrong parameter value detected on\r\n");
printf(" file %s\r\n", file);
printf(" line %d\r\n", line);
/* Infinite loop */
/* while (1)
{
} */
}
#endif
/*********************************************END OF FILE**********************/
<file_sep>/User/gprs/gprs.h
#ifndef _GPRS_H_
#define _GPRS_H_
#include "stm32f10x.h"
#include "AiderProtocol.h"
//#define NETERRORCOUNT 15
#define NETLOGIN 1 //设备注册基站
#define TCPCONNECT 2 //设备建立TCP连接
#define DATARECEV 3 //设备接收服务器数据
///////////////////////////////////////////////////////////////////////////////
//声明结构体
struct SMS_Config_RegPara
{
char CurrentPhoneNum[16]; //当前通信手机号码,字符串格式
char AlarmPhoneNum[16]; //短信配置液位报警号码,字符串格式
char ServerIP[16]; //短信配置服务器IP,字符串格式
char ServerPort[6]; //短信配置服务器端口号,字符串格式
union Hex_Float LowAlarmLevel;
union Hex_Float HighAlarmLevel;
uint8_t CollectPeriod_Byte[2]; //数据采集间隔,使用数组存储,以方便Flash读写
uint8_t SendCount_Byte[2]; //一天上传液位数据次数,使用数组存储,以方便Flash读写 上传周期
uint8_t CollectStartTime_Byte[2]; //开始采集时间
u8 CollectNum; //已经完成的采集数量
uint8_t RetryNum; //重传次数
uint8_t WorkNum_Byte[2]; //工作次数
uint8_t SensorDataInquireFlag; //短信查询当前传感器数据标志变量
uint8_t DeviceSetInquireFlag; //短信查询当前 传感器配置信息标志变量
};
//声明函数
void GPRS_Init(void); //433通信方式,该函数暂时无用,使用3G通信时才打开
void GPRS_Config(void); //配置3G模块相关参数
void TCP_Connect(void); //建立TCP连接
void TCP_Disconnect(void); //断开TCP连接
unsigned char TCP_StatusQuery(void); //查询TCP连接状态 返回TCP状态
void mput(char *str);
void mput_mix(char *str,int length);
char* Find_String(char *Source, char *Object);
char* Find_SpecialString(char* Source, char* Object, short Length_Source, short Length_Object);
//void SIM5216_PowerOn(void); //433通信方式,该函数暂时无用,使用3G通信时才打开
//void SIM5216_PowerOff(void); //433通信方式,该函数暂时无用,使用3G通信时才打开
void Sms_Send(char* pSend); //短信发送函数
void AlarmSMS_Send(char* pSend);//发送报警短信
void Sms_Analysis(char* pBuff); //短信接收解析函数
//void Sms_Consult(void); //查阅未读短信
void Sms_Consult(u8* pDeviceID, u16 sNodeAddress);
void USART_DataBlock_Send(USART_TypeDef *USART_PORT,char *SendUartBuf,u16 SendLength); //批量向串口发送数据
void SetRequest_GPRS(void); //通过3G模块请求服务器下发配置信息
void ConfigData_Init(struct Sensor_Set* Para);
unsigned char GPRS_Receive_NetLogin(void); //模块注册网络接收信息解析
unsigned char GPRS_Receive_TcpConnect(void);//建立TCP连接接收信息解析
unsigned char Receive_Deal_GPRS(void); //3G模块接收数据解析,主要用于处理MCU与3G模块之间的交互数据
unsigned char GPRS_Receive_DataAnalysis(u8* pDeviceID, u16 sNodeAddress); //3G模块接收服务器数据解析,主要处理服务器下发的基于埃德尔协议的数据
void ClientRequest_GPRS(u8* pSendBuff, u8* pDeviceID, u16 NodeAddress); //传感器终端主动申请服务器下发配置
void Treaty_Data_Analysis(u8* pTreatyBuff, u16* pFlag, u8* pDeviceID, u16 NodeAddress);
uint16_t char_to_int(char* pSetPara); //处理短信下发的配置,主要将字符转化为整数
float char_to_float(char* pSetPara); //处理短信下发的配置,主要将字符转化为小数
void SensorSetMessage(void); //短信获取设备配置参数
#endif
<file_sep>/User/gprs/gprs.c
// File Name: gprs.c
#include "string.h"
#include "gprs.h"
#include "bsp_SysTick.h"
#include "bsp_usart.h"
#include "AiderProtocol.h"
#include "bsp_rtc.h"
#include "433_Wiminet.h"
#include "common.h"
#include "math.h"
#include "SPI_Flash.h"
#include "DS2780.h"
#include "API-Platform.h"
#include "SensorInit.h"
#include "test.h"
//char Receive_Monitor_GPRS(void); //3G模块串口监听,当MCU检测到3G模块串口的数据时
//void Receive_Deal_GPRS(void); //3G模块接收数据解析,主要用于处理MCU与3G模块之间的交互数据
//void Receive_Analysis_GPRS(void);//3G模块接收服务器数据解析,主要处理服务器下发的基于埃德尔协议的数据
//u8 NetStatus_Detection( void );//3G模块网络连接状态检测
//void SetRequest_GPRS(void); //通过3G模块请求服务器下发配置信息
char Usart3_recev_buff[1000]={'\0'}; //USART3接收缓存
uint16_t Usart3_recev_count=0; //USART3接收计数器
extern unsigned char Usart3_send_buff[300];
uint8_t CSQ_OK =0; //信号质量标志变量
extern u8 Send_Request_flag; //发送数据至上位机后收到反馈
extern char SendData_Flag; //发送数据成功标志位,发送成为为1,不成功为0;
extern char TcpConnect_Flag; //TCP连接成功标志位,连接成功为1,不成功为0;
extern struct SMS_Config_RegPara ConfigData; //定义的下发配置参数,HEX格式,方便在系统进入休眠模式之前写入BKP寄存器
static char RespRev_OK =0; //成功接收服务器应答
extern struct Sensor_Set DeviceConfig; //配置信息结构体
extern char SetRev_OK; //成功接收服务器配置
extern char Alive; //不休眠标志变量,为1时说明不进行休眠处理,有待调整
extern char DatRev_OK ; //成功正确接收液位数据
extern uint8_t DataCollectCount; //数据采集计数器
extern uint8_t LiquidDataSend_Flag;
extern uint8_t DMA_USART3_RecevBuff[RECEIVEBUFF_SIZE];
extern uint8_t DMA_UART3_RECEV_FLAG ; //USART3 DMA接收标志变量
extern unsigned char DMA_UART3_RecevDetect(unsigned char RecevFlag,u8* pDeviceID, u16 sNodeAddress); //USART3接收数据监测与数据解析
extern void DataMessageSend(void); // 通过短信发送液位数据
//void SIM5216_PowerOn(void) //打开SIM5216模块
//{
// GPIO_SetBits(GPIOC,GPIO_Pin_3); //POWER_ON引脚拉低
// Delay_ms(120); //100ms延时 64ms<Ton<180ms
// GPIO_ResetBits(GPIOC,GPIO_Pin_3); //POWER_ON引脚拉高
// Delay_ms(5500); //5s延时 Tuart>4.7s
//
//}
//void SIM5216_PowerOff(void) //关闭SIM5216模块
//{
// GPIO_SetBits(GPIOC,GPIO_Pin_3); //POWER_ON引脚拉低
// Delay_ms(2000); //1s延时 500ms<Ton<5s
// GPIO_ResetBits(GPIOC,GPIO_Pin_3); //POWER_ON引脚拉高
// Delay_ms(6000);
//}
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void delay(unsigned int dl_time)
{
unsigned int i,y;
for(i=0;i<5000;i++)
{
for(y=0;y<dl_time;y++);
}
}
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void USART_DataBlock_Send(USART_TypeDef* USART_PORT,char* SendUartBuf,u16 SendLength) //批量向串口发送数据
{
u16 i;
for(i=0;i<SendLength;i++)
{
USART_SendData(USART_PORT, *(SendUartBuf+i));
while (USART_GetFlagStatus(USART_PORT, USART_FLAG_TC) == RESET);
}
}
void mput_mix(char *str,int length)
{
printf("length:%d\r\n",length); //测试使用
//USART_ITConfig(USART3, USART_IT_IDLE, ENABLE); //向USART3发送数据前,先打开USART3接收空闲中断,便于监测数据接收完成
USART_DataBlock_Send(USART3,str,length);
//USART_DataBlock_Send(USART3,"\r\n",2);
USART_DataBlock_Send(USART1,str,length);
USART_DataBlock_Send(USART1,"\r\n",2);
}
void mput(char* str)
{
// printf("length:%d\r\n",strlen(str)); //测试使用
// USART_ITConfig(USART3, USART_IT_IDLE, ENABLE); //向USART3发送数据前,先打开USART3接收空闲中断,便于监测数据接收完成
USART_DataBlock_Send(USART3,str,strlen(str));
USART_DataBlock_Send(USART3,"\r\n",2);
USART_DataBlock_Send(USART1,str,strlen(str));
USART_DataBlock_Send(USART1,"\r\n",2);
}
/*******************************************************************************
* Function Name : void GPRS_Config(void)
* Description : GPRS
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void GPRS_Config(void)
{
printf("\r\nFUNCTION :GPRS_Config start! \r\n"); //提示进入该函数
memset(DMA_USART3_RecevBuff,0x00,RECEIVEBUFF_SIZE);
USART_DMACmd(USART3, USART_DMAReq_Rx, ENABLE); //配置串口DMA1接收
mput("AT^UARTRPT=1"); //设置通信接口为UART
Delay_ms(200);
mput("AT+CMGF=1"); //短信格式设置为文本模式
Delay_ms(300);
mput("AT+CPMS=\"ME\",\"ME\",\"ME\""); //设置发送和接收短信存储器为ME消息存储器,否则使用AT+CMGL="REC UNREAD"命令查不到短信
Delay_ms(300);
mput("AT+CNMI=1,1"); //新消息指示设置为存储并送通知
Delay_ms(200);
// mput("AT+CMGD=1,3"); //新消息指示设置为存储并送通知
// Delay_ms(500);
// mput("AT+CPMS?"); //新消息指示设置为存储并送通知
// Delay_ms(200);
printf("\r\nFUNCTION :GPRS_Config end! \r\n"); //提示结束该函数
}
/*******************************************************************************
* Function Name : void GPRS_Init(void)
* Description : GPRS
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void GPRS_Init(void)
{
u8 NetSearchCount=40; //搜寻网络最大尝试次数
u8 CSQ_DetectCount=2; //网络注册成功以后再次搜索网络次数,用以稳定网络连接
// char SendArry1[80] ={'\0'};
// u8 i=0;
printf("\r\nFUNCTION :GPRS_Init start! \r\n"); //提示进入该函数
memset(DMA_USART3_RecevBuff,0x00,RECEIVEBUFF_SIZE);
USART_DMACmd(USART3, USART_DMAReq_Rx, ENABLE); //配置串口DMA1接收
// SIM5216_PowerOn();
Delay_ms(1000);
mput("AT^MODECONFIG=19"); //
while(NetSearchCount!=0)
{
NetSearchCount--;
printf("\r\nGPRS Net Searching...\r\n"); //测试使用
mput("AT+CGREG=1"); //完成信号自动收索,当3G信号很弱时自动切换到3G信号
Delay_ms(800);
mput("AT+CGREG?"); //完成信号自动收索,当3G信号很弱时自动切换到3G信号
Delay_ms(800);
DMA_UART3_RecevDetect( NETLOGIN,0,0);
if(CSQ_OK ==1)
{
CSQ_OK =0;
CSQ_DetectCount--;
if(CSQ_DetectCount==0)
{
break;
}
}
// DS2780_Test(); //测试使用
}
if(NetSearchCount==0)
{
gotoSleep(DeviceConfig.CollectPeriod );
}
printf("\r\nFUNCTION :GPRS_Init end! \r\n");
}
/*******************************************************************************
* Function Name : void TCP_Connect(void)
* Description : GPRS
* Input : None
* Output : None
* Return : None
*******************************************************************************/
unsigned char TCP_StatusQuery(void)
{
unsigned char TcpStatusFlag =0; //TCP连接状态标志变量
int i;
for(i=0;i<4;i++)
{
//mput("AT+MIPOPEN?"); //查询Socket建立情况
Delay_ms(800);
TcpStatusFlag =DMA_UART3_RecevDetect( TCPCONNECT ,0, 0);
if(TcpStatusFlag==1)
{
break;
}
}
return TcpStatusFlag;
}
/*******************************************************************************
* Function Name : void TCP_Connect(void)
* Description : GPRS
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TCP_Connect(void)
{
char SendArry[50] ={'\0'};
unsigned char TcpConnectFlag =0; //TCP连接建立标志变量
unsigned char NetErrorCount =10; //TCP建立连接尝试次数,下一版短信可配置
#if DEBUG_TEST
printf(" Multi GPRS Start!\r\n");
printf(" TCP Start Connect!\r\n"); //测试显示
#endif
GPRS_Init();
while(NetErrorCount>0)
{
mput("at+mipcall=1");
Delay_ms(800);
snprintf(SendArry,sizeof(SendArry),"at+miptrans=1,\"%s\",%s",DeviceConfig.ServerIP,DeviceConfig.ServerPort); // mput("at+miptrans=1,\"172.16.58.3\",2015"); //后续需要从寄存器中读取,有待进一步完善
// snprintf(SendArry,sizeof(SendArry),"AT+MIPOPEN=1,\"TCP\",\"%s\",%s,10000",DeviceConfig.ServerIP,DeviceConfig.ServerPort); // mput("at+miptrans=1,\"172.16.58.3\",2015"); //后续需要从寄存器中读取,有待进一步完善
mput(SendArry);
Delay_ms(5000);
//mput("AT+MIPOPEN?"); //查询Socket建立情况 注释9.9
Delay_ms(800);
TcpConnectFlag =DMA_UART3_RecevDetect( TCPCONNECT ,0 ,0 ); //对GPRS模块接收到的数据进行解析
NetErrorCount--;
if(TcpConnectFlag==1)
{
printf("\r\nThe TCP connect is OK\r\n");
//mput("AT+MIPMODE=1,1"); //设置SOCKET模式为Hex传输模式
Delay_ms(500);
// mput("AT+MIPSEND=1,5"); //发送测试
// mput("11111");
break;
}
}
if(NetErrorCount == 0)
{
printf("\r\nThe Client Could Not Connect TCP!\r\n");
TCP_Disconnect();
Delay_ms(2000);
//TCP_Connect(); //保证TCP连接成功
gotoSleep(DeviceConfig.CollectPeriod ); //多次尝试未连接到网络,直接进入休眠模式,用于监测模块唤醒以后第一次入网状态
}
#if DEBUG_TEST
printf(" TCP end Connect!\r\n"); //测试显示
#endif
}
/*******************************************************************************
* Function Name : void TCP_Disconnect(void)
* Description : GPRS
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TCP_Disconnect(void)
{
#if DEBUG_TEST
printf("\r\nTCP link is disconnect!\r\n");
#endif
mput("+++");
//mput("AT+MIPCLOSE=1");
// TCP_Connect_Flag =0; //关闭循环联网
Delay_ms(500);
}
/*******************************************************************************
* Function Name : char* Find_String(char* Source, char* Object)
* Description : 在目标字符串中发现一个指定的字符串
* Input :
* Output :
* Return : 如果找到,则返回目标字符串在源字符串中的首地址
*******************************************************************************/
char* Find_String(char* Source, char* Object)
{
char* Ptemp1 = Source;
char* Ptemp2 = Object;
short Length_Source =0;
short Length_Object =0;
short i=0,j=0;
short count=0;
Length_Source = strlen(Source);
Length_Object = strlen(Object);
if(Length_Source < Length_Object)
{
return NULL;
}
else if(Length_Source == Length_Object)
{
if((Length_Source==0)&&(Length_Object==0))
{
return NULL;
}
else
{
for(i=0;i<Length_Source;i++)
{
if(Ptemp1[i] != Ptemp2[i])
return NULL;
}
return Ptemp1;
}
}
else
{
if(Length_Object == 0)
{
return NULL;
}
else
{ count = Length_Source - Length_Object + 1;
for(i=0;i<count;i++)
{ for(j=0;j<Length_Object;j++)
{
if(Ptemp1[i+j] != Ptemp2[j])
break;
}
if(j==Length_Object)
return &Ptemp1[i];
}
return NULL;
}
}
}
/***********函数功能:在特定序列中发现一个指定的序列****************/
/***********如果找到,则返回目标序列在源序列中的首地址**************/
char* Find_SpecialString(char* Source, char* Object, short Length_Source, short Length_Object)
{
char* Ptemp1 = Source;
char* Ptemp2 = Object;
short i=0,j=0;
short count=0;
if((Length_Source < 0)||(Length_Object < 0))
{
return NULL;
}
if(Length_Source < Length_Object)
{
return NULL;
}
else if(Length_Source == Length_Object)
{
if((Length_Source==0)&&(Length_Object==0))
{
return NULL;
}
else
{
for(i=0;i<Length_Source;i++)
{
if(Ptemp1[i] != Ptemp2[i])
return NULL;
}
return Ptemp1;
}
}
else
{
if(Length_Object == 0)
{
return NULL;
}
else
{
count = Length_Source - Length_Object + 1;
for(i=0;i<count;i++)
{ for(j=0;j<Length_Object;j++)
{
if(Ptemp1[i+j] != Ptemp2[j])
break;
}
if(j==Length_Object)
{
return &Ptemp1[i];
}
}
return NULL;
}
}
}
/********************函数功能:短信发送前预处理*********************/
/*************即在需要发送的数据最后增加一个结束符0x1a**************/
void SendPretreatment(char* pSend)
{
uint8_t i=0;
char* pTemp =NULL;
i= strlen(pSend);
pTemp =pSend+i;
*(pTemp) =0x1a;
}
/***********************函数功能:发送短信**************************/
/*******************************************************************/
//发送短信流程:
//第一步:设置接收短信提醒格式:AT+CNMI=1,2,0,0,0
//第二步:设定短信接收方号码:AT+CMGS="15116924685"
//第三步:发送短信正文,并以16进制0x1a作为结尾
void Sms_Send(char* pSend)
{
// uint8_t PhoneNum[13]={0x00}; //后续更改为从寄存器中读取
char SendBuf[200]={0x00}; //短信发送缓存,根据最大可能的发送数据长度确定其大小
// struct Sensor_Set* Para= &DeviceConfig;
// memcpy(PhoneNum, DeviceConfig.AlarmPhoneNum,strlen((char*)DeviceConfig.AlarmPhoneNum));
// mput("AT+CNMI=1,2,0,0,0");
memset(SendBuf,0,sizeof(SendBuf));
snprintf(SendBuf,sizeof(SendBuf),"AT+CMGS=\"%s\"",ConfigData.CurrentPhoneNum); //发送短信号码为当前通信手机号码
mput(SendBuf);
// mput("AT+CMGS=\"861064617006426\""); //测试使用,有待完善
Delay_ms(500);
memset(SendBuf,0,sizeof(SendBuf));
snprintf(SendBuf, (sizeof(SendBuf)-1), pSend, strlen(pSend));
SendPretreatment(SendBuf);
mput(SendBuf);
Delay_ms(1000);
// DMA_UART3_RecevDetect(); //等待接收信息
}
void AlarmSMS_Send(char* pSend) //发送报警短信
{
char SendBuf[200]={0x00}; //短信发送缓存,根据最大可能的发送数据长度确定其大小
memset(SendBuf,0,sizeof(SendBuf));
snprintf(SendBuf,sizeof(SendBuf),"AT+CMGS=\"%s\"",DeviceConfig.AlarmPhoneNum); //发送短信号码为预设报警手机号码
mput(SendBuf);
Delay_ms(500);
memset(SendBuf,0,sizeof(SendBuf));
snprintf(SendBuf, (sizeof(SendBuf)-1), pSend, strlen(pSend));
SendPretreatment(SendBuf);
mput(SendBuf);
Delay_ms(1000);
}
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
uint8_t Char2Hex(uint8_t* HexArry, char* CharArry, uint8_t Length_CharArry)
{
uint8_t i=0,j=0;
uint8_t val=0;
// char* pChar = CharArry;
for(i=0; i<Length_CharArry; i++)
{
// val = *pChar;
val = CharArry[i];
if((val >= '0')&&(val <= '9'))
{
HexArry[j++] = val-'0';
}
else if(val == '.')
{
HexArry[j++] = val;
}
// pChar++;
}
return j;
}
/**************************************字符转化为浮点数******************************************/
/**************************************用于计算报警阈值******************************************/
float char_to_float(char* pSetPara)
{
char CharTemp[10]={0x00};
int i,j;
int IntegerPart=0;
int DecimalPart=0;
int Counter=0;
float number=0.0;
for(j=0;j<strlen(pSetPara);j++) //调用函数已经做了防溢出处理,strlen(pSetPara)<=5
{
if((pSetPara[j]>='0')&&(pSetPara[j]<='9'))
{
CharTemp[j] =pSetPara[j];
}
else
{
break;
}
}
if(strlen(CharTemp)>2)
{
printf("\r\nInput ERROR!!\r\n");
return 0;
}
for(i=strlen(CharTemp),j=0; i>=1; i--,j++)
{
IntegerPart =IntegerPart + (CharTemp[i-1]-'0')*(int)(pow(10,j)); //计算报警阈值整数部分
}
Counter =strlen(CharTemp)+1; //跳过小数点
memset(CharTemp,0x00,sizeof(CharTemp));
for(i=0,j=Counter;j<strlen(pSetPara);j++,i++)
{
if((pSetPara[j]>='0')&&(pSetPara[j]<='9'))
{
CharTemp[i] =pSetPara[j];
}
else
{
break;
}
}
if(strlen(CharTemp)>2)
{
printf("\r\nInput Alarm Threshold ERROR!!\r\n");
return 0;
}
for(i=strlen(CharTemp),j=0; i>=1; i--,j++)
{
if(strlen(CharTemp)==1)
{
DecimalPart =(CharTemp[i-1]-'0')*10;
break;
}
else
{
DecimalPart =DecimalPart + (CharTemp[i-1]-'0')*(int)(pow(10,j)); //计算报警阈值小数部分
}
}
number=DecimalPart*0.01 + IntegerPart;
return(number);
}
/**************************************字符转化为整数******************************************/
uint16_t char_to_int(char* pSetPara)
{
char CharTemp[10]={0x00};
int i,j;
int length;
int IntegerPart=0;
for(j=0;j<strlen(pSetPara);j++) //调用函数已经做了防溢出处理,strlen(pSetPara)<=5
{
if((pSetPara[j]>='0')&&(pSetPara[j]<='9'))
{
CharTemp[j] =pSetPara[j];
}
else
{
break;
}
}
if(strlen(CharTemp)>5)
{
printf("\r\nInput ERROR!!\r\n");
return 0;
}
length=strlen(CharTemp);
for(i=0;i<length;i++)
printf("----the data is %c -----",CharTemp[i]);
IntegerPart = IntegerPart + (CharTemp[length-1]-'0');
if(length>1)
for(i=1; i<strlen(CharTemp); i++)
{
IntegerPart =IntegerPart + (CharTemp[length-1-i]-'0')*(int)(pow(10,i)); //
}
return (IntegerPart);
}
//}
/*******************************************************************************
* Function Name : XX
* Description : 查阅未读短信
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void Sms_Consult(u8* pDeviceID, u16 sNodeAddress)
{
#if DEBUG_TEST
printf("\r\nFUNCTION :Sms_Consult start! \r\n"); //提示进入该函数
#endif
mput("AT+CMGL=\"REC UNREAD\""); //读取未读信息
// mput("AT+CMGL=\"ALL\""); //读取未读信息
// mput("AT+CMGL=0"); //读取未读信息
Delay_ms(1500);
DMA_UART3_RecevDetect( DATARECEV, pDeviceID, sNodeAddress );
// mput("AT+CMGD=,3"); //删除已读信息
Delay_ms(2500); //等待模块切换回数据传输状态
#if DEBUG_TEST
printf("\r\nFUNCTION :Sms_Consult end! \r\n"); //提示退出该函数
#endif
}
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
/***********************函数功能:短信配置解析**************************/
/*******************************************************************/
//AT+CNMI=1,2,0,0,0 //接收短信设置
//+CMT: "+8613121342836","","15/08/18,17:05:29+32" //接收到的短信报文格式,回车换行(0D 0A)之后为消息正文
//ok //消息正文
//AT+CNMI=2,1 //接收短信设置
//+CMTI: "ME",1 //接收到新短信提醒
//AT+CMGL="REC UNREAD" //需发送查询未读短信命令
//+CMGL: 1,"REC UNREAD","+8613121342836","","15/08/18,17:12:19+32" //接收到的短信报文格式,回车换行(0D 0A)之后为消息正文
//ok //消息正文
void Sms_Analysis(char* pBuff)
{
// char MessageRead[11] ="REC UNREAD"; //查询到未读短信存在
char MessageRecevIndicate[5] ="+32\""; //接收到短信指示性字符串
////////////////////////////////短信配置///////////////////////////////////////////////////////////////////////
char AlarmPhoneSet[25] ="casic_set_alarm_phone_"; //报警号码设置命令
char ServerIpSet[25] ="casic_set_server_ip_"; //服务器IP设置命令
char ServerPortSet[25] ="casic_set_server_port_"; //服务器端口号设置命令
char StartCollectTime[30] ="casic_start_collect_time_"; //首次采集时间设置
char CollectPeriod[30] ="casic_collect_period_"; //采集周期设置
char SendCount[30] ="casic_send_count_"; //上传周期设置
char RetryNum[30] ="casic_retry_number_"; //重新上传次数设置
char LowAlarmThresholdSet[35] ="casic_set_low_alarm_threshold_"; //低浓度报警阈值设置命令
char HighAlarmThresholdSet[35] ="casic_set_high_alarm_threshold_"; //高浓度报警阈值设置命令
char SensorDataInquire[20]= "casic_current_data"; //短信获取传感器数据
char SensorSetInquire[20] = "casic_set_parameter"; //短信获取传感器配置参数
//////////////////////////////////配置数组定义完毕////////////////////////////////////////////////////////////////////
char CurrentPhoneNum[16] ={0x00}; //存储当前通信手机号码
char ReceiveTemp[16] ={0x00}; //暂时接收数据组
char MessageSend[200] ={0x00}; //短信发送数据组
char* pSmsRecevBuff =NULL; //查找特征数据位置指针
char* pSmsRecevData =NULL; //查找目标数据位置指针
uint8_t UploadFlag =0; //用于指示短信设置参数修改结果
uint8_t i=0; //循环变量
uint16_t temp=0; //暂时整数保存
uint8_t interget=0;
uint8_t decimal=0;
u8 j=0;
pSmsRecevBuff = Find_String(pBuff,"\"REC UNREAD\""); //检查是否收到短信
if(pSmsRecevBuff !=NULL)
{
if(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-29))) //防止指针越界
{
pSmsRecevBuff = pSmsRecevBuff+15; //指针指向手机号码前缀86 REC UNREAD 到 +86之间为15位
for(i=0;i<16;i++)
{
if(*pSmsRecevBuff == '\"')
{
break;
}
CurrentPhoneNum[i] = *pSmsRecevBuff;
pSmsRecevBuff++;
}
}
if(i>=13)
{
memcpy(ConfigData.CurrentPhoneNum,CurrentPhoneNum,i); //提取当前通信手机号码,有前缀86
printf("\r\nCurrentPhoneNum:%s\r\n",CurrentPhoneNum); //测试使用
}
pSmsRecevBuff =NULL;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pSmsRecevBuff = Find_String(pBuff,"+32\""); //检查是否收到短信
// pSmsRecevBuff = Find_SpecialString(Usart3_recev_buff, MessageRecevIndicate,sizeof(Usart3_recev_buff),strlen(MessageRecevIndicate)); //检查是否收到短信,过滤短信查询命令
if((pSmsRecevBuff !=NULL) &&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(MessageRecevIndicate))))) //防止指针越界
{
pSmsRecevData =pSmsRecevBuff +strlen(MessageRecevIndicate); //测试使用
pSmsRecevBuff =NULL;
printf("\r\nReceive Short Message is: %s\r\n",pSmsRecevData); //测试使用
/*****************************************参数设置功能*************************************************************/
//(2)设置采集周期
//pSmsRecevBuff = Find_String(pBuff,"casic_start_collect_time_"); //设置采集周期
pSmsRecevBuff = Find_SpecialString(pBuff, CollectPeriod,strlen(pBuff),strlen(CollectPeriod)); //设置采集周期
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(CollectPeriod)-1))))
{
pSmsRecevData =pSmsRecevBuff +strlen(CollectPeriod);
for(i=0;i<4;i++)
{
if(((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9')))
{;}
else
{
break;
}
}
if(i==0)
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
}
else
{
if(i>4)
{
i=4; //i表示有效,限制长度,防止溢出
}
memset(ReceiveTemp,0x00,sizeof(ReceiveTemp));
memcpy(ReceiveTemp, pSmsRecevData, i); //转为10进制 DeviceConfig.CollectPeriod = char_to_int(AlarmThresholdTemp);
DeviceConfig.CollectPeriod = char_to_int(ReceiveTemp);
ConfigData.CollectPeriod_Byte [0] = DeviceConfig.CollectPeriod >>8;
ConfigData.CollectPeriod_Byte [1] = DeviceConfig.CollectPeriod &0xff;
printf("\r\n-----data before write in flash!----%s----",(char*)ReceiveTemp); //在写入FLASH之前,输出测试
printf("\r\n-----data before write in flash!----%d----",DeviceConfig.CollectPeriod); //在写入FLASH之前,输出测试
for(j=0;j<2;j++)
printf("\r\n-----data before write in flash!----%x----",ConfigData.CollectPeriod_Byte [j]);
UploadFlag = UploadFlash((char*)ConfigData.CollectPeriod_Byte , 2);
}
if(UploadFlag ==1)
{
printf("\r\nStart CollectPeriod upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rStart CollectPeriod upload success!!\r");
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清零
snprintf( MessageSend , sizeof(MessageSend),"\rcollect period is %d \r", DeviceConfig.CollectPeriod );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput CollectPeriod not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput CollectPeriod not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
// char StartCollectTime[30]="casic_start_collect_time_"; //首次采集时间设置
// char CollectPeriod[30] ="casic_collect_period_"; //采集周期设置
// char SendCount[30] ="casic_send_count_"; //上传周期设置
// char RetryNum[30] ="casic_retry_number_"; //重新上传次数设置
//(3)设置上传周期
//pSmsRecevBuff = Find_String(pBuff,"casic_start_collect_time_"); //设置上传周期
pSmsRecevBuff = Find_SpecialString(pBuff, SendCount,strlen(pBuff),strlen(SendCount)); //设置上传周期
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(SendCount)-1))))
{
pSmsRecevData =pSmsRecevBuff +strlen(SendCount);
for(i=0;i<4;i++)
{
// if(pSmsRecevData[i]==0x0D)
// {
// break;
// }
if(((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9')))
{;}
else
{
break;
}
}
if(i==0)
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
}
else
{
if(i>4)
{
i=4; //i表示有效,限制长度,防止溢出
}
memset(ReceiveTemp,0x00,sizeof(ReceiveTemp));
memcpy(ReceiveTemp, pSmsRecevData, i);
DeviceConfig.SendCount = char_to_int(ReceiveTemp);
ConfigData.SendCount_Byte [0] = DeviceConfig.SendCount >> 8;
ConfigData.SendCount_Byte [1] = DeviceConfig.SendCount & 0xff;
printf("\r\n-----data before write in flash!----%s----",(char*)ReceiveTemp); //在写入FLASH之前,输出测试
printf("\r\n-----data before write in flash!----%d----",DeviceConfig.SendCount); //在写入FLASH之前,输出测试
for(j=0;j<2;j++)
printf("\r\n-----data before write in flash!----%x----",ConfigData.SendCount_Byte [j]);
UploadFlag = UploadFlash((char*)ConfigData.SendCount_Byte , 3);
}
if(UploadFlag ==1)
{
printf("\r\nStart SendCount upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rSendCount upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清零
snprintf( MessageSend , sizeof(MessageSend),"\rsend count time is %d \r", DeviceConfig.SendCount );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息 //
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput SendCount not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput SendCount not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
//(4)设置报警电话号码
// pSmsRecevBuff = Find_String(pBuff,"casic_set_alarm_phone_"); //设置报警号码
pSmsRecevBuff = Find_SpecialString(Usart3_recev_buff, AlarmPhoneSet,sizeof(Usart3_recev_buff),strlen(AlarmPhoneSet));
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(AlarmPhoneSet)-15))))
{
pSmsRecevData =pSmsRecevBuff +strlen(AlarmPhoneSet);
for(i=0;i<16;i++)
{
if((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9'))
{ ; }
else
{
break;
}
}
if((i>15)||(i<11)) //输入数据不合法,直接丢弃,不更新配置信息,并给出错误提示
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
// i=16; //i表示有效报警阈值长度,限制长度,防止溢出
}
else
{
memset(DeviceConfig.AlarmPhoneNum,0x00,sizeof(DeviceConfig.AlarmPhoneNum));
memcpy(DeviceConfig.AlarmPhoneNum, pSmsRecevData, i);
UploadFlag = UploadFlash(DeviceConfig.AlarmPhoneNum , 4);
}
if(UploadFlag ==1)
{
printf("\r\nAlarm phone number upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rAlarm phone number upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清零
snprintf( MessageSend , sizeof(MessageSend),"\rAlarm phone number is %s \r", DeviceConfig.AlarmPhoneNum );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else
{
printf("\r\nAlarm phone number not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rAlarm phone number not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
//(5)设置网络服务IP号码
pSmsRecevBuff = Find_SpecialString(Usart3_recev_buff, ServerIpSet,sizeof(Usart3_recev_buff),strlen(ServerIpSet)); //设置服务器IP
// pSmsRecevBuff = Find_String(pBuff,"casic_set_server_ip_"); //设置服务器IP
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(ServerIpSet)-16))))
{
pSmsRecevData =pSmsRecevBuff +strlen(ServerIpSet);
for(i=0;i<16;i++)
{
if(((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9'))||(pSmsRecevData[i]=='.'))
{;}
else
{
break;
}
}
if((i>15)||(i<7)) //输入数据不合法,直接丢弃,不更新配置信息,并给出错误提示
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
// i=15; //i表示有效IP地址长度,限制长度,防止溢出
}
else
{
memset(DeviceConfig.ServerIP,0x00,sizeof(DeviceConfig.ServerIP));
memcpy(DeviceConfig.ServerIP, pSmsRecevData, i);
UploadFlag = UploadFlash(DeviceConfig.ServerIP, 5);
}
if(UploadFlag ==1)
{
printf("\r\nServer IP upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rServer IP upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清零
snprintf( MessageSend , sizeof(MessageSend),"\rserver IP is %s \r", DeviceConfig.ServerIP );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput server IP not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput server IP not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
//(6)设置网络服务端口号
pSmsRecevBuff = Find_SpecialString(Usart3_recev_buff, ServerPortSet,sizeof(Usart3_recev_buff),strlen(ServerPortSet)); //设置服务器端口号
// pSmsRecevBuff = Find_String(pBuff,"casic_set_server_port_"); //设置服务器端口号
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(ServerPortSet)-6))))
{
pSmsRecevData =pSmsRecevBuff +strlen(ServerPortSet);
for(i=0;i<6;i++)
{
if((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9'))
{;}
else
{
break;
}
}
if((i<2)||(i>5)) //输入数据不合法,直接丢弃,不更新配置信息,并给出错误提示,端口号范围有待确认
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
// i=5; //i表示有效端口号长度,限制长度,防止溢出
}
else
{
memset(DeviceConfig.ServerPort,0x00,sizeof(DeviceConfig.ServerPort));
memcpy(DeviceConfig.ServerPort, pSmsRecevData, i);
UploadFlag = UploadFlash(DeviceConfig.ServerPort, 6);
}
if(UploadFlag ==1)
{
printf("\r\nServer port upload success!!:%s\r\n",pSmsRecevData); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rServer port upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清零
snprintf( MessageSend , sizeof(MessageSend),"\rServer port is %s\r", DeviceConfig.ServerPort );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput server port not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput server port not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
//(7)设置低浓度阈值
// pSmsRecevBuff = Find_String(pBuff,"casic_set_alarm_threshold_"); //设置低浓度报警阈值
pSmsRecevBuff = Find_SpecialString(Usart3_recev_buff, LowAlarmThresholdSet,sizeof(Usart3_recev_buff),strlen(LowAlarmThresholdSet)); //设置报警阈值
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(LowAlarmThresholdSet)-3)))) //低浓度阈值数据:XX.XX
{
pSmsRecevData =pSmsRecevBuff +strlen(LowAlarmThresholdSet);
for(i=0;i<5;i++)
{
if(((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9'))||(pSmsRecevData[i]=='.'))
{;}
else
{
break;
}
}
if(i==0)
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
}
else
{
if(i>5)
{
i=5; //i表示有效报警阈值长度,限制长度,防止溢出
}
memset(ReceiveTemp,0x00,sizeof(ReceiveTemp));
memcpy(ReceiveTemp, pSmsRecevData, i);
DeviceConfig.LowAlarmLevel .Data_Float = char_to_float(ReceiveTemp);
printf("\r\n-----data before write in flash!----%f----",DeviceConfig.LowAlarmLevel .Data_Float); //在写入FLASH之前,输出测试
UploadFlag = UploadFlash((char*)DeviceConfig.LowAlarmLevel.Data_Hex ,7);
}
if(UploadFlag ==1)
{
printf("\r\nlow Alarm threshold upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rlow Alarm threshold upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清零
snprintf( MessageSend , sizeof(MessageSend),"\rlow alarm level is %0.2f \r", DeviceConfig.LowAlarmLevel .Data_Float );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput alarm threshold not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput alarm threshold not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
///////////////////////////////////////////////增加配置参数/////////////////////////////////////////////////////////
// char StartCollectTime[30]="casic_start_collect_time_"; //首次采集时间设置
// char CollectPeriod[30] ="casic_collect_period_"; //采集周期设置
// char SendCount[30] ="casic_send_count_"; //上传周期设置
// char RetryNum[30] ="casic_retry_number_"; //重新上传次数设置
//(8)设置第一次采集时间
//pSmsRecevBuff = Find_String(pBuff,"casic_start_collect_time_"); //设置第一次采集时间
pSmsRecevBuff = Find_SpecialString(pBuff, StartCollectTime,strlen(pBuff),strlen(StartCollectTime)); //设置第一次采集时间
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(StartCollectTime)-1))))
{
pSmsRecevData =pSmsRecevBuff +strlen(StartCollectTime);
for(i=0;i<4;i++)
{
if(((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9')))
{;}
else
{
break;
}
}
if(i==0)
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
}
else
{
if(i>4)
{
i=4; //i表示有效第一次采集时间,限制长度,防止溢出
}
memset(ReceiveTemp,0x00,sizeof(ReceiveTemp));
memcpy(ReceiveTemp, pSmsRecevData, i);
DeviceConfig.CollectStartTime = char_to_int(ReceiveTemp);
ConfigData.CollectStartTime_Byte [0] = DeviceConfig.CollectStartTime >> 8;
ConfigData.CollectStartTime_Byte [1] = DeviceConfig.CollectStartTime & 0xff;
//printf("\r\n-----data before write in flash!----%s----",CollectStartTime_data); //在写入FLASH之前,输出测试
printf("\r\n-----data before write in flash!----%d----",DeviceConfig.CollectStartTime); //在写入FLASH之前,输出测试
for(j=0;j<2;j++)
printf("\r\n-----data before write in flash!----%x----",ConfigData.CollectStartTime_Byte [j]);
UploadFlag = UploadFlash((char*)ConfigData.CollectStartTime_Byte , 8);
}
if(UploadFlag ==1)
{
printf("\r\nStart Collect Time upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rStart Collect Time upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清空
snprintf( MessageSend , sizeof(MessageSend),"\rstart collect time is %d\r", DeviceConfig.CollectStartTime );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput Start Collect Time not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput Start Collect Time not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
// char StartCollectTime[30]="casic_start_collect_time_"; //首次采集时间设置
// char CollectPeriod[30] ="casic_collect_period_"; //采集周期设置
// char SendCount[30] ="casic_send_count_"; //上传周期设置
// char CollectNum[30] ="casic_collect_number_"; //一次采集数量设置
// char RetryNum[30] ="casic_retry_number_"; //重新上传次数设置
//(10)设置重新上传次数
pSmsRecevBuff = Find_SpecialString(pBuff, RetryNum,strlen(pBuff),strlen(RetryNum)); //设置重传次数
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(RetryNum)-1))))
{
pSmsRecevData =pSmsRecevBuff +strlen(RetryNum);
for(i=0;i<2;i++)
{
// if(pSmsRecevData[i]==0x0D)
// {
// break;
// }
if(((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9')))
{;}
else
{
break;
}
}
if(i==0)
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
}
else
{
if(i>2)
{
i=2; //i表示有效,限制长度,防止溢出
}
memset(ReceiveTemp,0x00,sizeof(ReceiveTemp));
memcpy(ReceiveTemp, pSmsRecevData, i);
DeviceConfig.RetryNum = char_to_int(ReceiveTemp);
printf("\r\n-----data before write in flash!----%s----",(char*)ReceiveTemp); //在写入FLASH之前,输出测试
printf("\r\n-----data before write in flash!----%d----", DeviceConfig.RetryNum); //在写入FLASH之前,输出测试
printf("\r\n-----data before write in flash!----%x----", DeviceConfig.RetryNum);
UploadFlag = UploadFlash((char*)&DeviceConfig.RetryNum , 10);
}
if(UploadFlag ==1)
{
printf("\r\nStart RetryNum upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rStart RetryNum upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清空
snprintf( MessageSend , sizeof(MessageSend),"\r Retry Number is %d \r", DeviceConfig.RetryNum );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput RetryNum not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput RetryNum not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
// char StartCollectTime[30]="casic_start_collect_time_"; //首次采集时间设置
// char CollectPeriod[30] ="casic_collect_period_"; //采集周期设置
// char SendCount[30] ="casic_send_count_"; //上传周期设置
// char CollectNum[30] ="casic_collect_number_"; //一次采集数量设置
// char RetryNum[30] ="casic_retry_number_"; //重新上传次数设置
//(11)设置高浓度报警阈值
pSmsRecevBuff = Find_SpecialString(Usart3_recev_buff, HighAlarmThresholdSet,sizeof(Usart3_recev_buff),strlen(HighAlarmThresholdSet)); //设置报警阈值
if((pSmsRecevBuff != NULL)&&(pSmsRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-strlen(HighAlarmThresholdSet)-3)))) //高浓度阈值数据:XX.XX
{
pSmsRecevData =pSmsRecevBuff +strlen(HighAlarmThresholdSet);
for(i=0;i<5;i++)
{
if(((pSmsRecevData[i]>='0')&&(pSmsRecevData[i]<='9'))||(pSmsRecevData[i]=='.'))
{;}
else
{
break;
}
}
if(i==0)
{
printf("\r\nMessage set input ERROR!!\r\n"); //测试使用
}
else
{
if(i>5)
{
i=5; //i表示有效报警阈值长度,限制长度,防止溢出
}
memset(ReceiveTemp,0x00,sizeof(ReceiveTemp));
memcpy(ReceiveTemp, pSmsRecevData, i);
DeviceConfig.HighAlarmLevel .Data_Float = char_to_float(ReceiveTemp);
printf("\r\n-----data before write in flash!----%f----",DeviceConfig.HighAlarmLevel .Data_Float); //在写入FLASH之前,输出测试
UploadFlag = UploadFlash((char*)DeviceConfig.HighAlarmLevel.Data_Hex ,11);
}
if(UploadFlag ==1)
{
printf("\r\nHigh Alarm threshold upload success!!\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rHigh Alarm threshold upload success!!\r");
Delay_ms(2000); //短信发送缓冲
memset(MessageSend,0x00,sizeof(MessageSend)); //将发送数组清空
snprintf( MessageSend , sizeof(MessageSend),"\rhigh alarm level is %0.2f\r", DeviceConfig.HighAlarmLevel .Data_Float );
printf("\r\nSend char to phone %s\r\n",MessageSend); //将需要发送的短信利用串口显示
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(MessageSend); //短信发送配置信息
}
else //对非法输入值给出提示(负值不做非法处理,自动取绝对值)
{
printf("\r\nInput alarm threshold not correct!\r\nPlease check and retry.\r\n"); //测试使用
Delay_ms(2000); //短信发送缓冲
Sms_Send("\rInput alarm threshold not correct!\rPlease check and retry.\r");
}
UploadFlag =0; //复位变量
pSmsRecevBuff = NULL; //复位变量
}
// char StartCollectTime[30]="casic_start_collect_time_"; //首次采集时间设置
// char CollectPeriod[30] ="casic_collect_period_"; //采集周期设置
// char SendCount[30] ="casic_send_count_"; //上传周期设置
// char CollectNum[30] ="casic_collect_number_"; //一次采集数量设置
// char RetryNum[30] ="casic_retry_number_"; //重新上传次数设置
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*****************************************查询功能****************************************************************/
// pSmsRecevBuff = Find_String(pBuff,"casic_current_data"); //查询液位信息
pSmsRecevBuff = Find_SpecialString(pBuff, SensorDataInquire,sizeof(Usart3_recev_buff),strlen(SensorDataInquire)); //查询传感器采集数据
if(pSmsRecevBuff != NULL) //有查询液位数据查询命令
{
//DataMessageSend();
if(DataCollectCount==0) //数据采集完成则直接通过短信发送当前液位信息
{
DataMessageSend();
}
else
{
ConfigData.SensorDataInquireFlag =1; //液位数据未进行采集时,收到查询命令,将标志变量置1,当液位数据采集完成时通过短信发送当前液位信息
}
pSmsRecevBuff = NULL; //复位变量
}
pSmsRecevBuff = Find_SpecialString(pBuff, SensorSetInquire,sizeof(Usart3_recev_buff),strlen(SensorSetInquire)); //查询设备配置信息
if(pSmsRecevBuff != NULL) //
{
Delay_ms(2000); //短信发送缓冲
SensorSetMessage();
Delay_ms(2000); //短信发送缓冲
SensorSetMessage();
//ConfigData.DeviceSetInquireFlag =1; //液位数据未进行采集时,收到查询命令,将标志变量置1,当液位数据采集完成时通过短信发送当前液位信息
pSmsRecevBuff = NULL; //复位变量
}
}
}
}
/*******************************************************************************
* Function Name : 将配置信息利用短信的方式发送至手机
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void SensorSetMessage(void)
{
char SensorSet[200]={0x00};
uint8_t counter;
uint8_t i;
char temp[20]={0x00};
// strcpy(SensorSet,"\r PhoneNum:");
//counter=strlen(SensorSet)-1;
strcat(SensorSet,"\rPhone Num:"); //ALARM PHONE NUM
snprintf( temp , sizeof(temp),"%s,", DeviceConfig.AlarmPhoneNum );
strcat(SensorSet,temp);
strcat(SensorSet,"IP:"); //IP
snprintf( temp , sizeof(temp),"%s,", DeviceConfig.ServerIP );
strcat(SensorSet,temp);
strcat(SensorSet,"PORT:"); //PORT
snprintf( temp , sizeof(temp),"%s,", DeviceConfig.ServerPort );
strcat(SensorSet,temp);
strcat(SensorSet,"LOWLEVEL:"); //LowAlarmLevel
snprintf( temp , sizeof(temp),"%0.2f,", DeviceConfig.LowAlarmLevel.Data_Float );
strcat(SensorSet,temp);
strcat(SensorSet,"HIGHLEVEL:"); //HighAlarmLevel
snprintf( temp , sizeof(temp),"%0.2f,", DeviceConfig.HighAlarmLevel.Data_Float );
strcat(SensorSet,temp);
strcat(SensorSet,"StartTime:"); //Start time
snprintf( temp , sizeof(temp),"%d,", DeviceConfig.CollectStartTime );
strcat(SensorSet,temp);
strcat(SensorSet,"CollectPeriod:"); //CollectPeriod
snprintf( temp , sizeof(temp),"%d,", DeviceConfig.CollectPeriod );
strcat(SensorSet,temp);
strcat(SensorSet,"SendCount:"); //SendCount
snprintf( temp , sizeof(temp),"%d,", DeviceConfig.SendCount );
strcat(SensorSet,temp);
strcat(SensorSet,"RETRY NUM:"); //RETRY NUM
snprintf( temp , sizeof(temp),"%d,", DeviceConfig.RetryNum );
strcat(SensorSet,temp);
strcat(SensorSet,"BATTER:"); //BATTER Capacity
snprintf( temp , sizeof(temp),"%d,\r", DeviceConfig.BatteryCapacity );
strcat(SensorSet,temp);
Delay_ms(2000); //短信发送缓冲
printf("\r\n the device set parametor is %s,\r\n",SensorSet);
//Sms_Send(SensorSet);
Delay_ms(2000); //短信发送缓冲
AlarmSMS_Send(SensorSet);
}
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
//void Receive_Analysis_GPRS(void)
//{
// char* pRecevBuff =NULL;
// char updata_set[7] = {0x50,0x00,0x14,0x01,0x00,0x00,0x34}; //服务器更新配置命令
// char complete_set[9] = {0x50,0x00,0x09,0x02,0x00,0x00,0x34,0x00,0x03};//服务器请求结束命令
// char DataRecv_State[8] = {0x50,0x00,0x09,0x02,0x00,0x00,0x34,0x22}; //服务器发送液位数据接收状态命令
//
// int TimeSet[7] ={0}; //用于检验服务器下发的时间配置的合法性
// unsigned char ReceiveState[4] ={0x00}; //记录服务器各批次数据接收状态
// unsigned char ReceiveFlag =0xFF; //记录服务器总数据接收状态
// uint16_t PeriodSet =0; //用于检验服务器下发的数据采集周期配置的合法性
// uint16_t CountSet =0; //用于检验服务器下发的数据上传次数配置的合法性
// u8 Resp_Count=3; //Response帧发送尝试次数
// int i=0;
// u8 OpCode=0;
///////////////////////////////////////验证有无收到服务器更新配置应答////////////////////////////////
// pRecevBuff = Find_SpecialString(Usart3_recev_buff, updata_set, sizeof(Usart3_recev_buff), sizeof(updata_set)); //检查有无配置更新命令请求
// if((pRecevBuff != NULL)&&(pRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-19)))) //防止指针越界
// {
// #if DEBUG_TEST
// printf("\r\nTime correct fream receive ok!!\r\n"); //测试使用
// #endif
// SetRev_OK =1; //配置接收成功,标志变量置位
// PeriodSet =(pRecevBuff[8]*256) +pRecevBuff[9];
// CountSet =(pRecevBuff[10]*256) +pRecevBuff[11];
// for(i=0;i<7;i++)
// {
// TimeSet[i] =pRecevBuff[i+12];
// }
// OpCode =pRecevBuff[7];
////****************************参数配置合法性验证*************************//
// if(OpCode == 0xC1) //只有当命令是0xC1时才更新配置
// {
// if((PeriodSet>0)&&(CountSet>0))
// {
//// if(CountSet>1440) //当服务器下发配置大于1440时,说明要求主机不进入休眠状态,发行版需要关闭此功能,对非法数据进行屏蔽,不更新当前配置
//// {
////// Alive =1;
////// DeviceConfig.SendCount =0x0018; //
////// DeviceConfig.CollectPeriod =0x0001; //
//// #if DEBUG_TEST
//// printf("\r\nServer config ERROR!!\r\n"); //测试使用
//// #endif
//// }
// if((PeriodSet*CountSet)<=1440)
// {
// if(Alive ==1)
// {
// Alive =0; //恢复正常休眠模式
// }
// LSLIQUSET_Handle(pRecevBuff, &DeviceConfig);
// }
// else
// {
// #if DEBUG_TEST
// printf("\r\nConfig not correct!!\r\n"); //测试使用
// #endif
// }
// }
// else
// {
// #if DEBUG_TEST
// printf("\r\nConfig not correct!!\r\n"); //测试使用
// #endif
// }
// }
////****************************时间配置合法性验证*************************//
// if((OpCode == 0xC1)||(OpCode == 0xC2)) //命令为0xC1或0xC2时,均更新时间配置
// {
// if((TimeSet[0]>=0)&&(TimeSet[0]<=60)&&(TimeSet[1]>=0)&&(TimeSet[1]<=60)&&(TimeSet[2]>=0)&&(TimeSet[2]<=23)
// &&(TimeSet[4]>=1)&&(TimeSet[4]<=31)&&(TimeSet[5]>=1)&&(TimeSet[5]<=12)&&(TimeSet[6]>=0)&&(TimeSet[5]<=99)) //特殊月份有待调整
// {
// LSTIMESET_Handle(pRecevBuff, &DeviceConfig);
// Time_Auto_Regulate(&DeviceConfig); //通过服务器进行RTC时钟校准,默认服务器发送的设置请求都需要进行校时操作
// while(Resp_Count!=0)
// {
// if(RespRev_OK ==0) //是否收到服务器下发的配置会话结束帧标志变量
// {
// LSLIQUSET_Response(&DeviceConfig);
// Delay_ms(4000);
// DMA_UART3_RecevDetect( DATARECEV );
// }
// else
// {
// RespRev_OK=0;
// break;
// }
// Resp_Count--;
// }
// }
// else
// {
// #if DEBUG_TEST
// printf("\r\nTime not correct!!\r\n"); //测试使用
// #endif
// }
//
// }
// pRecevBuff = NULL;
// }
///////////////////////////////////////验证有无收到服务器会话结束命令////////////////////////////////
// pRecevBuff = Find_SpecialString(Usart3_recev_buff, complete_set, sizeof(Usart3_recev_buff), sizeof(complete_set));
// if((pRecevBuff != NULL) &&(pRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-12)))) //防止指针越界
// {
// Section_Handle();
// RespRev_OK =1;
//
// #if DEBUG_TEST
// printf("\r\nSECTION SEND TEST:"); //调试使用
// for(i=0;i<12;i++)
// {
// printf("-%x-",pRecevBuff[i]); //调试使用
// } //调试使用
// printf("\r\n"); //调试使用
// #endif
// pRecevBuff =NULL;
// }
///////////////////////////////////////验证有无收到服务器下发的液位数据接收状态//////////////////////
// pRecevBuff = Find_SpecialString(Usart3_recev_buff, DataRecv_State, sizeof(Usart3_recev_buff), sizeof(DataRecv_State));
// if((pRecevBuff != NULL) &&(pRecevBuff <(Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1-12)))) //防止指针越界
// {
// for(i=0;i<4;i++)
// {
// ReceiveState[i] =pRecevBuff[8+i];
// ReceiveFlag =ReceiveFlag & ReceiveState[i];
// }
// if(ReceiveFlag == 0xFF)
// {
// #if DEBUG_TEST
// printf("\r\n液位数据接收成功!!\r\n"); //调试使用
// #endif
// DatRev_OK =1; //数据完全正确接收标志变量
// for(i=0;i<4;i++)
// {
// ReceiveState[i] =0x00; //接收状态复位
// }
// }
// else
// {
// ;//数据有丢失,需要重传,后续有待完善
// }
// pRecevBuff =NULL;
// }
//
//}
/*******************************************************************************
* Function Name : GPRS_Receive_NetLogin
* Description : 接收GPRS上网注册的数据
* Input : None
* Output : None
* Return : 上网注册状态
*******************************************************************************/
unsigned char GPRS_Receive_NetLogin(void)
{
char* pRecevBuff =NULL;
#if DEBUG_TEST
printf("\r\nGPRS Net Login Receive Analysis ...\r\n"); //测试使用
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////
pRecevBuff = Find_SpecialString(Usart3_recev_buff, "+CGREG: 1,1", sizeof(Usart3_recev_buff), 11); //检查模块入网状态
if(pRecevBuff!=NULL)
{
#if DEBUG_TEST
printf("\r\nNet Register OK!!\r\n");
#endif
CSQ_OK =1; //握手有响应时,标志变量置1
pRecevBuff =NULL;
return 1;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
pRecevBuff = Find_SpecialString(Usart3_recev_buff, "+CGREG: 1,5", sizeof(Usart3_recev_buff), 11); //检查模块入网状态
if(pRecevBuff!=NULL)
{
#if DEBUG_TEST
printf("\r\nNet Register OK!!Roaming on!!\r\n");
#endif
CSQ_OK =1; //握手有响应时,标志变量置1
pRecevBuff =NULL;
return 1;
}
return 0;
}
/*******************************************************************************
* Function Name : GPRS_Receive_TcpConnect
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
unsigned char GPRS_Receive_TcpConnect(void)
{
char* pRecevBuff =NULL;
#if DEBUG_TEST
printf("\r\nTCP Connect is in process...\r\n"); //测试使用
#endif
pRecevBuff = Find_SpecialString(Usart3_recev_buff, "CONNECT", sizeof(Usart3_recev_buff), 7); //检查模块入网状态
//pRecevBuff = Find_SpecialString(Usart3_recev_buff, "CONNECT", sizeof(Usart3_recev_buff), 10); //检查模块入网状态
if(pRecevBuff != NULL) //网络连接出现故障时,对3G模块复位
{
return 1;
}
return 0;
}
/*******************************************************************************
* Function Name : GPRS_Receive_DataAnalysis
* Description : 3G模块进行数据的第一层解析
* Input : None
* Output : None
* Return : None
*******************************************************************************/
unsigned char GPRS_Receive_DataAnalysis(u8* pDeviceID, u16 sNodeAddress)
{
u16 Recev_Flag2 =0; //接收数据正确性标志变量
char* pRecevBuff =NULL;
char NewMessageIndicate[7] ="+CMGL:"; //收到未读短信指示
char RecevFromCollector[2]={0xA3,0x20}; //接收服务器发送的数据标志序列
u8 PayloadLen =0;
u16 CrcVerify =0x0000;
u16 CrcRecev =0x0000;
int k;
#if DEBUG_TEST
printf("\r\n接收数据解析!!\r\n"); //测试使用
#endif
//////////////////////////////////////////////////////////////////////////////////
pRecevBuff = Find_SpecialString(Usart3_recev_buff, NewMessageIndicate,sizeof(Usart3_recev_buff),strlen(NewMessageIndicate)); //检查是否收到短信
{
if(pRecevBuff !=NULL)
{
#if DEBUG_TEST
printf("\r\n接收短信数据解析!!\r\n"); //测试使用
#endif
Sms_Analysis(pRecevBuff); //接收短信解析
pRecevBuff =NULL; //复位查询指针
Delay_ms(3000); //等待时间不能太短,否则无法成功清空短信记录
mput("AT+CMGD=1,3"); //删除全部已发、未发和已读短信
Delay_ms(500);
return 1;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
pRecevBuff = Find_SpecialString(Usart3_recev_buff,RecevFromCollector,sizeof(Usart3_recev_buff),sizeof(RecevFromCollector)); //检查有无收到主站回复
if((pRecevBuff != NULL)&&(pRecevBuff< Usart3_recev_buff+(sizeof(Usart3_recev_buff)-1))) //防止指针越界
{
#if DEBUG_TEST
printf("\r\n接收上位机数据解析!!\r\n"); //测试使用
#endif
if(((u8)pRecevBuff[0]==0xA3)&&(pRecevBuff[1]==0x20))//第二层校验
{
Treaty_Data_Analysis(((u8*)pRecevBuff), &Recev_Flag2, pDeviceID, sNodeAddress); //解析接收数据
}
else
{
#if DEBUG_TEST
printf("\r\nReceive data not correct!!\r\n"); //测试使用
#endif
Delay_ms(500);
pRecevBuff =NULL;
return 0;
}
}
return Recev_Flag2;
#if DEBUG_TEST
printf("\r\n接收数据解析完成!!\r\n"); //调试使用
#endif
}
/*******************************************************************************
* Function Name : XX
* Description : 初始化一些配置参数
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void ConfigData_Init(struct Sensor_Set* Para)
{
// uint8_t HexArry[7] ={0x00};
char CharArry[16] ={0x00};
// char* pCharArry =NULL;
uint8_t length =0;
uint16_t Temp=0;
float fTemp=0;
// uint8_t Flag =0; //合法性判断
// uint8_t FlashStateIndicate[9] = {0x00}; //"FLASH_OK";
// uint8_t FlashStateFlag =0; //用于指示Flash状态是否正常,为0时表示正常,为1时表示发生故障
int i;
#if DEBUG_TEST
printf("\r\nConfigData_Init start...\r\n"); //测试使用
#endif
BKP_TamperPinCmd(DISABLE); //
/******************************************************************************************/
//(2)采集周期
DataRead_From_Flash(0,2,0, ConfigData.CollectPeriod_Byte,2); //从Flash中读取液位计采集间隔
Temp =ConfigData.CollectPeriod_Byte[0]*256 + ConfigData.CollectPeriod_Byte[1];
//printf("------------%d------------",Temp);
if((Temp>0)&&(Temp<=60)) //可配置1~60分钟进行数据采集间隔
{
Para->CollectPeriod = Temp;
}
else
{
Para->CollectPeriod =60; //每隔15分钟采集一次数据。
}
printf("\r\n**************采集周期-->> %d ***********\r\n",Para->CollectPeriod); //输出测试
//(3)上报周期
DataRead_From_Flash(0,3,0, ConfigData.SendCount_Byte ,2); //从Flash中读取上传周期
Temp =ConfigData.SendCount_Byte[0]*256 + ConfigData.SendCount_Byte[1];
//printf("------------%d------------",Temp);
if((Temp>0)&&(Temp<=1440))
{
Para->SendCount = Temp;
}
else
{
Para->SendCount =60; //1小时发送一次数据
}
printf("\r\n**************上报周期-->> %d *********** \r\n",Para->SendCount ); //输出测试
//(4)报警手机号
DataRead_From_Flash(0,4,0, (u8*)ConfigData.AlarmPhoneNum,15); //从Flash中读取预设报警手机卡号
for(Temp=0;Temp<15;)
{
if((ConfigData.AlarmPhoneNum[Temp] >='0')&&(ConfigData.AlarmPhoneNum[Temp] <='9'))
{
Temp++;
}
else
{
break;
}
}
length =Temp;
if(((length==11)||(length==13)||(length==15)) && (ConfigData.AlarmPhoneNum[0] == '8') && (ConfigData.AlarmPhoneNum[1] == '6')) //物联网卡必须加86前缀才能成功发短信,所以最大长度为15
{
memcpy(Para->AlarmPhoneNum, ConfigData.AlarmPhoneNum, length);
}
else
{
memcpy(Para->AlarmPhoneNum,"861064617178004",15); //读取数据无效时,初始化报警电话,后续需要根据卡号做相应调整 测试手机号码
}
printf("\r\n**************报警电话-->> %s *********** \r\n", Para->AlarmPhoneNum ); //输出测试
//(5)网络服务IP号
DataRead_From_Flash(0,5,0, (u8*)ConfigData.ServerIP,15); //从Flash中读取预设服务器IP
length = strlen(ConfigData.ServerIP );
for(Temp=0;Temp<15;)
{
if(((ConfigData.ServerIP[Temp] >='0')&&(ConfigData.ServerIP[Temp] <='9'))||(ConfigData.ServerIP[Temp] =='.'))
{
Temp++;
}
else
{
break;
}
}
length =Temp;
if(9<length<15) //对IP地址合法性做初步筛选,后续有待完善
{
memcpy(Para->ServerIP, ConfigData.ServerIP, length);
}
else
{
memcpy(Para->ServerIP,"172.16.17.32",14); //读取数据无效时,初始化服务器IP
}
printf("\r\n**************网络IP-->> %s *********** \r\n", Para->ServerIP ); //输出测试
//(6) 网络服务端口号
DataRead_From_Flash(0,6,0, (u8*)ConfigData.ServerPort,5); //从Flash中读取预设服务器端口号
// length = strlen(ConfigData.SMS_Set_ServerPort);
for(Temp=0;Temp<5;)
{
if((ConfigData.ServerPort[Temp] >='0')&&(ConfigData.ServerPort[Temp] <='9'))
{
Temp++;
}
else
{
break;
}
}
length =Temp;
if(length>0) //对服务器端口号合法性做初步筛选,后续有待完善
{
memcpy(Para->ServerPort, ConfigData.ServerPort, length);
}
else
{
memcpy(Para->ServerPort,"2017",4); //读取数据无效时,初始化服务器端口号
}
printf("\r\n**************网络端口号-->> %s *********** \r\n", Para->ServerPort ); //输出测试
//(7)低浓度报警阈值
DataRead_From_Flash(0,7,0, ConfigData.LowAlarmLevel .Data_Hex ,4); //从Flash中读取预设报警阈值
fTemp = ConfigData.LowAlarmLevel .Data_Float ;
//printf("\r\n---read low level ---%f----\r\n",fTemp ); //打印FLASH读取的原始数据
if( (0.0<fTemp ) && ( fTemp <25.0) )
Para->LowAlarmLevel .Data_Float =ConfigData.LowAlarmLevel .Data_Float ;
else
{
Para->LowAlarmLevel .Data_Float =25.0; //读取数据无效时,将报警阈值设为25.0,当报警阈值为0时,不会触发报警事件
}
printf("\r\n**************低报警浓度-->> %0.2f ************\r\n", Para->LowAlarmLevel .Data_Float ); //输出测试
// (8)开始采集时间
DataRead_From_Flash(0,8,0,ConfigData.CollectStartTime_Byte ,2); //从Flash中读取第一次采集时间
//Temp = char_to_int(CharArry);
Temp =ConfigData.CollectStartTime_Byte [0]*256 + ConfigData.CollectStartTime_Byte [1];
//printf("\r\n---read CollectStartTime ---%d----\r\n",Temp ); //打印FLASH读取的原始数据
if((Temp>=0)&&(Temp<=1440))
{
Para->CollectStartTime = Temp;
}
else
{
Para->CollectStartTime = 0; //第一次采集时间为0点钟
}
printf("\r\n**************开始采集时间-->> %d ***********\r\n", Para->CollectStartTime ); //输出测试
//(9)已采集数量
DataRead_From_Flash(0,9,0, &(ConfigData.CollectNum) ,1); //从Flash中读取当前采集数量
// printf("\r\n---read retry number ---%s----\r\n",(u8*)ConfigData.CollectNum_Byte ); //打印FLASH读取的原始数据
//Temp =ConfigData.CollectNum_Byte [0]*256 + ConfigData.CollectNum_Byte [1];
Temp = ConfigData.CollectNum;
//printf("\r\n---read CollectNum ---%d----\r\n",Temp ); //打印FLASH读取的原始数据
// if((0 <=ConfigData.CollectNum )&&(ConfigData.CollectNum <= MAX_COLLECTNUM))
// {
// if(ConfigData.CollectNum <=( Para->SendCount /Para->CollectPeriod ))
// { Para->CollectNum = ConfigData.CollectNum; }
// else
// { Para->CollectNum =( Para->SendCount /Para->CollectPeriod );}
// }
// else
// {
// Para->CollectNum = ( Para->SendCount /Para->CollectPeriod ) ; //当前采集的传感器数据量
// }
printf("\r\n**************已采集数量-->> %d ***********\r\n", Temp ); //输出测试
//(10)重传次数
DataRead_From_Flash(0,10,0, &(ConfigData.RetryNum ) ,1); //从Flash中读取重传次数
//printf("\r\n---read retry number ---%d----\r\n",ConfigData.RetryNum ); //打印FLASH读取的原始数据
Temp =ConfigData.RetryNum ;
if((Temp>0)&&(Temp<=10))
{
Para->RetryNum = Temp;
}
else
{
Para->RetryNum =3; //默认为3
}
printf("\r\n**************重传次数-->> %d ***********\r\n", Para->RetryNum ); //输出测试
//(11)高浓度报警阈值
DataRead_From_Flash(0,11,0, ConfigData.HighAlarmLevel .Data_Hex ,4); //从Flash中读取高浓度报警
//printf("\r\n---read high alarm level ---%f----\r\n",ConfigData.HighAlarmLevel .Data_Float ); //打印FLASH读取的原始数据
fTemp =ConfigData.HighAlarmLevel .Data_Float ;
if((fTemp>0.0) && (fTemp < 50.0) && (fTemp > ConfigData.LowAlarmLevel .Data_Float ))
{
Para->HighAlarmLevel .Data_Float = fTemp;
}
else
{
Para->HighAlarmLevel .Data_Float = 50.0; //报警高浓度阈值默认为50%
}
printf("\r\n**************高报警浓度-->> %0.2f ***********\r\n", Para->HighAlarmLevel .Data_Float ); //输出测试
//(12)设备已工作次数
DataRead_From_Flash(0,12,0, (ConfigData.WorkNum_Byte),4); //从Flash中读取已工作次数
Temp=ConfigData.WorkNum_Byte [0]*256+ConfigData.WorkNum_Byte [1];
Para->WorkNum = Temp;
printf("\r\n**************工作次数-->> %d ***********\r\n", Para->WorkNum); //输出测试
//(13)电池电量
printf("\r\n**************电池电量-->> %d%% ***********\r\n", Para->BatteryCapacity=DS2780_Test()); //输出测试
// Para->Time_Sec =0x00;
// Para->Time_Min =0x00;
// Para->Time_Hour =0x00;
// Para->Time_Mday =0x00;
// Para->Time_Mon =0x00;
// Para->Time_Year =0x00;
// Para->BatteryCapacity =0x64; //电池电量,暂定为100%
Para->MessageSetFlag =0;
}
/**********************************************END******************************************/
<file_sep>/User/test/test.c
/***************************本程序为初始化设备********************************/
#include "test.h"
extern struct Sensor_Set DeviceConfig;
//(1)配置采集相关信息,分别为采集周期、上传周期、重传次数、低浓度阈值、高浓度阈值
void write_collect_parameter_to_flash(void) //利用该函数可进行燃气智能终端采集配置 配置3G版本
{
uint8_t collect_period[2]={00,60}; //采集周期 默认60分钟采集一次
uint8_t send_out[2]={00,60}; //上传周期 默认60分钟上传一次
uint8_t retry_num = 3; //重传次数
uint8_t first_collect[2]={00,00}; //第一次采集时间
uint8_t collect_num = 0; //已采集数量
uint8_t error_state[2]={1,1}; //初始化异常信息,第一次初始化均为正常信号
union Hex_Float low_alarm;
union Hex_Float high_alarm;
low_alarm.Data_Float =25.0;
high_alarm.Data_Float =50.0;
//PowerON_Flash();
DataWrite_To_Flash(0,2,0,collect_period,2);
DataWrite_To_Flash(0,3,0,send_out,2);
DataWrite_To_Flash(0,7,0,low_alarm.Data_Hex ,4);
DataWrite_To_Flash(0,8,0,first_collect,2);
DataWrite_To_Flash(0,9,0,&collect_num,1);
DataWrite_To_Flash(0,10,0,&(retry_num),1);
DataWrite_To_Flash(0,11,0,high_alarm.Data_Hex ,4);
DataWrite_To_Flash(2,1,0,error_state ,2); //写入异常状态
}
//(2)配置3G模块信息, 报警电路号码、IP端口号、PORT端口号
void write_3G_parameter_to_flash(void)
{
char phone_num[16]={"861064617178004"}; //报警电话号码
// char ip[16]={"192.168.127.12"}; //网络服务IP地址
// char ip[16]={"192.168.127.12"}; //网络服务IP地址
char ip[16]={"192.168.127.12"}; //网络服务IP地址
// char port[6]={"2020"}; //网络服务端口号
// char ip[16]={"192.168.1.115"}; //网络服务IP地址
char port[6]={"2017"}; //网络服务端口号
////////////////////将参数写入FLASH中////////////////////////////
DataWrite_To_Flash(0,4,0,phone_num,strlen(phone_num));
DataWrite_To_Flash(0,5,0,ip,strlen(ip));
DataWrite_To_Flash(0,6,0,port,strlen(port));
}
//(3)配置433模块信息
void write_433_parameter_to_flash(void)
{
}
//(4)配置时钟信息
void Set_Time(void)
{
DeviceConfig.Time_Year = 0x10; //2016年
DeviceConfig.Time_Mon = 0x09; //8月
DeviceConfig.Time_Mday = 0x08; //23
DeviceConfig.Time_Hour = 0x08; //
DeviceConfig.Time_Min = 0x34;
DeviceConfig.Time_Sec = 0x00;
Time_Auto_Regulate(&DeviceConfig);
}
void test_sensor_to_flash(void) //将传感器数据写入FLASH内,并读出来
{
struct SenserData TestSensorData;
uint8_t sensordata[7]={0x00}; //将传感器数据写入FLASH
uint8_t readdata[7]={0x00};
uint8_t i;
TestSensorData.Ch4Data .Data_Float = 3.9; //利用假数据进行调试
//TestSensorData.CollectTime =(DeviceConfig.Time_Hour)*60 +(DeviceConfig.Time_Min); //第一组数据采集时间
TestSensorData.CollectTime = 40;
TestSensorData.DataCount = 1; //当前采集的个数
//Delay_ms(500);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DataCollectCount = pGetData->DataCount;
//ConfigData.CollectNum = DataCollectCount;
//DataWrite_To_Flash(0,9,0,&pGetData.DataCount,1);
////////////////////////////////将采集的传感器数据写入FLASH///////////////////////////////////////////////////
sensordata[0]= TestSensorData.CollectTime >> 8;
sensordata[1]= TestSensorData.CollectTime & 0xff;
for(i=0;i<4;i++)
sensordata[2+i] = TestSensorData.Ch4Data.Data_Hex[i];
sensordata[6] = TestSensorData.DataCount;
for(i=0;i<7;i++)
printf("\r\nwrite this data to flash!\r\n ->%x",sensordata[i]);
DataWrite_To_Flash(0,16,0,sensordata,sizeof(sensordata));
printf("\r\nthe sensor data already send to flash!\r\n");
DataRead_From_Flash(0,16,0, readdata ,sizeof(readdata)); //从Flash中读取重传次数
for(i=0;i<7;i++)
printf("\r\nwrite this data to flash!\r\n ->%x",readdata[i]);
printf("\r\ntest sensor data from Flash! ->%s\r\n",readdata);
}
<file_sep>/User/SensorInit/SensorInit.c
#include "SensorInit.h"
#include "test.h"
#include "SPI_Flash.h"
/**********************************将配置信息人工写入FLASH内*******************************/
void SensorInit(void)
{
write_collect_parameter_to_flash(); //测试函数 进行设备采集参数的初始化设置
//Set_Time(); //测试函数 进行设备时间的设置
//Set_DS2780();
}
<file_sep>/User/Aider_Data_Protocol/AiderProtocol.c
#include "stm32f10x.h"
#include "gprs.h"
#include "bsp_SysTick.h"
#include "modbus.h"
#include "string.h"
#include "AiderProtocol.h"
#include "433_Wiminet.h"
#include "bsp_rtc.h"
#include "SPI_Flash.h"
#include "API-Platform.h"
#include "SensorInit.h"
//#include "bsp_date.h"
extern struct Sensor_Set DeviceConfig; //液位计配置信息结构体
extern struct SMS_Config_RegPara ConfigData;
extern u8 DataCollectCount; //数据采集计数器
extern char SendData_Flag;
extern struct rtc_time systmtime; //系统时间
extern uint8_t Usart3_send_buff[300];
extern uint8_t DMA_UART3_RECEV_FLAG ; //USART3 DMA接收标志变量
u8 phone_number_next=0; //电话号码的下一个指示
u8 ip_number_next=0; //网络IP的下一个指示
u8 port_number_next=0; //网络端口的下一个指示
/*******************************************************************************
* Function Name : UploadFlash
* Description : 输入需要存储的字符串,并将存储位置输入
* Input : None
* Output : 返回存储成功标志
* Return : None
*******************************************************************************/
uint8_t UploadFlash(char* pSetPara, uint8_t InstructCode)
{
uint8_t j=0;
uint8_t Counter=0;
switch(InstructCode)
{
case 2: //存储采集周期
{
for(j=0;j<strlen(pSetPara);j++)
//printf("\r\n---------%x----------\r\n",pSetPara[j]);
DataWrite_To_Flash(0,2,0,(uint8_t*)pSetPara,2); //将采集周期写入Flash
DeviceConfig.MessageSetFlag =1; //标示当前液位仪参数通过短信修改
printf("\r\n存储采集周期:%s\r\n",pSetPara); //测试使用
return 1;
}
case 3: //存储上传周期
{
for(j=0;j<strlen(pSetPara);j++)
//printf("\r\n---------%x----------\r\n",pSetPara[j]);
DataWrite_To_Flash(0,3,0,(uint8_t*)pSetPara,2); //将上传次数写入Flash
DeviceConfig.MessageSetFlag =1; //标示当前液位仪参数通过短信修改
printf("\r\n存储上报周期:%s\r\n",pSetPara); //测试使用
return 1;
}
case 4: //存储报警号码
{
//手机号码的判别条件,后续需要增加。
DataWrite_To_Flash(0,4,0,(uint8_t*)pSetPara,strlen(pSetPara)); //将报警号码写入Flash
DeviceConfig.MessageSetFlag =1; //标示当前液位仪参数通过短信修改
printf("\r\n存储报警电话:%s\r\n",pSetPara); //测试使用
return 1;
}
case 5: //存储服务器IP
{
for(j=0,Counter=0;j<strlen(pSetPara);j++) //调用函数已经做了防溢出处理,strlen(pSetPara)<=15
{
if((pSetPara[j]>='0')&&(pSetPara[j]<='9'))
{
// CharTemp[j] =pSetPara[j];
;
}
else if(pSetPara[j]=='.') //分隔符统计
{
Counter++;
}
else
{
break;
}
}
if(Counter==3)
{
DataWrite_To_Flash(0,5,0, (uint8_t*)pSetPara,strlen(pSetPara)); //将服务器IP写入Flash
}
else
{
printf("\r\nInput Server IP ERROR!!\r\n");
}
DeviceConfig.MessageSetFlag =1; //标示当前液位仪参数通过短信修改
printf("\r\n存储网络IP号: %s\r\n",pSetPara); //测试使用
return 1;
}
case 6: //存储服务器端口号
{
DataWrite_To_Flash(0,6,0,(uint8_t*)pSetPara,strlen(pSetPara)); //将服务器端口号写入Flash
DeviceConfig.MessageSetFlag =1; //标示当前液位仪参数通过短信修改
printf("\r\n存储网络端口号: %s\r\n",pSetPara); //测试使用
return 1;
}
case 10: //存储重传次数
{
DataWrite_To_Flash(0,10,0,(uint8_t*)pSetPara,1); //将重传次数写入Flash
DeviceConfig.MessageSetFlag =1; //标示当前液位仪参数通过短信修改
printf("\r\n 存储重传次数: %x\r\n",pSetPara[0]); //测试使用
return 1;
}
default:
{
printf("\r\nInstruct Code ERROR !!\r\n");
return 0;
}
}
}
/*******************************************************************************
* Function Name : Get_Rand_Num
* Description : 获取0~1000随机数据
* Input : None
* Output : 返回随机数
* Return : None
*******************************************************************************/
unsigned int Get_Rand_Num(void)
{
unsigned int rand_num;
srand((unsigned)RTC_GetCounter()); //设置种子
rand_num = rand()%1000; //获取0~1000随机数据
return(rand_num);
}
/**************************************************************************
* Function Name : SendDataToServ()
* Description : 通信协议的发送操作实现,在用该函数之前,需进行设备类型、上报数据格式、传输方式以及软件版本的定义。
相关的定义见SensorInit.h和 AiderProtocol.h
本函数将TAG打包后进行发送,如果发送不成功,进行设定值重传。
* Input :
操作类型: 参考AiderProtocol.h内操作类型;主要包括设备响应SET/GET请求GETRESPONSE,设备主动上报TRAPREQUEST,
设备开机上报信息STARTUPREQUEST,设备响应服务器唤醒WAKEUPRESPONSE,设备检查链接ONLINEREQUEST
发送TAG列表: 参考AiderProtocol.h内TAG结构体,将需要发送的TAG传递进来,不传输时可传递NULL
TAG数量: 需要发送的TAG的数量,TAG数量不超过20,不传输时为0
设备ID: 6字节的设备ID号
* Output : None
* Return : 发送成功标志
**************************************************************************/
uint8_t SendDataToServ(CommunicateType CommType,struct TagStruct TagList[],uint8_t TagNum,u8* pDeviceID)
{
DeviceType DevType = DEVICE; //初始化设备类别
ReportDataType RDataType = REPORTDATA; //初始化上报类型
SendType SType = TYPESEND; //通信方式为433通信
struct DataFrame SendData; //发送数据格式
struct DataFrame* pDataFrame =&SendData; //发送数据指针
struct TagStruct* pTag=TagList; //接收TAG指针
uint8_t pSendBuff[300]; //需要发送的数组
char* pChar =NULL;
u16 RecevFlag =0; //服务器数据接收标志变量
uint16_t NodeAddress; //设备地址
uint8_t SendCounter; //发送次数
uint16_t rand_num; //随机数字
u16 CrcData=0;
u8 i=0,j=0;
uint8_t RevTagNum = 0; //TAG的数量
u8 ValidLength =0; //有效数据长度,Tag空间中实际存储有效数据的长度。
const u8 PreLength =16; //帧前缀长度,指从帧前导码到OID序列(或者Tag序列)的数据长度,包括帧前导码,而不包括OID序列(或者Tag序列)
const u8 CoreLength =12; //关键信息长度,指数据净荷部分长度字段指示的数值,去除OID序列(或者Tag序列)后剩余数据的长度
const u8 TagPreLength=6; //TAG的OID长度为4+TAG数据长度2
uint8_t TagLength=0; //TAG的总长度
uint8_t Offset=0; //指针偏移量
u8 TotalLength; //除去CRC的数据总长度
NodeAddress = pDeviceID[4]*256 +pDeviceID[5];
pChar =(char*)pDataFrame;
memset(pChar,0x00,sizeof(struct DataFrame)); //初始化结构体
SendData.Preamble =0xA3;
SendData.Version = SOFTVERSION;
for(i=0;i<6;i++)
{
SendData.DeviceID[i] = pDeviceID[i];
}
SendData.RouteFlag =SType; //数据发送方式
SendData.NodeAddr =ntohs( NodeAddress); //调整为网络序,即高字节在前,低字节在后
SendData.PDU_Type =(CommType<<8)+(1<<7)+DEVICE;
SendData.PDU_Type =ntohs(SendData.PDU_Type); //调整为网络序,即高字节在前,低字节在后
SendData.Seq =1;
if(pTag!=NULL)
{
RevTagNum=TagNum; //如果指针不空,则证明有数据传输过来,接收TAG的数量
for(i=0;i<RevTagNum;i++)
SendData.TagList[i] = TagList[i];
}
else
{
switch(CommType)
{
case GETRESPONSE:
{
break;
}
case TRAPREQUEST:
{
SendData.TagList[0].OID_Command = ntohl(DEVICE_QTY); //调整为网络序,即高字节在前,低字节在后
SendData.TagList[0].Width =1; //
SendData.TagList[0].Value[0] =DeviceConfig.BatteryCapacity; //数据上传时的电池剩余电量
SendData.TagList[1].OID_Command= ntohl(SYSTERM_DATA); //调整为网络序,即高字节在前,低字节在后
SendData.TagList[1].Width =3; //
SendData.TagList[1].Value[0] =systmtime.tm_year-2000; //系统日期,年
SendData.TagList[1].Value[1] =systmtime.tm_mon ; //系统日期,月
SendData.TagList[1].Value[2] =systmtime.tm_mday ; //系统日期,日
RevTagNum =2; //TAG的总数等于电量+日期
break;
}
case ONLINEREQUEST:
{
break;
}
case WAKEUPRESPONSE:
{
SendData.TagList[0].OID_Command =ntohl(DEVICE_WAKEUP); //调整为网络序,即高字节在前,低字节在后
SendData.TagList[0].Width =1;
SendData.TagList[0].Value[0]=1;
RevTagNum =1;
break;
}
case STARTUPREQUEST:
{
SendData.TagList[0].OID_Command =ntohl(DEVICE_STATE); //调整为网络序,即高字节在前,低字节在后
SendData.TagList[0].Width =1;
SendData.TagList[0].Value[0]=1;
RevTagNum =1;
break;
}
default:
{
RevTagNum =0;
}
}
}
for(i=0; i<RevTagNum;i++)
{
TagLength = SendData.TagList[i].Width +TagPreLength;
ValidLength += TagLength;
}
SendData.Length =CoreLength + ValidLength;
SendData.Length =ntohs(SendData.Length );
memcpy(pSendBuff,pChar,PreLength ); //进行除TAG的数据复制
SendData.CrcCode =0xffff; //CRC字段赋初值
TotalLength = PreLength + ValidLength;
Offset= PreLength;
for(i=0; i<RevTagNum;i++)
{
pChar = (char*)&(SendData.TagList [i].OID_Command);
TagLength = SendData.TagList[i].Width +TagPreLength; //进行TAG的复制
SendData.TagList[i].Width=ntohs(SendData.TagList[i].Width);
memcpy((pSendBuff+Offset),pChar,TagLength );
Offset+=TagLength;
}
CrcData = CRC16(pSendBuff, TotalLength); // Update the CRC value
SendData.CrcCode =CrcData;
pSendBuff[TotalLength+1] = CrcData&0xff; //CRC低字节在前
pSendBuff[TotalLength+2] = CrcData>>8; //CRC高字节在后
if(DeviceConfig.RetryNum>0)
{
SendCounter =DeviceConfig.RetryNum;
}
else
{
SendCounter =1;
}
for(i=0;i<SendCounter;i++)
{
RecevFlag =SendMessage(pSendBuff, TotalLength+2);
if(RecevFlag !=0) //成功接收到数据
{
#if DEBUG_TEST
printf("\r\nReceive TrapResponse success!\r\n"); //测试使用
#endif
break;
}
rand_num=Get_Rand_Num();
#if DEBUG_TEST
printf("\r\nthe rand_num is %d\r\n",rand_num);
#endif
Delay_ms(3000+2*rand_num); //随机发送
}
}
/*******************************************************************************
* Function Name : TrapData
* Description : 进行传感器数据的主动上报
* Input : 设备节点
* Output : None
* Return : None
*******************************************************************************/
void TrapData(u8* pDevID)
{
int i,j;
uint8_t Tag_Count=0;
unsigned char readdata[7];
struct TagStruct Taglist[MAX];
uint16_t CollectTime;
Taglist[0].OID_Command = ntohl(DEVICE_QTY); //调整为网络序,即高字节在前,低字节在后
Taglist[0].Width =1; //
Taglist[0].Value[0] =DeviceConfig.BatteryCapacity; //数据上传时的电池剩余电量
Taglist[1].OID_Command= ntohl(SYSTERM_DATA); //调整为网络序,即高字节在前,低字节在后
Taglist[1].Width =3; //
Taglist[1].Value[0] =systmtime.tm_year-2000; //系统日期,年
Taglist[1].Value[1] =systmtime.tm_mon ; //系统日期,月
Taglist[1].Value[2] =systmtime.tm_mday ; //系统日期,日
Tag_Count =2; //TAG的总数等于电量+日期
for(i=0;i< DataCollectCount;i++) //进行上报数据TAG的填充
{
///////////////////////////////////////?FLASH????????????////////////////////////////////
DataRead_From_Flash(1,i+1,0, readdata ,sizeof(readdata));
CollectTime = readdata[0] *256 + readdata[1];
for(j=0;j<4;j++)
Taglist[2+i].OID_Command =ntohl((DeviceConfig.CollectPeriod<<11)+CollectTime +((0xC0 + REPORTDATA )<<24));
Taglist[2+i].Width =4;
for(j=0;j<Taglist[2+i].Width;j++)
Taglist[2+i].Value[j]= readdata[2+j];
Tag_Count++ ;
}
SendDataToServ(TRAPREQUEST,Taglist,Tag_Count,pDevID); //433模块主动上传数据
}
/*******************************************************************************
* Function Name : 二院协议数据分析
* Description : 用于接收服务器配置,没有9字头标志
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void Treaty_Data_Analysis(u8* pTreatyBuff, u16* pFlag, u8* pDeviceID, u16 NodeAddress)
{
u8 DataLen =0; //Tag序列或者OID序列的长度
u16 PduType =0;
u8 i=0,j=0,k=0;
u8* pChar =NULL;
u32* pOid =NULL;
u8 next = 0;
struct DataFrame ParaRequest;
struct TagStruct RecTagList[MAX]; //接收到的TAG
uint8_t RecTagNum; //接收到TAG的数量
PduType =pTreatyBuff[13]*256 +pTreatyBuff[14]; //结算接收数据PDU编码
switch(PduType)
{
/******************************************服务器请求********************************************/
case ((GETREQUEST<<8)+(1<<8)+DEVICE):
{
printf("\r\nReceive Get Request Command from Server.\r\n"); //监测到服务器发送的请求命令
*pFlag =PduType;
DataLen =pTreatyBuff[2]*256 +pTreatyBuff[3]-12; //接收的OID的总长度
ParaRequest.Tag_Count =DataLen/4; //接收的OID的数量,即TAG数量
if((ParaRequest.Tag_Count>0)&&(ParaRequest.Tag_Count <= MAX)) //限定OID的数量,控制在20个
{
pOid = (u32*)&pTreatyBuff[16];
j =ParaRequest.Tag_Count;
RecTagNum = j; //接收TAG的总数
for(i=0;i<ParaRequest.Tag_Count;i++)
{
ParaRequest.TagList[i].OID_Command =(CommandType)*pOid; //进行OID采集
ParaRequest.TagList[i].OID_Command =ntohl( ParaRequest.TagList[i].OID_Command ); //进行网络序列的变化
ParaRequest.TagList[i].Width=0;
#if DEBUG_TEST
printf("\r\n--Cycle--%4x----.\r\n", ParaRequest.OID_List[i]); //显示OID
#endif
j--;
if(j==0)
{
break;
}
pOid++;
}
printf("\r\n--i:%d--j:%d--%4x----.\r\n",i,j, ParaRequest.TagList[i].OID_Command); //显示OID
}
else
{
#if DEBUG_TEST
printf("\r\nReceive Command OID not correct.\r\n"); //????
#endif
}
DMA_UART3_RECEV_FLAG =0; //清接收标志变量
SendDataToServ(GETRESPONSE, ParaRequest.TagList,RecTagNum,pDeviceID); //进行响应
//GetResponse( ParaRequest, Usart3_send_buff, pDeviceID, NodeAddress);
break;
}
/******************************************设置设备参数请求********************************************/
case ((SETREQUEST<<8)+(1<<8)+DEVICE): //接收服务器下发的配置
{
#if DEBUG
printf("\r\nReceive Set Request Command from Server.\r\n"); //测试使用
#endif
*pFlag =PduType;
DataLen =pTreatyBuff[2]*256 +pTreatyBuff[3]-12; //接收到的Tag序列的总长度
if(DataLen >6) //至少存在一个合法的配置参数
{
pOid = (u32*)(pTreatyBuff+16); //服务器下发的第一个OID
i=0;
while( DataLen >6 )
{
printf("\r\n--Cycle--%4x----.\r\n",ntohl(*pOid)); //测试使用
pChar = (u8*)pOid;
switch(ntohl(*pOid))
{
case SYSTERM_TIME: //系统时间
{
DeviceConfig.Time_Year =*(pChar+6);
DeviceConfig.Time_Mon =*(pChar+7);
DeviceConfig.Time_Mday =*(pChar+8);
DeviceConfig.Time_Hour =*(pChar+9);
DeviceConfig.Time_Min =*(pChar+10);
DeviceConfig.Time_Sec =*(pChar+11);
printf("\r\n-年-月-日-时-分-秒:-%d--%d--%d--%d--%d--%d--.\r\n",DeviceConfig.Time_Year,DeviceConfig.Time_Mon,DeviceConfig.Time_Mday,
DeviceConfig.Time_Hour,DeviceConfig.Time_Min, DeviceConfig.Time_Sec ); //测试使用
if((DeviceConfig.Time_Mon<=12)&&(DeviceConfig.Time_Mday<=31)&&(DeviceConfig.Time_Hour<=23)&&(DeviceConfig.Time_Min<=60)&&(DeviceConfig.Time_Sec<=60)) //参数合法性判定
{
Time_Auto_Regulate(&DeviceConfig); //通过服务器下发参数进行RTC时钟校准,
}
ParaRequest.TagList[i].OID_Command=SYSTERM_TIME;
ParaRequest.TagList[i].Width = 6;
for(k=0;k<ParaRequest.TagList[i].Width;k++)
ParaRequest.TagList[i].Value[k]=pChar[6+k];
pOid =(u32*)(pChar+12); //指针后移1个Tag
DataLen = DataLen-12;
i++; //合法OID计数器
break;
}
case CLT1_ITRL1: //一时区采集间隔
{
DeviceConfig.CollectPeriod =pChar[6]*256+pChar[7];
ConfigData.CollectPeriod_Byte [0]=*(pChar+6);
ConfigData.CollectPeriod_Byte [1]=*(pChar+7);
printf("\r\n---CollectPeriod:-%d---.\r\n", DeviceConfig.CollectPeriod ); //测试使用
if(3<DeviceConfig.CollectPeriod<=1440) //参数合法性判定
{
UploadFlash((char*)ConfigData.CollectPeriod_Byte,2); //参数存入Flash
}
ParaRequest.TagList[i].OID_Command=CLT1_ITRL1;
ParaRequest.TagList[i].Width = 2;
for(k=0;k<ParaRequest.TagList[i].Width;k++)
ParaRequest.TagList[i].Value[k]=pChar[6+k];
pOid =(u32*)(pChar+8); //指针后移1个Tag
DataLen = DataLen-8;
i++; //合法OID计数器
break;
}
// case CLT1_CNT1: //一时区采集次数
// {
// DeviceConfig.CollectNum =pChar[6]*256+pChar[7];
// printf("\r\n-CollectNum:-%2x---.\r\n", DeviceConfig.CollectNum ); //测试使用
// if(DeviceConfig.CollectNum<=1440) //参数合法性判定
// {
// UploadFlash((char*)&(DeviceConfig.CollectNum), 9); //参数存入Flash
// }
// ParaRequest.OID_List[i] =CLT1_CNT1;
// pOid =(u32*)(pChar+8); //指针后移1个Tag
// DataLen = DataLen-8;
// i++; //合法OID计数器
// break;
// }
//
case UPLOAD_CYCLE: //数据上报周期
{
DeviceConfig.SendCount =pChar[6]*256+pChar[7];
ConfigData.SendCount_Byte [0]=*(pChar+6);
ConfigData.SendCount_Byte [1]=*(pChar+7);
if(0<DeviceConfig.SendCount <=1440) //参数合法性判定
{
UploadFlash((char*) ConfigData.SendCount_Byte , 3); //参数存入Flash
}
printf("\r\n-UploadCycle:-%d---.\r\n", DeviceConfig.SendCount ); //测试使用
ParaRequest.TagList[i].OID_Command=UPLOAD_CYCLE;
ParaRequest.TagList[i].Width = 2;
for(k=0;k<ParaRequest.TagList[i].Width;k++)
ParaRequest.TagList[i].Value[k]=pChar[6+k];
pOid =(u32*)(pChar+8); //指针后移1个Tag
DataLen = DataLen-8;
i++; //合法OID计数器
break;
}
///////////////////////////////////////////////////////////////////////////////////////////add by gao
case SMS_PHONE: //报警电话号码
{
for(k=0;k<16;k++)
{
DeviceConfig.AlarmPhoneNum [k] = pChar[6+k];
if((((pChar[6+k])>'9') || (pChar[6+k]<'0')) )
{
next=6+k;
phone_number_next=k;
//printf("*******phone number %d******",next); //??????
break;
}
}
if(11<strlen(DeviceConfig.AlarmPhoneNum)<16 ) //参数合法性判定
{
UploadFlash((char*)DeviceConfig.AlarmPhoneNum ,4); //参数存入Flash
}
printf("\r\n-Server set SMS_PHONE:-%s---.\r\n", DeviceConfig.AlarmPhoneNum ); //测试使用
ParaRequest.TagList[i].OID_Command=SMS_PHONE;
ParaRequest.TagList[i].Width = phone_number_next;
for(k=0;k<ParaRequest.TagList[i].Width;k++)
ParaRequest.TagList[i].Value[k]=pChar[6+k];
pOid =(u32*)(pChar+next); //指针后移1个Tag
DataLen = DataLen-next;
i++; //合法OID计数器
break;
}
case BSS_IP: //网络服务IP地址
{
for(k=0;k<16;k++)
{
DeviceConfig.ServerIP [k] =pChar[6+k];
if(((((pChar[6+k])>'9') || (pChar[6+k]<'0')) )&& (pChar[6+k]!='.'))
{
next=6+k;
ip_number_next=k;
//printf("*******ip %d******",next);
break;
}
}
if(8<strlen(DeviceConfig.ServerIP )<16) //参数合法性判定
{
UploadFlash((char*)DeviceConfig.ServerIP , 5); //参数存入Flash
}
printf("\r\n-BSS_IP:-%s---.\r\n", DeviceConfig.ServerIP ); //测试使用
ParaRequest.TagList[i].OID_Command=BSS_IP;
ParaRequest.TagList[i].Width = ip_number_next;
for(k=0;k<ParaRequest.TagList[i].Width;k++)
ParaRequest.TagList[i].Value[k]=pChar[6+k];
pOid =(u32*)(pChar+next); //指针后移1个Tag
DataLen = DataLen-next;
i++; //合法OID计数器
break;
}
case BSS_PORT: //网络服务端口号
{
for(k=0;k<6;k++)
{
DeviceConfig.ServerPort [k] = pChar[6+k];
if(((pChar[6+k])>'9') || (pChar[6+k]<'0'))
{
next=6+k;
port_number_next=k;
//printf("*******port %d******",next);
break;
}
}
if(strlen(DeviceConfig.ServerPort )!=0) //参数合法性判定
{
UploadFlash((char*)DeviceConfig.ServerPort , 6); //参数存入Flash
}
printf("\r\n-BSS_PORT:-%s---.\r\n", DeviceConfig.ServerPort ); //测试使用
ParaRequest.TagList[i].OID_Command=BSS_PORT;
ParaRequest.TagList[i].Width = port_number_next;
for(k=0;k<ParaRequest.TagList[i].Width;k++)
ParaRequest.TagList[i].Value[k]=pChar[6+k];
pOid =(u32*)(pChar+next); //指针后移1个Tag
DataLen = DataLen-next;
i++; //合法OID计数器
break;
}
case DEF_NR: //重传次数
{
DeviceConfig.RetryNum =*(pChar+6);
if(1<= DeviceConfig.RetryNum <10) //参数合法性判定
{
UploadFlash((char*)&(DeviceConfig.RetryNum), 10); //参数存入Flash
}
printf("\r\n-Retry Num-%x---.\r\n", DeviceConfig.RetryNum); //测试使用
// else //当配置参数不合法时,使用默认参数,同时不更新Flash数据
// {
// DeviceConfig.RetryNum =1; //为了反馈真实情况不发送默认参数
// }
ParaRequest.TagList[i].OID_Command=DEF_NR;
ParaRequest.TagList[i].Width = 1;
for(k=0;k<ParaRequest.TagList[i].Width;k++)
ParaRequest.TagList[i].Value[k] = pChar[6+k];
pOid =(u32*)(pChar+7); //指针后移1个Tag
DataLen = DataLen-7;
i++; //合法OID计数器
break;
}
////////////////////////////////////////////////////////////////////////////////////////////add by gao
default:
{
#if DEBUG_TEST
printf("\r\nWarning!!Tag OID not recognition!\r\n"); //测试使用
#endif
pOid =(u32*)(pChar+1); //指针后移一个字节,查询后续有无合法OID
DataLen = DataLen-1; //指针后移一个字节,查询后续有无合法OID
break;
}
}
}
}
if((i>0)&&(i<=20))
{
ParaRequest.Tag_Count =i; //对OID序列进行计数
RecTagNum=i;
}
else
{
ParaRequest.Tag_Count =7; //当OID计数器值超过20时,将计数器值重置成默认值(默认7)
}
DMA_UART3_RECEV_FLAG =0; //接收标志变量复位
SendDataToServ(GETRESPONSE,ParaRequest.TagList,RecTagNum,pDeviceID); //进行响应
break;
}
/******************************************设备数据上报信息响应*********************************************/
case ((TRAPRESPONSE<<8)+(1<<8)+DEVICE): //收到上报数据的响应
{
#if DEBUG_TEST
printf("\r\nReceive Trap Response Command from Server.\r\n"); //测试使用
#endif
/////////////////////////
//服务器接收完整性验证,对于一次上传一帧数据的情况,只需通过PDUType进行验证,接收到应答帧即代表接收完整
*pFlag =PduType;
break;
}
/******************************************设备检查链接响应*********************************************/
case ((ONLINERESPONSE<<8)+(1<<8)+DEVICE): //设备检查链接响应
{
#if DEBUG_TEST
printf("\r\nReceive Online Response Command from Server.\r\n"); //测试使用
#endif
*pFlag =PduType;
break;
}
/******************************************设备开机上报信息响应*********************************************/
case ((STARTUPRESPONSE<<8)+(1<<8)+DEVICE): //收到设备开机上报信息响应
{
#if DEBUG_TEST
printf("\r\nReceive Startup Response Command from Server.\r\n"); //测试使用
#endif
*pFlag =PduType;
break;
}
/******************************************服务器唤醒设备请求*********************************************/
case ((WAKEUPREQUEST<<8)+(1<<8)+DEVICE):
{
#if DEBUG_TEST
printf("\r\nReceive Wakeup Request Command from Server.\r\n"); //测试使用
#endif
*pFlag =PduType;
break;
}
default:
{
#if DEBUG_TEST
printf("\r\nWarning!!PDU Type not recognition!\r\n"); //测试使用
#endif
break;
}
}
}
<file_sep>/User/common/common.c
/**
******************************************************************************
* @file main.c
* @author fire
* @version V1.0
* @date 2013-xx-xx
* @brief 串口中断接收测试
******************************************************************************
* @attention
*
* 实验平台:野火 iSO-MINI STM32 开发板
* 论坛 :http://www.chuxue123.com
* 淘宝 :http://firestm32.taobao.com
*
******************************************************************************
*/
#include "stm32f10x.h"
#include "misc.h"
#include "stm32f10x_it.h"
#include "bsp_usart.h"
#include "bsp_TiMbase.h"
#include "bsp_SysTick.h"
#include "string.h"
#include "bsp_rtc.h"
#include "bsp_date.h"
#include "WatchDog.h"
#include "common.h"
#include "gprs.h"
#include "SPI_Flash.h"
extern struct Sensor_Set DeviceConfig; //传感器配置信息结构体
extern struct SMS_Config_RegPara ConfigData; //FLASH读取结构
extern u8 Send_Request_flag; //发送数据至上位机后收到反馈
extern u8 ReadData_flag; //读取传感器成功标志位,成功为1,失败为0;
extern char SendData_Flag; //发送数据成功标志位,发送成为为1,不成功为0;
extern char TcpConnect_Flag; //TCP连接成功标志位,连接成功为1,不成功为0;
/*******************************************************************************
* Function Name : XX
* Description : XX
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void gotoSleep(uint16_t SendCount)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);
PWR_BackupAccessCmd(ENABLE);
if(SendCount<1)
{
SendCount = 1; //防止程序出错,导致设备长期处于休眠状态而无法唤醒,目前设置最长休眠时间为24h
}
//Sms_Consult(); //查阅短信,更新配置参数,后续有待完善
//RTC_SetAlarm(RTC_GetCounter()+(24*60*60/SendCount)); //采集时间到开始唤醒
RTC_SetAlarm(RTC_GetCounter()+(DeviceConfig.SendCount ) * 60 ); //休眠,调试使用
RTC_WaitForLastTask();
if(DeviceConfig.MessageSetFlag ==1) //有短信修改参数时,将数据写入存储区
{
// ParaUpdateCheck(); //写配置数据
#if DEBUG_TEST
printf("\r\nDevice Set Upload Success According to Messages!!\r\n"); //测试使用
#endif
}
Delay_ms(800);
PowerOFF_GPRS(); //关闭GPRS模块电源
Delay_ms(100);
PowerOFF_Sensor(); //关闭超声波探头电源
Delay_ms(100);
PowerOFF_485(); //关闭485电源
Delay_ms(100);
PowerOFF_Flash(); //关闭Flash电源
/*********************************将工作的次数写入FLASH***************************************************/
DeviceConfig.WorkNum += 1;
ConfigData.WorkNum_Byte [0]=DeviceConfig.WorkNum>>8;
ConfigData.WorkNum_Byte [1]=DeviceConfig.WorkNum & 0x00FF;
DataWrite_To_Flash(0,12,0,ConfigData.WorkNum_Byte,2); //将已工作的次数写入FLASH
#if DEBUG_TEST
printf("\r\nCollectPeriod:%d-----SendCount:%d\r\n",DeviceConfig.CollectPeriod,DeviceConfig.SendCount); //测试使用
printf("SLEEP OK!\r\n%dmin later wakeup!!",SendCount); //应该考虑两个参数乘积
#endif
// RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR , ENABLE);
// PWR_WakeUpPinCmd(ENABLE); //使能WAKE-UP管脚
PWR_EnterSTANDBYMode();
}
<file_sep>/User/SensorInit/SensorInit.h
#ifndef _SENSORINIT_H_
#define _SENSORINIT_H_
#include "stm32f10x.h"
#include "stdlib.h"
#define DEVICE BIRMM_RTU100 //设备类型为燃气智能监测终端
#define REPORTDATA GAS //上报数据为气体浓度
#define TYPESEND TYPE_GPRS //传输类型选型GPRS通信
#define SENSORID {0x31,0x20,0x16,0x08,0x31,0x02} //传感器ID号
#define SOFTVERSION 0x20 //软件版本号
#define HARDVERSION 0x10 //硬件版本号
#define SETTIME {16,12,12,19,11,00}
#define CONFIG 0 //是否需要出厂配置参数标志
#define DEBUG_TEST 0 //打印功能,1应用于调试 0应用于正常工作
/* Private function prototypes -----------------------------------------------*/
void SensorInit(void); //设备初始化设置
#endif
/* end of SensorInit.h */
<file_sep>/README.md
# BIRMM-RTU100-GPRS
#Created by GaoJie
<file_sep>/User/433_Wiminet/433_Wiminet.c
// File Name: 433_Wiminet.c
#include "stdlib.h"
#include "string.h"
#include "API-Platform.h"
#include "433_Wiminet.h"
#include "bsp_SysTick.h"
#include "gprs.h"
#include "bsp_usart.h"
#include "common.h"
extern char Usart3_recev_buff[1000];
extern uint16_t Usart3_recev_count;
extern uint8_t DMA_UART3_RECEV_FLAG ; //USART3 DMA接收标志变量
//extern uint32_t time; // ms 计时变量
extern u8 SENSOR_ID[6];
extern u16 NODE_ADDR;
extern unsigned char DMA_UART3_RecevDetect(unsigned char RecevFlag,u8* pDeviceID, u16 sNodeAddress); //USART3接收数据监测与数据解析
//extern void RecvBuffInit_USART3(void);
//extern void ReceiveAnalysis_433(void);
//extern char Receive_Monitor_GPRS(void);
//extern void Receive_Deal_GPRS(void);
//extern u8 NetStatus_Detection( void );
// *****************************************************************************
// Design Notes:
// -----------------------------------------------------------------------------
unsigned char ReverseBitOrder08( unsigned char iSrc )
{
unsigned char index;
unsigned char iDst;
iDst = iSrc & 0X01;
for( index = 0X00; index < 0X07; index++ )
{
iDst <<= 0X01;
iSrc >>= 0X01;
iDst |= ( iSrc & 0X01 );
}
return iDst;
}
// *****************************************************************************
// Design Notes:
// -----------------------------------------------------------------------------
unsigned short ReverseBitOrder16( unsigned short iSrc )
{
unsigned char index;
unsigned short iDst;
iDst = iSrc & 0X01;
for( index = 0X00; index < 0X0F; index++ )
{
iDst <<= 0X01;
iSrc >>= 0X01;
iDst |= ( iSrc & 0X01 );
}
return iDst;
}
// *****************************************************************************
// Design Notes: CRC-16
// f(X)=X^16 + X^15 + X^2 + X^0
// POLYNOMIALS = 0X8005
// -----------------------------------------------------------------------------
unsigned short CRC16( unsigned char * pMsg, unsigned short iSize )
{
unsigned char index;
unsigned short iCRC;
// The default value
iCRC = 0XFFFF;
while ( iSize-- )
{
iCRC ^= ( ( ( unsigned short ) ReverseBitOrder08( *pMsg ) ) << 0X08 );
for ( index = 0X00; index < 0X08; index++ )
{
if ( iCRC & 0X8000 )
{
iCRC = ( iCRC << 1 ) ^ 0X8005;
}
else
{
iCRC <<= 1;
}
}
pMsg++;
}
return ReverseBitOrder16( iCRC );
}
// *****************************************************************************
// Design Notes:
// -----------------------------------------------------------------------------
void UpdateNodeMsgCRC( NodeMsg * pMsg )
{
unsigned char iSize;
unsigned short iCRC;
// The message header
// pMsg->m_iHeader = 0xAA;
// The defualt CRC value
pMsg->m_iCRCode = 0x00;
// The message size
iSize = 0x09;
iSize += pMsg->m_iAmount;
// Update the CRC value
iCRC = CRC16( ( unsigned char * )pMsg, iSize );
// -----------------------------------------------------------------------------
// DESCRIPTION:
// -----------------------------------------------------------------------------
#if ( CPU_ENDIAN_MODE == LITTLE_ENDIAN_MODE )
// Change the byte order
iCRC = ntohs( iCRC );
// -----------------------------------------------------------------------------
// DESCRIPTION:
// -----------------------------------------------------------------------------
#endif
// Restore the CRC of this message
pMsg->m_iCRCode = iCRC;
}
// *****************************************************************************
// Design Notes: 初始化结构体
// -----------------------------------------------------------------------------
void InitCommandMessage( NodeMsg * pMsg )
{
memset( pMsg, 0x00, sizeof( NodeMsg ) );
}
//// *****************************************************************************
//// Design Notes: 对查询主站ID函数封包
//// *****************************************************************************
//// Design Notes: 查询主站ID
//// -----------------------------------------------------------------------------
// unsigned short GetCoordinatorID (void)
//{
// NodeMsg Msg; //正式使用时不用
// NodeMsg* pMsg = &Msg;
// unsigned short iSize;
//// char i=0; //调试使用
// char receive_flag =0;
// //char SendBuffer[12]={0xAA,0x1D,0x33,0x86,0x03,0x00,0x03,0x00,0x00,0x01,0x02,0x03};
// char ID_GetFlag[2]={0xAA,0xF6};
// char* pRecevBuff=NULL;
// unsigned short ID_Temp=0x0000;
// // Initialize the message body
// InitCommandMessage( pMsg );
// // Construct the message
// IMP_GetCoordinatorID( pMsg );
// UpdateNodeMsgCRC( pMsg );
// // The total message size
// iSize = pMsg->m_iAmount + 0x09;
// USART_DataBlock_Send(USART1,(char* )(pMsg),iSize); //调试使用
// USART_DataBlock_Send(USART1,"\r\n",2); //调试使用
// USART_DataBlock_Send(USART3,(char* )(pMsg),iSize);
//
// Delay_ms(1000);
// receive_flag = Receive_Monitor_433();
// if(receive_flag == 1)
// {
// pRecevBuff = Find_SpecialString(Usart3_recev_buff,ID_GetFlag,300,2); //检查有无收到主站回复
// if(pRecevBuff!=NULL) //有回复,提取地址信息 //暂时缺少CRC校验
// {
//
//// printf("\r\nResponse from 433 is:"); //调试使用
//// for(i=0;i<Usart3_recev_count;i++) //调试使用
//// {
//// printf(" %x",pRecevBuff[i]); //调试使用
//// }
// ID_Temp = (pRecevBuff[9]*256) +pRecevBuff[10];
// pRecevBuff =NULL;
// receive_flag = 0;
// memset(Usart3_recev_buff,'\0',300);
// Usart3_recev_count =0; //清空USART3接收计数器
// time=0; //定时器复位
// return ID_Temp;
// }
// else
// {
// memset(Usart3_recev_buff,'\0',300);
// Usart3_recev_count =0; //清空USART3接收计数器
// time=0; //定时器复位
// }
// }
// return 0x0000;
//}
// *****************************************************************************
// Design Notes: 发送数据主函数
// -----------------------------------------------------------------------------
uint8_t SendMessage(char* Psend, unsigned short iSize)
{
int i=0; //测试使用
if(iSize>255)
{
iSize =255; //限定长度,防止缓存溢出
}
for(i=0;i<iSize;i++)
printf("--%x--",Psend[i]); //发送数据打印
mput_mix(( char * )(Psend), iSize);
Delay_ms(3000); //为了方便发送完配置成功帧以后接收服务器会话结束命令,在此处增加延时
#if DEBUG_TEST
printf("\r\nSend Over!!\r\n"); //调试使用
#endif
return 1;
}
// *****************************************************************************
// Design Notes:
// -----------------------------------------------------------------------------
unsigned char IsValidNodeMsg( NodeMsg * pMsg )
{
unsigned short iCRC1;
unsigned short iCRC2;
unsigned short iSize;
// Check the header
if ( pMsg->m_iHeader != 0XAA )
{
return 0X00;
}
// The original CRC
iCRC1 = pMsg->m_iCRCode;
// Clear the CRC
pMsg->m_iCRCode = 0X00;
// The total message size
iSize = 0X09;
iSize += pMsg->m_iAmount;
// Validate the CRC of this message
iCRC2 = CRC16( ( unsigned char * )pMsg, iSize );
// -----------------------------------------------------------------------------
// DESCRIPTION:
// -----------------------------------------------------------------------------
#if ( CPU_ENDIAN_MODE == LITTLE_ENDIAN_MODE )
// Change the byte order
iCRC2 = ntohs( iCRC2 );
// printf("CRC is :%4x\r\n", iCRC2); 测试使用
// -----------------------------------------------------------------------------
// DESCRIPTION:
// -----------------------------------------------------------------------------
#endif
// Restore the CRC of this message
pMsg->m_iCRCode = iCRC1;
// Check the CRC value
return ( iCRC1 == iCRC2 );
}
// *****************************************************************************
// Design Notes: 接收数据解析函数
// -----------------------------------------------------------------------------
unsigned char ReceiveMessageVerify(char* pRecevBuff)
{
NodeMsg Msg;
NodeMsg* pMsg = &Msg;
uint16_t i=0;
unsigned char MessageRecv_Flag=0;
// char Recev_OK[2]={0xAA,0x1E};
// char* pRecevBuff=NULL;
// #if DEBUG_TEST
// printf("\r\nReceive from 433:");
// for(i=0;i<150;i++)
// {
// printf(" %x",pRecevBuff[i]);
// }
// #endif
pMsg->m_iHeader = pRecevBuff[0];
pMsg->m_iOpCode = pRecevBuff[1];
pMsg->m_iValueA = pRecevBuff[2];
pMsg->m_iValueB = pRecevBuff[3];
pMsg->m_iValueC = pRecevBuff[4];
pMsg->m_iValueD = pRecevBuff[5];
pMsg->m_iAmount = pRecevBuff[6];
pMsg->m_iCRCode = (pRecevBuff[8]*256)+pRecevBuff[7]; //顺序有待进一步确认
if(pRecevBuff< (Usart3_recev_buff+sizeof(Usart3_recev_buff)-1-9-pMsg->m_iAmount)) //防止指针越界
{
for(i=0;i<(pMsg->m_iAmount);i++)
{
pMsg->m_pBuffer[i] = pRecevBuff[9+i];
}
MessageRecv_Flag = IsValidNodeMsg(pMsg);
if(MessageRecv_Flag ==1) //接收数据有效
{
#if DEBUG_TEST
printf("\r\nData receive from %4x is :",(pMsg->m_iValueA*256)+(pMsg->m_iValueB));
for(i=0;i<(pMsg->m_iAmount);i++)
{
printf(" %x ",pMsg->m_pBuffer[i]);
}
#endif
return 1;
}
}
else
{
printf("\r\nWarnning!Memory OverFlow Occur!!\r\n");
}
return 0;
}
//// *****************************************************************************
//// Design Notes:
//// -----------------------------------------------------------------------------
//void WriteNodeMsg( unsigned char hFile, NodeMsg * pMsg )
//{
// unsigned char iSize;
// // Update the message CRC value
// UpdateNodeMsgCRC( pMsg );
// // The packet whole size
// iSize = 0X09 + pMsg->m_iAmount;
// // Write out message header
//// WriteFile( hFile, ( char * )pMsg, iSize ); //暂时注释掉
//}
| e2b5e66ad8fd940d638cd122989dbd56f6092d99 | [
"Markdown",
"C"
] | 10 | C | wgy504/BIRMM-RTU100-GPRS | e2ea3ab5082565a37581e6fdb2b060dcfb21ebd1 | fc2b27cc81e2c510d3cdad044624e812498c8be8 |
refs/heads/master | <file_sep>### Version 0.20
* Check user's machine for their timezone and set it this way. Don't require the user to set it themselves.
### Version 0.15
* Changed configuration handling from PHP files to JSON for smaller size and faster loading.
### Version 0.14
* Added keyword to enable / disable 12-hour time.
### Version 0.13
* Added support for 12-hour time.
* Added configuration for 12-hour time.
* Enhanced README.md with configuration options.
### Version 0.12
* Removed extra require's at the top of the tv show workflow.
* Removed unnecessary variables for less memory usage.
* Added TV Episode search functionality (beta).
### Version 0.11
* Corrected Alfred Output if a show had only one season.
### Version 0.1
* Initial Release<file_sep><?php
// Author: <NAME>
// Version: 0.2
$tz_string = exec('systemsetup -gettimezone');
$tz = substr( $tz_string, ( strpos( $tz_string, ": " ) + 2 ) );
date_default_timezone_set( $tz );
require_once('workflows.php');
require_once('TVRAGE/TVRAGE.class.php');
require_once('TVRAGE/TV_Show.class.php');
require_once('TVRAGE/TV_Shows.class.php');
//create new workflow
$w = new Workflows();
// Grab input
$input = "Mike & Molly";
$string = file_get_contents('config.json');
$decodedJSON = json_decode($string, true);
//Use the input to search TVRage
$show = TV_Shows::search($input);
//use foreach loop to set the information for each result
foreach ($show as $each) {
//set the information available to us
$thisShow = array(
'uid' => $each->showId,
'arg' => $each->showLink,
'name' => $each->name,
'subtitle' => "",
'status' => $each->status,
'airDay' => $each->airDay,
'airTime' => $each->airTime,
'12hrAirTime' => $each->twelveHourAirTime,
'network' => $each->network,
'seasons' => $each->seasons,
'valid' => 'yes',
'fileIcon' => 'icon.png',
'autocomplete' => 'yes'
);
//check number of seasons to ensure we return the correct word
if ($thisShow['seasons'] > 1) {
$seasons = "seasons";
} else {
$seasons = "season";
}
if($decodedJSON['12hrtimezone'] == true) {
//set the subtitle based on the status of the show. We want the user to get information pertinent to the show.
if($thisShow['status'] == "Returning Series") {
$thisShow['subtitle'] = $each->name . " is a " . $thisShow['status'] . ". It is aired " . $thisShow['airDay'] . " at " . $thisShow['12hrAirTime'] . " on " . $thisShow['network'] . ".";
} else if ($thisShow['status'] == "Canceled/Ended") {
$thisShow['subtitle'] = $thisShow['name'] . " is " . $thisShow['status'] . ". It ran for " . $thisShow['seasons'] . " $seasons on " . $thisShow['network'] . ".";
} else if ($thisShow['status'] == "TBD/On The Bubble") {
$thisShow['subtitle'] = $thisShow['name'] . " is on the bubble for being renewed. If it is renewed, it airs on " . $thisShow['airDay'] . " at " . $thisShow['12hrAirTime'] . " on " . $thisShow['network'] . ".";
} else {
$thisShow['subtitle'] = $thisShow['name'] . " is aired on " . $thisShow['airDay'] . " at " . $thisShow['12hrAirTime'] . " on " . $thisShow['network'] . ".";
}
} else {
//set the subtitle based on the status of the show. We want the user to get information pertinent to the show.
if($thisShow['status'] == "Returning Series") {
$thisShow['subtitle'] = $each->name . " is a " . $thisShow['status'] . ". It is aired " . $thisShow['airDay'] . " at " . $thisShow['airTime'] . " on " . $thisShow['network'] . ".";
} else if ($thisShow['status'] == "Canceled/Ended") {
$thisShow['subtitle'] = $thisShow['name'] . " is " . $thisShow['status'] . ". It ran for " . $thisShow['seasons'] . " $seasons on " . $thisShow['network'] . ".";
} else if ($thisShow['status'] == "TBD/On The Bubble") {
$thisShow['subtitle'] = $thisShow['name'] . " is on the bubble for being renewed. If it is renewed, it airs on " . $thisShow['airDay'] . " at " . $thisShow['airTime'] . " on " . $thisShow['network'] . ".";
} else {
$thisShow['subtitle'] = $thisShow['name'] . " is aired on " . $thisShow['airDay'] . " at " . $thisShow['airTime'] . " on " . $thisShow['network'] . ".";
}
}
//$w->result(uid, arg, title, subtitle, fileicon, valid, autocomplete)
$w->result($thisShow['uid'], $thisShow['arg'], $thisShow['name'], $thisShow['subtitle'], $thisShow['fileIcon'], $thisShow['valid'], $thisShow['autocomplete']);
}
// Return the result xml
echo $w->toxml();
?><file_sep><?php
$string = file_get_contents('config.json');
$decodedJSON = json_decode($string, true);
$decodedJSON['12hrtimezone'] = false;
$encodedJSON = json_encode($decodedJSON);
file_put_contents('config.json', $encodedJSON);
?><file_sep>Welcome to the TVRage Alfred Workflow
=====================================
### Version 1.0
This workflow is currently setup to run based on the tv keyword. It queries TVRage and returns information on the show. If you are using a hotkey, it will pass your current selection in OS X into the workflow.

Configuration:
--------------
* If you would like to switch the time from 12 hour to 24 hour or vice versa, use keyword 'enable12hr' or 'enable24hr'.
Returning Series:
-----------------
[*SHOW_NAME*] is a returning series. It is aired on [*AIR DAY*] at [*AIR TIME*] on [*TV NETWORK*].
Canceled/Ended Series:
----------------------
[*SHOW_NAME*] is canceled/ended. It ran for [*NUMBER OF SEASONS*] season(s) on [*TV NETWORK*].
TBD/On The Bubble Series:
----------------------
[*SHOW_NAME*] is on the bubble for being renewed. If it is renewed, it airs on [*AIR DAY*] at [*AIR TIME*] on [*TV NETWORK*].
Use of the Workflow
===================
This workflow can be called by the keyword "tv [*TV SHOW NAME*]". This will query the TVRage database and return results based on your query.
Features to be added:
---------------------
* TV Episode search — NOTE: functions, but slow. Trying to speed it up before hooking it up.
* ~~12 hour version (instead of current 24-hour time)~~
* ~~Create icon for TVRage workflow~~
* ~~Better Timezone support~~
* ~~[Alleyoop](http://www.alfredforum.com/topic/1582-alleyoop-update-alfred-workflows/) Support~~
Resources Used:
---------------
* [PHP TVRage Class](https://github.com/ryandoherty/PHP--TVRage)
* [Alfred App v2](http://www.alfredapp.com/)<file_sep> <?php
// Author: <NAME>
// Version: 0.06
date_default_timezone_set('America/New_York');
require_once('workflows.php');
require_once('TVRAGE/TVRAGE.class.php');
require_once('TVRAGE/TV_Show.class.php');
require_once('TVRAGE/TV_Shows.class.php');
require_once('TVRAGE/TV_Episode.class.php');
//create new workflow
$w = new Workflows();
// Grab input
$input = "{query}";
//next we want to separate the show name from the season and from the episode
preg_match("/(.+)S(\d{2})E(\d{2})/", $input, $showInfoArray);
if(empty($showInfoArray)) {
$fileIcon = "icon_waiting.png";
$valid = "no";
$w->result("52847495564616816814684357", "http://www.tvrage.com/", "Preparing to Search...", "Waiting for the complete input. Please enter \"[SHOW NAME] S##E##\" to begin the search.", $fileIcon, $valid, 'yes');
// Return the result xml
echo $w->toxml();
} else {
$showName = $showInfoArray['1'];
$showSeason = $showInfoArray['2'];
$showEpisode = $showInfoArray['3'];
$tvShowSearch = TV_Shows::search($showName);
foreach ($tvShowSearch as $returnedTVShow) {
//First, we want to get the TV show information.
$thisShowInfo = array(
'showId' => $returnedTVShow->showId,
'showName' => $returnedTVShow->name
);
//Now that we have the current TV Show ID #, we can use this to search for the specific episode
$useIDToGetToEpisode = TV_Shows::findById($thisShowInfo['showId']);
$episode = $useIDToGetToEpisode->getEpisode($showSeason, $showEpisode);
//Take the information we got from TV Rage, and put it in an array
$episodeInformation = array(
'uid' => $thisShowInfo['showId'],
'arg' => $episode->url,
'name' => $episode->title . ", " . $thisShowInfo['showName'] . " aired on " . $episode->formattedAirDate . ".",
'subtitle' => 'Episode ' . $showEpisode . " of " . $thisShowInfo['showName'] . " was named " . $episode->title . " and aired on " . $episode->formattedAirDate . ".",
'fileIcon' => 'icon.png',
'valid' => 'yes'
);
//prep it for return to Alfred!
$w->result($episodeInformation['uid'], $episodeInformation['arg'], $episodeInformation['name'], $episodeInformation['subtitle'], $episodeInformation['fileIcon'], $episodeInformation['valid'], 'yes');
//end foreach loop
}
//end else
// Return the result xml
echo $w->toxml();
}
?> | b869549ee6d6c9e144e2b6556b7fb2edfd5436fd | [
"Markdown",
"PHP"
] | 5 | Markdown | kkirsche/TVRage-Alfred_Workflow | 1adadd2b034c8465991dc4e8d870c7ae42433407 | dc2b12d89d6a79e7c441ccabd83a978ccf8bfc2f |
refs/heads/master | <repo_name>tokenblakk/Game_Code<file_sep>/README.txt
A Git REPOSITORY for my files, <NAME>, All rights reserved. 2013
Tokenblakk
Storage of Unity 3D projects and backups.
Using SSH
New Line
<file_sep>/Pyramid/Assets/Scripts/GoalScript.js
class GoalScript extends MonoBehaviour
{
//colors defined once in base class
var alpha : float = 0.3;
var red : Color = Color(1,0,0,alpha);
var green : Color = Color(0,1,0,alpha);
var yellow : Color = Color(1,0.92,0.016,alpha);
var blue : Color = Color(0,0,1,alpha);
var white : Color = Color(1,1,1,alpha);
var goalColor : Color;
function Start()
{
goalColor = white;
}
function Update ()
{
renderer.material.SetColor("_Color", goalColor);
}
function OnCollisionEnter(collision : Collision)
{
var contact = collision.contacts[0];
//print (contact.otherCollider.name);
if(contact.otherCollider.tag.Equals("Player") && GameObject.FindWithTag("Shield").GetComponent(ShieldScript).shieldColor.Equals(goalColor))
Destroy(gameObject);
}
//&& GameObject.FindWithTag("Player").GetComponent(PlayerMoveScript).shape.Equals(goalShape)
}<file_sep>/Pyramid/Assets/Scripts/ButtonGUI.js
var buttonTex : Texture2D;
var style : GUIStyle;
function OnGUI ()
{
if(GUI.RepeatButton(Rect((Screen.width/2 -350),(Screen.height/2 + 100),100,50), buttonTex, style))
{
GameObject.FindWithTag("Player").GetComponent(PlayerMoveScript).jetpack();
}
else
GameObject.FindWithTag("Player").GetComponent(PlayerMoveScript).laserOn = false;
}<file_sep>/FlySwat/Assets/Scripts/SwatterScript.js
public class SwatterScript extends MonoBehaviour
{
var swat : AudioClip;
//public var pointValue : float;
public var HUD : HUDScript;
function OnCollisionEnter(collision : Collision)
{
//HUD = GameObject.Find
//HUD = GetComponent(HUDScript); //Grandparent player screen GUI
//Play Sound
//Add Points
/////
// Programing paradigm
//for (var contact : ContactPoint in collision.contacts) <-
//For loops create an entire array of points contacted.
//So this would cause a series of points where the score was added to
//Contacts between faces of the bug object and the swatter resulted in varying score changes per hit.
var contact = collision.contacts[0];
//print(contact.otherCollider);
//contact.otherCollider.name.Contains("Bug") ||
if (contact.otherCollider.tag.Equals("Bug"))
{
audio.PlayOneShot(swat);
if (contact.otherCollider.name.Contains("Bug"))
{
if (collision.gameObject.GetComponent(BugScript))
HUD.increasePoints(collision.gameObject.GetComponent(BugScript).GetPointValue());
}
if (contact.otherCollider.name.Contains("Moth"))
{
if (collision.gameObject.GetComponent(MothScript))
HUD.increasePoints(collision.gameObject.GetComponent(MothScript).GetPointValue());
}
//contact.otherCollider.transform.);
}
//add the alternate bugs and their scores here.
}
function Update () {
}
}<file_sep>/FlySwat/Assets/Scripts/PlayerScript.js
@script RequireComponent(AudioSource)
public class PlayerScript extends MonoBehaviour
{
private var points : float = 0;
var mouseX : float = 0;
var mouseY : float = 0;
var xRotation : float;
var currentXRotation : float;
var xRotationV : float;
var zPosition : float = 4.2;
var currentZPosition : float;
var zPositionV : float;
var swatDamp : float = .02;
var sensitivity: float = 50;
var edgeL : float = -7;
var edgeR : float = 7;
var edgeT : float = 5.0;
var edgeB : float = -3.0;
var swipe : AudioClip;
var holdCount : float = 0;
var engaged : boolean = false;
var timeout : boolean = false;
var timeoutTimer : float = 0;
function Update ()
{
Screen.showCursor = false;
Screen.lockCursor = true;
mouseX += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
mouseY += Input.GetAxis("Mouse Y") *sensitivity *Time.deltaTime;
mouseX = Mathf.Clamp(mouseX, edgeL, edgeR);
mouseY = Mathf.Clamp(mouseY, edgeB, edgeT);
if (Input.GetButton("Fire1") && !timeout)
{
holdCount += 1;
if (holdCount >=20)
{
holdCount = 0;
timeout = true;
timeoutTimer = 0;
}
if (!engaged)
audio.PlayOneShot(swipe);
engaged = true;
xRotation = 45;
zPosition = 5.5;
}
else
{
if (timeoutTimer >= 20)
{
timeout = false;
holdCount = 0;
}
else
timeoutTimer += 1;
engaged = false;
xRotation = -25;
zPosition = 4.2;
}
xRotation = Mathf.Clamp(xRotation, -25, 45);
currentXRotation = Mathf.SmoothDamp(currentXRotation, xRotation, xRotationV, swatDamp);
currentZPosition = Mathf.SmoothDamp(currentZPosition, zPosition, zPositionV, swatDamp);
transform.rotation = Quaternion.Euler(currentXRotation,0,0);
transform.position = Vector3(mouseX, mouseY, currentZPosition);
}
}
/*
public function increasePoints(point : float)
{
this.points += point;
}*/<file_sep>/FlySwat/Assets/Scripts/MothScript.js
public class MothScript extends BugScript
{
//var deadMoth : Transform;// = gameObject.getComponent<Transform>();
//var self : Rigidbody;
var pos : Vector3;
var speed : Vector2;
var rand : int;
function Start()
{
//var self = rigidbody;
pointValue = 2;
pos = rigidbody.position;
speed = rigidbody.velocity;
rand = Random.Range(0, 3);
}
/*function MothScript()
{
//this is for making a dead moth thisMoth = GameObject.Instantiate(
//
}*/
function Update ()
{
switch (rand)
{
case 0:
pos.x = (pos.x -(2 * Time.deltaTime));
break;
case 1:
pos.x = (pos.x +(2 * Time.deltaTime));
break;
case 2:
pos.y = pos.y -(2 * Time.deltaTime);
//pos.x = (pos.x -(2 * Time.deltaTime));
break;
case 3:
pos.y = pos.y +(2 * Time.deltaTime);
//pos.x = (pos.x -(2 * Time.deltaTime));
break;
}
rigidbody.position = pos;
//speed.y += -0.001;
//speed.x += 0.002;
//rigidbody.velocity = speed;
//Destroy(gameObject, 3);
super.Update();
}
}<file_sep>/FlySwat/Assets/Scripts/MothSpawnerScript.cs
using UnityEngine;
using System.Collections;
public class MothSpawnerScript : BugSpawnerScript {
// Use this for initialization
public void Start ()
{
base.Start();
}
// Update is called once per frame
public void Update ()
{
base.Update();
}
/*void spawn(Transform bug)
{
position = new Vector3(Random.Range(-7f, 7f), Random.Range(-3f, 5f) , 5.7f);
Instantiate(bug, position, Quaternion.Euler(0,180,0)); //Bugs face backwards otherwise
}
/*override void spawn(Transform moth)
{
}*/
}
<file_sep>/FlySwat/Assets/Scripts/DeadBugScript.js
@script RequireComponent(AudioSource)
public class DeadBugScript extends MonoBehaviour
{
var splat : AudioClip;
var timer : float = 10;
function Awake()
//When instantiated, play the splat sound
//Instead of when the bug is destroyed
{
audio.PlayOneShot(splat);
}
function Update ()
//Fade the bug, or just get rid of it
{
Destroy(gameObject, 3);
}
}<file_sep>/FlySwat/Assets/Scripts/BeeSpawnerScript.cs
using UnityEngine;
using System.Collections;
public class BeeSpawnerScript : BugSpawnerScript {
int rand;
//Vector3 position;
// Use this for initialization
public void Start ()
{
base.Start();
}
// Update is called once per frame
public void Update ()
{
base.Update();
}
/*void spawn(Transform bug)
{
position = new Vector3(Random.Range(-7f, 7f), Random.Range(-2.5f, 5f) , 5.7f);
Instantiate(bug, position, Quaternion.Euler(0,180,0)); //Bugs face backwards otherwise
}
*/
public override void spawn(Transform bee)
{
rand = Random.Range(0, 3);
switch (rand)
{
case 0: //from right
base.position = new Vector3(7, Random.Range(-2.5f, 5f) , 5.7f);
print("right");
break;
case 1: // from left
position = new Vector3(-7, Random.Range(-2.5f, 5f) , 5.7f);
print("left");
break;
case 2: // from bottom
position = new Vector3(Random.Range(-7f, 7f), -2.5f , 5.7f);
//pos.x = (pos.x -(2 * Time.deltaTime));
print("bot");
break;
case 3: //from top
position = new Vector3(Random.Range(-7f, 7f), 4f , 5.7f);
//pos.x = (pos.x -(2 * Time.deltaTime));
print("top");
break;
}
Instantiate(bee, position, Quaternion.Euler(0,180,0)); //Bugs face backwards otherwise
}
}
<file_sep>/Pyramid/Assets/Scripts/CameraMoveScript.js
var player : GameObject;
var cameraLag : float = 0.9;
//var xRotation : float = 6;
//var yRotation : float = 6;
var yPosition : float;
var zPosition : float;
var xPosition : float;
//player.rigidbody.position.y;
//var targetYRotation : float;
var targetXRotationV : float;
//var targetYRotationV : float;
var targetYV : float;
var targetXV : float;
var targetZV : float;
var rotationSpeed : float = 0.5;
var targetYPosition : float;
var targetZPosition : float;
var targetXPosition : float; //Zoom
var mouseLookSpeed : float = 50;
function Update ()
{
var playerTrans = player.GetComponent(Transform);
yPosition = playerTrans.position.y;
zPosition = playerTrans.position.z;
xPosition = playerTrans.position.x + 10;
if (Input.GetAxisRaw("Horizontal") == 1 || Input.GetAxisRaw("Horizontal") == -1)
{
targetXPosition = xPosition + 2;
targetXPosition = Mathf.SmoothDamp(xPosition, targetXPosition, targetXV, rotationSpeed);//rotational speed
}
else
{
targetXPosition = xPosition + 5;
targetXPosition = Mathf.SmoothDamp(xPosition, targetXPosition, targetXV, rotationSpeed);//rotational speed
}
targetYPosition = Mathf.SmoothDamp(targetYPosition, yPosition +1, targetYV, rotationSpeed);
targetZPosition = Mathf.SmoothDamp(targetZPosition, zPosition +1, targetZV, rotationSpeed);
transform.position.z = targetZPosition;
transform.position.y = targetYPosition;
transform.position.x = targetXPosition;
Camera.main.transform.LookAt(playerTrans);
//transform.rotation = Quaternion.Euler(0,targetYRotation,0);
//transform.eulerAngles = Vector3(Mathf.Clamp(0.0,yRotation,0.0), 0, 0);
//transform.rotation.x = Mathf.Clamp(transform.rotation.x,0.0,30.0);
}
<file_sep>/Pyramid/Assets/Scripts/ShieldScriptPlayerControlled.js
#pragma strict
var alpha : float = 0.3;
var red : Color = Color(1,0,0,alpha);
var green : Color = Color(0,1,0,alpha);
var yellow : Color = Color(1,0.92,0.016,alpha);
var blue : Color = Color(0,0,1,alpha);
var white : Color = Color(1,1,1,alpha);
var colors : Color[] = [red, green, yellow, blue, white];
var index : int = 1;
var shieldColor : Color;
function Start ()
{
shieldColor = white;
}
function Update ()
{
//testing colors against color walls
if (Input.GetKeyDown("e")) //keeps colors switching forward through array
{
index += 1;
if (index > 4)
index = 0;
}
if (Input.GetKeyDown("q")) //cycle backward
{
index -= 1;
if (index < 0)
index = 4;
}
//index = index % colors.Length; //cycle through colors the ifs are safer and avoid index out of bounds
shieldColor = colors[index];
renderer.material.SetColor("_Color", shieldColor);
}<file_sep>/FlySwat/Assets/Scripts/BugSpawnerScript.cs
using UnityEngine;
using System.Collections;
public class BugSpawnerScript : MonoBehaviour {
public Transform Bug;// = gameObject.GetComponent<Transform>();
float timer;
public float defaultTime;
bool canSpawn = false;
public Vector3 position;
// Use this for initialization
public void Start ()
{
timer = defaultTime;
spawn(Bug);
canSpawn = false;
}
// Update is called once per frame
public void Update ()
{
if (canSpawn)
{
spawn(Bug);
canSpawn = false;
}
if (timer <= 0)
{
canSpawn = true;
timer = defaultTime;
}
timer -= Time.deltaTime;
//print(timer);
}
public virtual void spawn(Transform bug)
{
position = new Vector3(Random.Range(-7f, 7f), Random.Range(-2.5f, 5f) , 5.7f);
Instantiate(bug, position, Quaternion.Euler(0,180,0)); //Bugs face backwards otherwise
}
}
<file_sep>/Pyramid/Assets/Scripts/WallScript.js
class WallScript extends GoalScript
{
var customColor : Color = Color(0,0,0,alpha);
//enum Colors {RED : "RED", GREEN : "GREEN", YELLOW : "YELLOW", BLUE : "BLUE", WHITE : "WHITE"};
enum Colors {RED, GREEN, YELLOW, BLUE, WHITE};
var inputColor : Colors;
//no Colors here look in base class
//goalColor =
function Start()
{
switch(inputColor)
{
case Colors.RED:
customColor = red;
break;
case Colors.GREEN:
customColor = green;
break;
case Colors.YELLOW:
customColor = yellow;
break;
case Colors.BLUE:
customColor = blue;
break;
case Colors.WHITE:
customColor = white;
break;
default:
customColor = white;
break;
}
//if (customColor != Color(0,0,0,alpha))
//goalColor = customColor;
goalColor = customColor;
}
//&& GameObject.FindWithTag("Player").GetComponent(PlayerMoveScript).shape.Equals(goalShape)
}
//TODO either come back and fix this goal/custom color or revert back to seperate scripts with same code, which is inefficent but effective<file_sep>/FlySwat/Assets/Scripts/BugScript.js
public class BugScript extends MonoBehaviour
{
//@script RequireComponent(AudioSource)
var deadBug: Transform;
var pointValue : int = 1;
//var splat : AudioClip;
/*function BugScript()
{
}
*/
function OnCollisionEnter(collision : Collision)
{
//When Hit, destroy and change to dead bug.
//Dead bug should have some fading mechanism.
var contact = collision.contacts[0];
if (contact.otherCollider.tag.Equals("Player"))
{
Destroy(gameObject);
var theDeadBug : Transform;
theDeadBug = Instantiate(deadBug, transform.position, Quaternion.Euler(0,180,0));
}
}
function GetPointValue()
{
return pointValue;
}
function Update ()
{
Destroy(gameObject, 6);
}
}
<file_sep>/Pyramid/Assets/Scripts/ShieldScript.js
#pragma strict
var alpha : float = 0.3;
var red : Color = Color(1,0,0,alpha);
var green : Color = Color(0,1,0,alpha);
var yellow : Color = Color(1,0.92,0.016,alpha);
var blue : Color = Color(0,0,1,alpha);
var white : Color = Color(1,1,1,alpha);
enum Colors {RED, GREEN, YELLOW, BLUE, WHITE};
var inputColor : Colors = Colors.WHITE;
var shieldColor : Color;
function Start ()
{
//shieldColor = white;
}
function Update ()
{
switch(inputColor)
{
case Colors.RED:
shieldColor = red;
break;
case Colors.GREEN:
shieldColor = green;
break;
case Colors.YELLOW:
shieldColor = yellow;
break;
case Colors.BLUE:
shieldColor = blue;
break;
case Colors.WHITE:
shieldColor = white;
break;
default:
shieldColor = white;
break;
}
renderer.material.SetColor("_Color", shieldColor);
}
public function setInputColor(_color : String)
{
//hard to convert string to enum, but this is how
inputColor = System.Enum.Parse(Colors, _color, true);
// Picking an invalid colors throws an ArgumentException. To
// avoid this, call Enum.IsDefined() first, as follows:
/*
string nonColor = "Polkadot";
if (Enum.IsDefined(typeof(Colors), nonColor))
inputColor = (Colors) Enum.Parse(typeof(Colors), nonColor, true);
else
MessageBox.Show("Uh oh!");
*/
}
<file_sep>/FlySwat/Assets/Scripts/BeeScript.js
public class BeeScript extends BugScript
{
var pos : Vector3;
var speed : Vector2;
var rand : int;
var atkTimer : float;
var flyDamp : float;
var attacking : boolean;
var damage : int;
var dir;
public var HUD : HUDScript;
function BeeScript()
{ //should I make bees bounce or try to pass a direction in from the spawner?
//int side =
//this.dir = side;
}
function Start ()
{
pointValue = 3;
pos = rigidbody.position;
speed = rigidbody.velocity;
rand = Random.Range(0, 3);
atkTimer = 120.0;
flyDamp = 2.0;
attacking = false;
/*
if (rigidbody.position.x = 6)
dir = 0;
if (rigidbody.position.x = 7)
dir = 1;
if (rigidbody.position.y = 2)
dir = 2;
if (rigidbody.position.y = 4)
dir = 3;
*/
}
// Update is called once per frame
function Update ()
{
if (rigidbody.position.x <= -2.6)
{
rigidbody.velocity.x = -1;
}
if (rigidbody.position.x >= 5.1)
{
rigidbody.velocity.x *= -1;
}
if (rigidbody.position.y <= -7.1)
{
rigidbody.velocity.y *= -1;
}
if (rigidbody.position.y >= 7.1)
{
rigidbody.velocity.y *= -1;
}
if (atkTimer <= 0 )
{
if (!attacking)
{
//print("Attacking");
attacking = true;
Attack();
}
}
else
{
switch (rand)
{
case 0: // right
pos.x = (pos.x -((1 * Time.deltaTime) * flyDamp));
break;
case 1: // left
pos.x = (pos.x +((1 * Time.deltaTime) * flyDamp));
break;
case 2:// bottom
pos.y = pos.y -((1 * Time.deltaTime) * flyDamp);
//pos.x = (pos.x -(2 * Time.deltaTime));
break;
case 3: // top
pos.y = pos.y +((1 * Time.deltaTime) * flyDamp);
//pos.x = (pos.x -(2 * Time.deltaTime));
break;
}
rigidbody.position = pos;
atkTimer --;
flyDamp = Mathf.Clamp(flyDamp - 0.01, 0.25, 2);
}
super.Update();
}
function Attack()
{
rigidbody.velocity.x = 0;
rigidbody.velocity.y = 0;
rigidbody.AddForce(0,0, -300);
//rigidbody.velocity.z -= 2;
}
function OnCollisionEnter(collision : Collision)
{
//If hit player
//Damage player from public method in playerhud class
var contact = collision.contacts[0];
if (contact.otherCollider.tag.Equals("HUD"))
{
Destroy(gameObject);
HUD.decreaseLives();
}
super.OnCollisionEnter(collision);
}
}
| 35b107bb6f7e08c292fee8afba56a63e02a80de9 | [
"JavaScript",
"C#",
"Text"
] | 16 | Text | tokenblakk/Game_Code | 4e769d65592f23ec68d8d5f7853ee32cd08e0c78 | 1a1e8d9ae28ab88796984ce200127f25e0f55763 |
refs/heads/master | <file_sep>module DefaultPageContent
extend ActiveSupport::Concern
included do
before_filter :set_page_defaults
end
def set_page_defaults
@page_title = "My Portfolio Website - AC"
@seo_keywords = "<NAME> Portfolio"
end
end<file_sep>Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( blogs.css )
Rails.application.config.assets.precompile += %w( portfolios.css )<file_sep>
Devise.setup do |config|
config.mailer_sender = '<EMAIL>'
require 'devise/orm/active_record'
config.case_insensitive_keys = [:email]
config.strip_whitespace_keys = [:email]
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 11. If
# using other algorithms, it sets how many times you want the password to be hashed.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 11
config.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
config.reset_password_within = 6.hours
config.sign_out_via = :delete
end
| ef8c322d7aa31855cf90531b697ef9e92a8272ac | [
"Ruby"
] | 3 | Ruby | alexcalaca/my-personal-website-ac | fb50fd8183052ba5f5ce4f6278ff3d788cd642e8 | 7f913d64ccde7e3a685dfa976c85467b90b4c6d3 |
refs/heads/master | <repo_name>CrBatista/rust-frontend<file_sep>/src/app/utils/RustUtils.ts
/**
* This class will give Utilities methods for refactoring code
*
* @export
* @class RustUtils
* @author <NAME> <<EMAIL>>
*/
export class RustUtils {
/**
* Will return true if the object is Null or Blank
*
* @static
* @param {*} object
* @returns {boolean}
* @memberof RustUtils
*/
public static isNullOrBlank(objectValue: any): boolean {
return objectValue === null || objectValue === undefined || objectValue === '';
}
}
<file_sep>/src/app/services/authentication.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { BehaviorSubject } from 'rxjs/Rx';
import { User } from '../pojos/User';
import { Settings } from '../utils/Settings';
@Injectable()
export class AuthenticationService {
private static readonly LOGIN_URL = '/oauth/token';
private static readonly LOCAL_STORAGE_KEY = 'session_details';
// API_SECRET Generated from: https://www.blitter.se/utils/basic-authentication-header-generator/
private static readonly API_SECRET = '<KEY>';
private _user: BehaviorSubject<User>;
constructor(private _http: Http) { }
/**
* Logs the user in the application, and sets the user property into LocalStorage
*
* @memberOf AuthenticationService
* @author <NAME> <<EMAIL>>
*/
public login(): void {
const headers: Headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
headers.append('Authorization', 'Basic ' + AuthenticationService.API_SECRET);
const options: RequestOptions = new RequestOptions();
options.headers = headers;
this._http.post(Settings.BACKEND_URL + AuthenticationService.LOGIN_URL, 'grant_type=client_credentials', options)
.map(res => res.json())
.subscribe(result => {
localStorage.setItem(AuthenticationService.LOCAL_STORAGE_KEY, JSON.stringify(result));
// this._defineLoginHandledOnce();
// this._checkStatus();
},
error => {
this.logout();
});
}
public logout(): void {/*
clearInterval(this._intervalId);
this._intervalId = 0;
localStorage.removeItem(AuthenticationService.LOCAL_STORAGE_KEY);
this._user.next(null);
window.setTimeout(() =>
window.location.href = 'http://' + document.domain.replace(/admin\./g, '') + ':' + VisualBoardSettings.backendReadonlyPort, 1000
*/
}
}
<file_sep>/src/app/components/login-container/login-container.component.ts
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { RustUtils } from '../../utils/RustUtils';
@Component({
selector: 'app-login-container',
templateUrl: './login-container.component.html',
styleUrls: ['./login-container.component.less']
})
export class LoginContainerComponent implements OnInit {
@ViewChild('usernameLabel')
private usernameLabel: ElementRef;
@ViewChild('passwordLabel')
private passwordLabel: ElementRef;
@ViewChild('wrapperSubmit')
private wrapperSubmit: ElementRef;
public username: string;
public password: string;
private _usernameFocused: boolean;
private _passwordFocused: boolean;
public textHover: string;
public submitHover: string;
public loginButtonStyle: any;
public loginTextStyle: any;
constructor() { }
ngOnInit() {
this._usernameFocused = false;
this._passwordFocused = false;
}
/**
* Will dinamically add style to input's label (Username and Password)
*
* @param {string} element
* @memberof LoginContainerComponent
*/
public onFocusEvent(element: string): void {
if (element === 'username') {
this._usernameFocused = true;
} else {
this._passwordFocused = true;
}
}
/**
* Will dinamically remove style to input's label (Username and Password)
*
* @param {string} element
* @memberof LoginContainerComponent
*/
public onBlurEvent(element: string): void {
if (element === 'username') {
this._usernameFocused = false;
} else {
this._passwordFocused = false;
}
}
/**
* This method will return the Label Styling
*
* @returns {string}
* @memberof LoginContainerComponent
*/
public setLabelStyles(elementHtml: string): any {
const styleStart = {
'transition': 'all 0.2s',
'top': '0px',
'font-size': '15px'
};
const styleEnd = {
'transition': 'all 0.2s',
'top': '12px',
'font-size': '22px'
};
if (elementHtml === 'username' && (this._usernameFocused || !RustUtils.isNullOrBlank(this.username))) {
return styleStart;
} else if (elementHtml === 'password' && (this._passwordFocused || !RustUtils.isNullOrBlank(this.password))) {
return styleStart;
} else {
return styleEnd;
}
}
/**
* Event launched on Submit Login Hover. Used for styling
*
* @param {Event} event
* @memberof LoginContainerComponent
*/
public hoverLoginButton(event: Event): void {
this.textHover = (event.type === 'mouseover') ? 'submitTextHovered' : null;
this.submitHover = (event.type === 'mouseover') ? 'submitInputHovered' : null;
}
/**
* Event launched on Submit Login clicked. Used for styling and DoLogin
*
* @memberof LoginContainerComponent
*/
public clickLoginButton(): void {
if (this._formInputsAreCorrect()) {
this.loginButtonStyle = 'loginButtonClicked';
(<HTMLInputElement>document.getElementById('loginSubmitText')).value = '';
}
// This will be the OK subscription
setTimeout(() => {
this.loginButtonStyle = 'loginButtonOK';
}, 2000);
}
/**
* Will validate the fields introduced for Login.
*
* @private
* @returns {boolean}
* @memberof LoginContainerComponent
*/
private _formInputsAreCorrect(): boolean {
return true;
}
}
<file_sep>/src/app/utils/Settings.ts
export class Settings {
public static readonly BACKEND_URL = 'https://localhost:2030/rust';
}<file_sep>/src/app/pojos/User.ts
export class User {
public id: string;
public username: string;
public salt: string;
public passwordEncoded: string;
public email: string;
public expirationTime: number;
}
| 987f60412069715f388e4d20ea0cff94a6e29762 | [
"TypeScript"
] | 5 | TypeScript | CrBatista/rust-frontend | 6257c7b2fdb5541b8b6ba9732e3a44ee4b49f259 | 33fd9052b689be9fcfc702b63e813c62a44d20dc |
refs/heads/master | <file_sep># DigitsClassifier-Keras
CNN Model (Digits Classifier) trained and tested using python and converting the existing Keras model to TF.js Layers format for deploying the model in the browser.
<file_sep>const len = 784;
let pred_xs;
let txt = '';
let predArr = [];
let leftBuffer;
let rightBuffer;
let model;
async function preload() {
// Loading the model
model = await tf.loadLayersModel('MNISTv99.53/model.json');
}
function setup() {
createCanvas(800, 280);
background(255);
//creating two canvas
leftBuffer = createGraphics(280, 280);
rightBuffer = createGraphics(520, 280);
predArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let predButton = select('#predict');
predButton.mousePressed(function () {
let inputs = [];
let img = get(0, 0, 280, 280);
img.resize(28, 28);
img.loadPixels();
for (let i = 0; i < len; i++) {
let bright = img.pixels[i * 4];
inputs[i] = (255 - bright) / 255.0;
}
let testing = [];
testing[0] = inputs;
let xs = tf.tensor2d(testing);
pred_xs = xs.reshape([1, 28, 28, 1]);
predict();
xs.dispose();
pred_xs.dispose();
});
let clearButton = select('#Clear');
clearButton.mousePressed(function () {
background(255);
});
}
function predict() {
const preds = model.predict(pred_xs);
const values = preds.dataSync();
predArr = Array.from(values);
let m = max(predArr);
txt = 'Model predicts the digit is ' + predArr.indexOf(m);
preds.dispose();
}
function draw() {
drawLeftBuffer();
drawRightBuffer();
// Paint the off-screen buffers onto the main canvas
image(leftBuffer, 0, 0);
image(rightBuffer, 280, 0);
}
function drawLeftBuffer() {
strokeWeight(20);
stroke(0);
if (mouseIsPressed) {
line(pmouseX, pmouseY, mouseX, mouseY);
}
}
function drawRightBuffer() {
rightBuffer.background(218, 247, 166);
rightBuffer.fill(255);
rightBuffer.textSize(32);
for (var i = 0, j = 0; i <= 280; i += 28, j++) {
if (predArr[j] < 0.01) {
rightBuffer.fill(255);
} else if (predArr[j] < 0.1) {
rightBuffer.fill(200);
} else if (predArr[j] < 0.3) {
rightBuffer.fill(150);
} else if (predArr[j] < 0.6) {
rightBuffer.fill(100);
} else if (predArr[j] < 0.8) {
rightBuffer.fill(50);
} else if (predArr[j] >= 0.8) {
rightBuffer.fill(0);
}
rightBuffer.ellipse(40, 13 + i, 10, 10);
push();
rightBuffer.fill(0);
rightBuffer.textSize(10);
rightBuffer.text("" + j, 47, 17 + i);
pop();
}
noStroke();
rightBuffer.fill(65);
rightBuffer.textSize(18);
rightBuffer.text(txt, 100, 90);
} | 92ccb1a135f9df614afd485be04b81ebbb6b27c4 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | HarivardhanR/DigitsClassifier-Keras | aa9e037b218ec29e10bf9f39b9a5303f08b8073f | 6d701e89a2c1466a5902a48b5fc10031e1296804 |
refs/heads/main | <file_sep>const coin = document.querySelector('#coin');
const button = document.querySelector('#flip');
const button2 = document.querySelector('#flip2');
const button3 = document.querySelector('#top_up');
const button4 = document.querySelector('#transfer');
const status = document.querySelector('#status');
const heads = document.querySelector('#headsCount');
const tails = document.querySelector('#tailsCount');
const token = document.querySelector('#tokensCount');
const text1 = document.querySelector('#textboxmsg');
let headsCount = 0;
let tailsCount = 0;
let tokenCount = 0;
function deferFn(callback, ms) {
setTimeout(callback, ms);
}
function HeadprocessResult(result) {
var textBoxValue = Number(document.getElementById('TEXTBOX_ID').value);
if (tokenCount <= textBoxValue ){
status.innerText = "not enough token to bet!";
}
if (result === 'heads' && textBoxValue <= tokenCount ) {
headsCount++;
tokenCount = tokenCount+ textBoxValue;
token.innerText = tokenCount;
heads.innerText = headsCount;
status.innerText = "You win "+ textBoxValue+ " Token!";
} else if(result === 'tails' && textBoxValue <= tokenCount ){
tailsCount++;
tokenCount = tokenCount- textBoxValue;
token.innerText = tokenCount;
tails.innerText = tailsCount;
status.innerText = "You lose "+ textBoxValue+" Token!";
}
//status.innerText = result.toUpperCase();
//status.innerText = "You won";
if (textBoxValue === "" ){
text1.innerText = "type your value!";
}
text1.innerText = "You entered: " +textBoxValue+" Token";
}
function TailprocessResult(result) {
var textBoxValue = Number(document.getElementById('TEXTBOX_ID').value);
if (tokenCount <= textBoxValue ){
status.innerText = "not enough token to bet!";
}
if (result === 'heads' && textBoxValue <= tokenCount) {
headsCount++;
tokenCount = tokenCount- textBoxValue;
token.innerText = tokenCount;
heads.innerText = headsCount;
status.innerText = "You lose "+ textBoxValue+ " Token!";
} else if(result === 'tails' && textBoxValue <= tokenCount) {
tailsCount++;
tokenCount = tokenCount+ textBoxValue;;
token.innerText = tokenCount;
tails.innerText = tailsCount;
status.innerText = "You win "+ textBoxValue+ " Token!";
}
//status.innerText = result.toUpperCase();
//status.innerText = "You won";
text1.innerText = "You entered: " +textBoxValue+" Token";
}
function top_up() {
var topupValue = Number(document.getElementById('TEXTBOX_TOPUP').value);
tokenCount = tokenCount + topupValue;
token.innerText = tokenCount;
status.innerText = "Added " + topupValue +" tokens";
}
function transfer() {
var transValue = Number(document.getElementById('TEXTBOX_TRANS').value);
if (tokenCount >= transValue ){
tokenCount = tokenCount - transValue;
token.innerText = tokenCount;
status.innerText = "Transferred " + transValue +" ether to your wallet successfully.";
}
else{
status.innerText = "Not enough tokens";
}
}
function flipCoin() {
coin.setAttribute('class', '');
const random = Math.random();
const result = random < 0.5 ? 'heads' : 'tails';
deferFn(function() {
coin.setAttribute('class', 'animate-' + result );
deferFn(HeadprocessResult.bind(null, result), 2900);
}, 100);
}
function flipCoin2() {
coin.setAttribute('class', '');
const random = Math.random();
const result = random < 0.5 ? 'heads' : 'tails';
deferFn(function() {
coin.setAttribute('class', 'animate-' + result );
deferFn(TailprocessResult.bind(null, result), 2900);
}, 100);
}
button.addEventListener('click', flipCoin);
button2.addEventListener('click', flipCoin2);
button3.addEventListener('click', top_up);
button4.addEventListener('click', transfer);
| 4fffea9755ddff9d4e634d70ae0f462c68577d79 | [
"JavaScript"
] | 1 | JavaScript | MingHin-Cheung/CoinflipGame | 34743b87446802197b178f39fb157104c0e808a3 | 2dd6a7fbe69617512ee36fb5d66f617c7f2c430b |
refs/heads/master | <file_sep># ConsoleDisciplinas
Programa de teste usando C++.
Exercício de faculdade.
<file_sep>#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string>
using namespace std;
const unsigned int QUANTIDADE_DIARIO = 10;
const unsigned int QUANTIDADE_ALUNO = 10;
const unsigned int QUANTIDADE_AULA = 10;
const unsigned int OPERACAO_SAIR = 0;
const unsigned int OPERACAO_CADASTRAR = 1;
const unsigned int OPERACAO_CADASTRAR_ALUNO = 2;
const unsigned int OPERACAO_CADASTRAR_AULA = 3;
const unsigned int OPERACAO_PESQUISAR = 4;
const unsigned int OPERACAO_EDITAR_DISCIPLINA_NOME = 5;
const unsigned int OPERACAO_EDITAR_DISCIPLINA_INDICE = 6;
const unsigned int OPERACAO_MENU = 7;
struct Aluno {
int Ra;
string Nome;
};
struct Aula {
string Dia;
string Materia;
};
struct DiarioDeClasse {
int CursoId;
int DisciplinaId;
string NomeCurso;
string NomeDisciplina;
string PeriodoLetivo;
string Turma;
string NomeProfessor;
Aluno alunos[QUANTIDADE_ALUNO];
Aula aulas[QUANTIDADE_AULA];
};
#define BUFFERSIZE 512
int Operacao_Atual;
DiarioDeClasse diario[QUANTIDADE_DIARIO];
char teclado[BUFFERSIZE];
void inicializar();
void limparBuffer();
void limparTela();
void pesquisarDisciplina();
void cadastrarDisciplina();
void exibirMenuPrincipal();
void cadastrarDisciplina();
void cadastrarAluno();
void cadastrarAula();
void editarDisciplina();
void exibirDisciplina(int indice);
int encontrarDisciplina(string disciplina);
int encontrarDisciplinaVazia();
int encontrarAluno(int indiceDiario, int alunora);
int encontrarAlunoVazio(int indiceDiario);
int encontrarAulaVazia(int indiceDiario);
int main() {
setlocale(LC_ALL, "Portuguese");
// Prepara a estrutura para ser usada limpando todos os campos.
inicializar();
// Define a operação atual.
Operacao_Atual = OPERACAO_MENU;
while (Operacao_Atual != OPERACAO_SAIR) {
if (Operacao_Atual == OPERACAO_MENU) {
exibirMenuPrincipal();
}
if (Operacao_Atual == OPERACAO_CADASTRAR) {
cadastrarDisciplina();
}
if (Operacao_Atual == OPERACAO_CADASTRAR_ALUNO) {
cadastrarAluno();
}
if (Operacao_Atual == OPERACAO_CADASTRAR_AULA) {
cadastrarAula();
}
if (Operacao_Atual == OPERACAO_PESQUISAR) {
pesquisarDisciplina();
}
if (Operacao_Atual == OPERACAO_EDITAR_DISCIPLINA_NOME
|| Operacao_Atual == OPERACAO_EDITAR_DISCIPLINA_INDICE) {
editarDisciplina();
}
if (Operacao_Atual < OPERACAO_SAIR && Operacao_Atual > OPERACAO_MENU) {
cout << "Operação inválida, pressione qualquer tecla para voltar ao menu inicial.";
_getch();
Operacao_Atual = OPERACAO_MENU;
}
}
cout << "O programa foi terminado." << endl;
_getch();
return 0;
}
// Limpa todos os campos.
void inicializar() {
for (int i = 0; i < QUANTIDADE_DIARIO; i++) {
diario[i].CursoId = 0;
diario[i].DisciplinaId = 0;
diario[i].NomeCurso = "";
diario[i].NomeDisciplina = "";
diario[i].PeriodoLetivo = "";
diario[i].Turma = "";
diario[i].NomeProfessor = "";
for (int n = 0; n < QUANTIDADE_ALUNO; n++) {
diario[i].alunos[n].Ra = 0;
diario[i].alunos[n].Nome = "";
}
for (int n = 0; n < QUANTIDADE_AULA; n++) {
diario[i].aulas[n].Dia = "";
diario[i].aulas[n].Materia = "";
}
}
}
void limparBuffer() {
setvbuf(stdin, teclado, _IOFBF, BUFFERSIZE);
}
void limparTela() {
#if defined _WIN32 || _WIN64
system("CLS");
#endif
}
void exibirMenuPrincipal() {
limparTela();
cout << "Bem-vindo ao diario de classe." << endl;
cout << "0 - Sair do programa." << endl;
cout << OPERACAO_CADASTRAR << " - Cadastrar Disciplina." << endl;
cout << OPERACAO_CADASTRAR_ALUNO << " - Cadastrar Aluno." << endl;
cout << OPERACAO_CADASTRAR_AULA << " - Cadastrar Aula." << endl;
cout << OPERACAO_PESQUISAR << " - Pesquisar Disciplina." << endl;
cout << OPERACAO_EDITAR_DISCIPLINA_NOME << " - Editar Disciplina Pelo Nome." << endl;
cout << OPERACAO_EDITAR_DISCIPLINA_INDICE << " - Editar Disciplina Pelo Índice." << endl;
cout << "Insira o valor desejado: " << endl;
limparBuffer();
cin >> Operacao_Atual;
}
void pesquisarDisciplina() {
limparTela();
string disciplina = "";
cout << "Insira o nome da disciplina que deseja procurar: ";
limparBuffer();
getline(cin, disciplina);
// Pesquisa a disciplina no vetor.
if (disciplina.length() > 0) {
int indice = encontrarDisciplina(disciplina);
cout << endl;
if (indice < 0) {
cout << "Nenhuma disciplina foi encontrada" << endl;
}
else {
// Exibe o diário de classe passando o índice para parâmetro.
exibirDisciplina(indice);
}
}
else {
cout << "Disciplina inserida inválida." << endl;
}
cout << "Pressione uma tecla para voltar ao menu principal." << endl;
_getch();
Operacao_Atual = OPERACAO_MENU;
}
void cadastrarDisciplina() {
limparTela();
cout << "Insira o nome da disciplia: " << endl;
string disciplina = "";
limparBuffer();
getline(cin, disciplina);
if (disciplina.length() > 0) {
cout << endl;
// Procura a disciplina passando o nome como parâmetro.
int indice = encontrarDisciplina(disciplina);
if (indice == -1) {
int novoRegistro = encontrarDisciplinaVazia();
if (novoRegistro >= 0) {
cout << "Novo registro para: " << disciplina << endl;
diario[novoRegistro].NomeDisciplina = disciplina;
cout << "Código da disciplina: ";
limparBuffer();
cin >> diario[novoRegistro].DisciplinaId;
cout << "Código do curso: ";
limparBuffer();
cin >> diario[novoRegistro].CursoId;
cout << "Nome do curso: ";
limparBuffer();
getline(cin, diario[novoRegistro].NomeCurso);
cout << "Período Letivo: ";
limparBuffer();
getline(cin, diario[novoRegistro].PeriodoLetivo);
cout << "Turma: ";
limparBuffer();
getline(cin, diario[novoRegistro].Turma);
cout << "Professor: ";
limparBuffer();
getline(cin, diario[novoRegistro].NomeProfessor);
cout << endl << "A Disciplina foi cadastrada." << endl;
}
else {
cout << "Não há mais espaços para cadastrar uma nova disciplina." << endl;
}
}
else {
cout << "Esta disciplina já está cadastrada." << endl;
}
}
else {
cout << "Disciplina inserida é inválida." << endl;
}
cout << "Pressione uma tecla para voltar ao menu principal." << endl;
_getch();
Operacao_Atual = OPERACAO_MENU;
}
void cadastrarAluno() {
limparTela();
cout << "Insira o nome da disciplia: " << endl;
string disciplina = "";
limparBuffer();
getline(cin, disciplina);
if (disciplina.length() > 0) {
cout << endl;
// Procura a disciplina passando o nome como parâmetro.
int indice = encontrarDisciplina(disciplina);
if (indice >= 0) {
cout << "Novo registro de aluno em " << disciplina << endl;
int alunoRA = 0;
cout << "Insira o RA: ";
limparBuffer();
cin >> alunoRA;
// Verifica se o aluno já foi cadastrado.
if (encontrarAluno(indice, alunoRA) == 0) {
// Procura por um espaço vazio.
int novoAlunoIndice = encontrarAlunoVazio(indice);
// Cadastra o aluno.
if (novoAlunoIndice >= 0) {
diario[indice].alunos[novoAlunoIndice].Ra = alunoRA;
cout << "Nome do aluno: ";
limparBuffer();
getline(cin, diario[indice].alunos[novoAlunoIndice].Nome);
cout << endl << "O aluno foi cadastrado." << endl;
}
else {
cout << "Não há mais espaços para cadastrar alunos." << endl;
}
}
else {
cout << "O aluno já está cadastrado." << endl;
}
}
else {
cout << "Disciplina não cadastrada." << endl;
}
}
else {
cout << "Disciplina inserida é inválida." << endl;
}
cout << "Pressione uma tecla para voltar ao menu principal." << endl;
_getch();
Operacao_Atual = OPERACAO_MENU;
}
void cadastrarAula() {
limparTela();
cout << "Insira o nome da disciplia: " << endl;
string disciplina = "";
limparBuffer();
getline(cin, disciplina);
if (disciplina.length() > 0) {
cout << endl;
// Procura a disciplina passando o nome como parâmetro.
int indice = encontrarDisciplina(disciplina);
if (indice >= 0) {
cout << "Novo registro de aula em " << disciplina << endl;
int novaAula = encontrarAulaVazia(indice);
if (novaAula >= 0) {
cout << "Dia: ";
limparBuffer();
getline(cin, diario[indice].aulas[indice].Dia);
cout << "Materia: ";
limparBuffer();
getline(cin, diario[indice].aulas[indice].Materia);
cout << endl << "A matéria foi cadastrada." << endl;
}
else {
cout << "Não há mais espaços para registrar aula." << endl;
}
}
else {
cout << "Disciplina não cadastrada." << endl;
}
}
else {
cout << "Disciplina inserida é inválida." << endl;
}
cout << "Pressione uma tecla para voltar ao menu principal." << endl;
_getch();
Operacao_Atual = OPERACAO_MENU;
}
void editarDisciplina() {
limparTela();
int indice = -1;
string disciplina = "";
if (Operacao_Atual == OPERACAO_EDITAR_DISCIPLINA_NOME) {
cout << "Insira o nome da disciplia: " << endl;
limparBuffer();
getline(cin, disciplina);
if (disciplina.length() > 0) {
indice = encontrarDisciplina(disciplina);
if (indice == -1) {
cout << "Disciplina não cadastrada." << endl;
}
}
else {
cout << "Disciplina inserida é inválida." << endl;
}
}
if (Operacao_Atual == OPERACAO_EDITAR_DISCIPLINA_INDICE) {
cout << "Insira o índice do registro da disciplia: " << endl;
cin >> indice;
if (indice < 0 || indice >= QUANTIDADE_DIARIO) {
cout << "Índice do registro inválido." << endl;
cout << "Insira um valor entre 0 e " << QUANTIDADE_DIARIO - 1 << "." << endl;
// Altera o índice para não encontrado para voltar ao menu;
indice = -1;
}
else {
// Verifica se há uma disciplina para editar.
// Se não houver, não faz nada.
if (diario[indice].NomeDisciplina.length() == 0) {
cout << "Nenhuma disciplina cadastrada nesse registro." << endl;
cout << "Use a opção [ " << OPERACAO_CADASTRAR << " ] do menu para cadastrar uma nova disciplina" << endl;
indice = -1;
}
}
}
if (indice >= 0) {
limparTela();
cout << "Editando o registro índice: " << indice << " Disciplina: " << diario[indice].NomeDisciplina << endl;
cout << "Código da disciplina: ";
limparBuffer();
cin >> diario[indice].DisciplinaId;
cout << "Nome Disciplina: ";
limparBuffer();
getline(cin, diario[indice].NomeDisciplina);
cout << "Código do curso: ";
limparBuffer();
cin >> diario[indice].CursoId;
cout << "Nome do curso: ";
limparBuffer();
getline(cin, diario[indice].NomeCurso);
cout << "Período Letivo: ";
limparBuffer();
getline(cin, diario[indice].PeriodoLetivo);
cout << "Turma: ";
limparBuffer();
getline(cin, diario[indice].Turma);
cout << "Professor: ";
limparBuffer();
getline(cin, diario[indice].NomeProfessor);
cout << endl << "O registro do índice " << indice << " foi editado." << endl;
}
cout << endl << "Pressione uma tecla para voltar ao menu principal." << endl;
_getch();
Operacao_Atual = OPERACAO_MENU;
}
void exibirDisciplina(int indice) {
limparTela();
cout << "Diário de Classe Índice: " << indice << endl << endl;
cout << "Código Curso: " << diario[indice].CursoId << endl;
cout << "Nome Curso: " << diario[indice].NomeCurso << endl;
cout << "Código Disciplina: " << diario[indice].DisciplinaId << endl;
cout << "Nome Disciplina: " << diario[indice].NomeDisciplina << endl;
cout << "Período Letivo: " << diario[indice].PeriodoLetivo << endl;
cout << "Turma: " << diario[indice].Turma << endl;
cout << "Professor: " << diario[indice].NomeProfessor << endl;
cout << endl;
cout << "ALUNOS" << endl;
int quantidade = 0;
for (int i = 0; i < QUANTIDADE_ALUNO; i++) {
if (diario[indice].alunos[i].Nome.length() > 0) {
cout << "Matrícula RA: " << diario[indice].alunos[i].Ra;
cout << " Nome: " << diario[indice].alunos[i].Nome;
quantidade++;
}
}
if (quantidade == 0) {
cout << "Nenhum aluno cadastrado." << endl;
}
cout << endl;
cout << "AULAS" << endl;
// Reseta a quantidade.
quantidade = 0;
for (int i = 0; i < QUANTIDADE_AULA; i++) {
if (diario[indice].aulas[i].Materia.length() > 0) {
cout << "Dia: " << diario[indice].aulas[i].Dia;
cout << " Matéria: " << diario[indice].aulas[i].Materia;
cout << endl;
quantidade++;
}
}
cout << endl;
if (quantidade == 0) {
cout << "Nenhuma aula cadastrada." << endl;
}
}
// Procura a disciplina.
// Retorna -1 quando não encontrado.
int encontrarDisciplina(string disciplina) {
// Pesquisa a disciplina no vetor.
for (int i = 0; i < QUANTIDADE_DIARIO; i++) {
if (diario[i].NomeDisciplina == disciplina) {
// Retorna o índice do vetor.
return i;
}
}
return -1;
}
// Procura um espaço vazio.
// Retorna -1 quando estiver cheio.
int encontrarDisciplinaVazia() {
for (int i = 0; i < QUANTIDADE_DIARIO; i++) {
if (diario[i].NomeDisciplina.length() == 0) {
return i;
}
}
return -1;
}
// Procura o aluno.
// Retorna -1 quando não encontrado.
int encontrarAluno(int indiceDiario, int alunora) {
for (int i = 0; i < QUANTIDADE_ALUNO; i++) {
if (diario[indiceDiario].alunos[i].Ra == alunora) {
return i;
}
}
return -1;
}
// Procura um espaço vazio.
// Retorna -1 quando estiver cheio.
int encontrarAlunoVazio(int indiceDiario) {
for (int i = 0; i < QUANTIDADE_ALUNO; i++) {
if (diario[indiceDiario].alunos[i].Ra == 0) {
return i;
}
}
return -1;
}
// Procura um espaço vazio.
// Retorna -1 quando estiver cheio.
int encontrarAulaVazia(int indiceDiario) {
for (int i = 0; i < QUANTIDADE_AULA; i++) {
if (diario[indiceDiario].aulas[i].Materia.length() == 0) {
return i;
}
}
return -1;
} | 3944a250c423ed9941a6bf7753b4a50b25a40da5 | [
"Markdown",
"C++"
] | 2 | Markdown | DragonicK/ConsoleDisciplinas | 3b8d0d1eab897a5b6b19859f9c226370a431be4d | 3d4d394e9929090de8ccffa4c2294031fbf77f31 |
refs/heads/master | <file_sep>import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Color;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.JTextPane;
import java.lang.Math;
public class ComputeShennon{
public static void main(String[] args) {
Compute frame = new Compute();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Compute extends JFrame {
{
setSize(DEFAULT_WEIGHT,DEFAULT_HEIGHT);
setTitle("application");
penl p = new penl();
add(p);
}
public static final int DEFAULT_WEIGHT = 300;
public static final int DEFAULT_HEIGHT = 425;
}
class penl extends JPanel{
class element {
public int number = i;
JTextField textArea = new JTextField();
Action act = new ActionT("X");
Key act2 = new Key(textArea.getText());
JButton button = new JButton(act);
public int h;
public element(){
h = k;
setLayout(null);
textArea.addKeyListener(act2);
textArea.setText("0");
button.setBounds(170, k, 60, 25);
button.setActionCommand(new String().valueOf(number));
//System.out.println("///" + new String().valueOf(number) + " " + i);
textArea.setBounds(30, k, 120, 25);
k += 30;
add(textArea);
add(button);
repaint();
++i;
//System.out.println("i=" + i + " num=" + number);
}
public void view(){
}
}
public class addbut{
Action act = new ActionT("add");
JButton butadd = new JButton(act);
int ha = 85;
public addbut() {
butadd.setBounds(100, ha, 60, 25);
butadd.setActionCommand("add");
add(butadd);
}
}
public void upgrade(int j){
list[j].h = 30 * j + 20;
System.out.println(list[j].h);
list[j].button.setBounds(170, list[j].h , 60, 25);
list[j].textArea.setBounds(30, list[j].h , 120, 25);
list[j].number--;
list[j].button.setActionCommand(new String().valueOf(list[j].number));
Key act2 = new Key(new String().valueOf(list[j].number));
list[j].textArea.addKeyListener(act2);
}
JTextField ans = new JTextField("Answer: ");
{
ans.setBounds(30,5,170,35);
add(ans);
repaint();
}
static int i = 0;
static int k = 50;
element[] list = new element[15];
Font f1 = new Font("Serif", Font.BOLD, 17);
{
ans.setBackground(Color.WHITE);
ans.setFont(f1);
ans.setEditable(false);
}
{
setFont(f1);
}
{
list[0] = new element();
}
//System.out.println();
addbut butadde = new addbut();
public class ActionT extends AbstractAction
{
public ActionT(String name){
putValue(Action.NAME, name);
}
public void actionPerformed(ActionEvent event)
{
if (event.getActionCommand().equals("add")){
list[i] = new element();
remove(butadde.butadd);
butadde.ha = 30 * (i - 1) + 80;
butadde.butadd.setBounds(100, butadde.ha, 60, 25);
add(butadde.butadd);
repaint();
} else {
remove(list[Integer.parseInt(event.getActionCommand())].button);
remove(list[Integer.parseInt(event.getActionCommand())].textArea);
k-=30;
System.out.println(i + " " + Integer.parseInt(event.getActionCommand()) + " " + list[Integer.parseInt(event.getActionCommand())].number );
for (int j = list[Integer.parseInt(event.getActionCommand())].number + 1; j < i; ++j){
list[j - 1] = list[j];
upgrade(j);
}
list[i - 1] = null;
--i;
remove(butadde.butadd);
butadde.ha -= 30;;
butadde.butadd.setBounds(100, butadde.ha, 60, 25);
add(butadde.butadd);
repaint();
//}
}
}
}
public class Key implements DocumentListener, KeyListener {
private String s;
public Key(String s){
this.s = s;
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if ((e.getExtendedKeyCode() >= 48)&(e.getExtendedKeyCode() <= 57)){
double out = 0;
int sum = 0;
double[] input = new double[15];
for (int j = 0; j < i; j++){
//if (list[j].textArea.getText() != "")
//{
try {
input[j] = Double.parseDouble(list[j].textArea.getText());
}
catch (Exception e1){
}
sum+=input[j];
//}
}
for (int j = 0; j < i; j++){
if (sum != 0) {
// out+=(input[j]/sum) * (java.lang.Math.log((double)input[j]/sum)/java.lang.Math.log((double)2));
}
}
//out = out * ( -1);
out = sum;
ans.setText("Answer:" + new String().valueOf(out));
repaint();
}
if (e.getExtendedKeyCode() == 8) {
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
}
}
| f9c77dfc0af0927087bcdcf5cb55f8f45cb3312c | [
"Java"
] | 1 | Java | nvdmk/java | 2ca6d1c8f379439046be01a6fe542c73d4e0198c | 2846b27ba43008029b80301c9d5e8d7f8d31a5d5 |
refs/heads/master | <repo_name>lulu8879/simple-kost-api-laravel<file_sep>/app/Http/Controllers/AvailabilityController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Kost;
use App\Models\User;
use App\Models\Availability;
class AvailabilityController extends Controller
{
// show all availability based on role
// for user only show availability that user sent before
// for owner only show availability that owner receiver based on 'ownerId'
public function index(Request $request) {
if ($request->user()['role'] != 0) {
return response()->json(
Availability::where('userId', $request->user()['id'])
->orderBy('kostId', 'asc')
->get(),
200
);
} else {
return response()->json(
Availability::where('ownerId', $request->user()['id'])
->orderBy('kostId', 'asc')
->get(),
200
);
}
}
// show availability based on role
// for user only show availability that user sent before
// for owner only show availability his kost based on 'kostId'
public function show(Request $request, $kostId) {
if ($request->user()['role'] != 0) {
return response()->json(
Availability::where('userId', $request->user()['id'])
->where('kostId', $kostId)
->orderBy('kostId', 'asc')
->get(),
200
);
} else {
return response()->json(Availability::find($kostId), 200);
}
}
// Method for user to ask availability of owner's kost
// this action will deducted user's credit by 5 point
// this method only for user
public function askRoomAvailability(Request $request, $kostId) {
$userId = $request->user()['id'];
$user = User::find($userId);
$role = $user->role;
if ($role == 0) {
return response()->json([
'status' => 'Access forbidden',
'message' => 'This feature is restricted for current role'
], 403);
} else {
$kost = Kost::find($kostId);
if ($kost) {
$credit = $user->credit;
if ($credit < 5){
return response()->json([
'status' => 'Insufficient Credit',
'message' => 'Your credit is not enough'
], 200);
} else {
$credit = $credit - 5;
$user->credit = $credit;
$user->save();
$availability = Availability::create([
'userId' => $userId,
'kostId' => $kostId,
'ownerId' => $kost->userId,
'status' => 0
]);
if ($user && $availability) {
return response()->json([
'status' => 'OK',
'message' => 'Your request has been sent'
], 202);
} else {
return response()->json([
'status' => 'Error',
'message' => 'Failed to send your request'
], 500);
}
}
} else {
return response()->json([
'status' => 'Not Found',
'message' => 'Data not found'
], 404);
}
}
}
// Method for owner to give availability to user's request
// this method only for owner
public function giveRoomAvailability(Request $request){
$userId = $request->user()['id'];
$user = User::find($userId);
$role = $user->role;
if ($role != 0) {
return response()->json([
'status' => 'Access forbidden',
'message' => 'This feature is restricted for current role'
], 403);
} else {
$availability = Availability::find($request->id);
if ($availability) {
$availability->status = 1;
$availability->is_available = $request->is_available;
$availability->save();
return response()->json([
'status' => 'OK',
'message' => 'Your request has been sent'
], 200);
} else {
return response()->json([
'status' => 'Not Found',
'message' => 'Data not found'
], 404);
}
}
}
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\KostController;
use App\Http\Controllers\AvailabilityController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('/auth/register', [AuthController::class, 'register']);
Route::post('/auth/login', [AuthController::class, 'login']);
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/kost/list', [KostController::class, 'getKostByOwnerId']);
Route::post('/kost/create', [KostController::class, 'insert']);
Route::put('/kost/edit/{id}', [KostController::class, 'update']);
Route::delete('/kost/delete/{id}', [KostController::class, 'destroy']);
Route::post('/kost/{kostId}/availability/ask', [AvailabilityController::class, 'askRoomAvailability']);
Route::get('/availability', [AvailabilityController::class, 'index']);
Route::get('/kost/{kostId}/availability', [AvailabilityController::class, 'show']);
Route::post('/kost/{kostId}/availability/give', [AvailabilityController::class, 'giveRoomAvailability']);
Route::post('/auth/logout', [AuthController::class, 'logout']);
});
Route::get('/kost', [KostController::class, 'index']);
Route::get('/kost/{id}', [KostController::class, 'show']);
Route::post('/kost/search', [KostController::class, 'find']);
<file_sep>/database/migrations/2021_04_18_054758_create_availabilities_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAvailabilitiesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('availabilities', function (Blueprint $table) {
$table->id();
$table->integer('userId');
$table->integer('kostId');
$table->integer('ownerId');
$table->integer('status')->default(0)->comment('0 = send to owner, 1 = confirmed by owner');
$table->integer('is_available')->nullable()->comment('0 = not available, 1 = available');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('availabilities');
}
}
<file_sep>/app/Http/Controllers/KostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use App\Models\Kost;
use App\Models\Availability;
class KostController extends Controller
{
public function index() {
return response()->json(Kost::all(), 200);
}
public function show($id) {
return response()->json(Kost::find($id), 200);
}
public function getKostByOwnerId(Request $request) {
if ($request->user()['role'] != 0) {
return response()->json([
'status' => 'Access forbidden',
'message' => 'This feature is restricted for current role'
], 403);
} else {
return response()->json(
Kost::where('userId', $request->user()['id'])
->orderBy('price', 'asc')
->get(),
200
);
}
}
public function insert(Request $request) {
if ($request->user()['role'] != 0) {
return response()->json([
'status' => 'Access forbidden',
'message' => 'This feature is restricted for current role'
], 403);
} else {
$data = $request->all();
$validator = Validator::make($data, [
'name' => 'required',
'description' => 'required',
'location' => 'required',
'price' => 'required'
]);
if($validator->fails()){
return response()->json([
'status' => 'Bad request',
'message' => 'Validation Error.'.$validator->errors()
], 400);
}
$data['userId'] = $request->user()['id'];
$kost = Kost::create($data);
return response()->json([
'status' => 'OK',
'message' => 'Create success',
'data' => $data
], 201);
}
}
public function update(Request $request, $id) {
if ($request->user()['role'] != 0) {
return response()->json([
'status' => 'Access forbidden',
'message' => 'This feature is restricted for current role'
], 403);
} else {
$kost = Kost::find($id);
if ($kost) {
if ($request->name != null) {
$kost->name = $request->name;
}
if ($request->description != null) {
$kost->description = $request->description;
}
if ($request->location != null) {
$kost->location = $request->location;
}
if ($request->price != null) {
$kost->price = $request->price;
}
$kost->save();
return response()->json([
'status' => 'OK',
'message' => 'Edit success',
'data' => $kost
], 200);
} else {
return response()->json([
'status' => 'Not Found',
'message' => 'Data not found'
], 404);
}
}
}
public function destroy(Request $request, $id) {
if ($request->user()['role'] != 0) {
return response()->json([
'status' => 'Access forbidden',
'message' => 'This feature is restricted for current role'
], 403);
} else {
$kost = Kost::find($id);
if ($kost) {
// When delete kost
// availability with 'kostId' must be deleted if available
$kost->destroy($id);
$availability = Availability::where('kostId', $id);
if ($availability) {
$availability->delete();
}
return response()->json([
'status' => 'OK',
'message' => 'Delete success'
], 200);
} else {
return response()->json([
'status' => 'Not Found',
'message' => 'Data not found'
], 404);
}
}
}
public function find(Request $request) {
$name = $request->name;
$location = $request->location;
$price = $request->price;
// search by selecting parameter
// available parameter is name, location, and price
// result sorted by lowest price
$kost = Kost::when($name, function ($query) use ($name) {
return $query->where('name', 'like', '%'.$name.'%');
})
->when($location, function ($query) use ($location) {
return $query->where('location', 'like', '%'.$location.'%');
})
->when($price, function ($query) use ($price) {
return $query->where('price', $price);
})
->orderBy('price', 'asc')
->get();
if ($kost) {
return response()->json([
'status' => 'OK',
'message' => 'Find success',
'data' => $kost
], 200);
} else {
return response()->json([
'status' => 'Not Found',
'message' => 'Data not found'
], 404);
}
}
}
<file_sep>/README.md
# About This Repository
This is a simple API for organize kost's data by doing CRUD.
This project using Laravel 8 with Laravel Sanctum for Authentication.
# What I Use
- PHP 7.4.3
- Laravel 8.37.0
- Laravel Sanctum for Authentication
# Documentation
Please open this [documentation link](https://documenter.getpostman.com/view/5496895/TzJsfJJ9) for how to use this API.
# Scheduling Task
This project also implement scheduled task for recharge point on the first day of every month at 00:00 named **monthly:recharge**.
To run manually the scheduling:
1. Check the task
```
php artisan list
```
2. Run the task
```
php artisan monthly:recharge
```
or you can use **Crontab**:
1. Open crontab file
```
crontab -e
```
2. Edit crontab file and add
```
0 0 1 * * cd /your-project-path && php artisan monthly:recharge >> /dev/null 2>&1
```
# How to use
1. Clone this Repo
```
git clone https://github.com/lulu8879/simple-kost-api-laravel.git
```
2. Copy file .env.example and rename it to .env
```
cp .env.example .env
```
3. Edit .env, fill DB setting and save
4. Migrate DB
```
php artisan migrate
```
5. Run the project
```
php artisan serve
```
<file_sep>/app/Models/Availability.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Availability extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'userId',
'kostId',
'ownerId',
'status',
'is_available'
];
}
<file_sep>/app/Console/Commands/MonthlyRecharge.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
class MonthlyRecharge extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'monthly:recharge';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Scheduled command to recharge user credit on every start of the month';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$users = User::where('role', 1)->update(['credit' => 20]);
$users = User::where('role', 2)->update(['credit' => 40]);
$this->info('Recharge credit success.');
}
}
| 5a92accc15299d8c93dbabb0611a0e061fe941da | [
"Markdown",
"PHP"
] | 7 | PHP | lulu8879/simple-kost-api-laravel | 21df77ff4b082d6923d24b6e4d174b3fd6613f8c | 5c111fdc7ff6ce803f37e467278fb1c93659825e |
refs/heads/master | <file_sep>angular
.module('universal-inbox', [
'angularMoment',
'utility.logger',
'directive.setHeight',
'ui.router',
'ui.bootstrap',
'universal-inbox.router',
'universal-inbox.AuthController',
'universal-inbox.PostsFactory',
'universal-inbox.MainController',
'universal-inbox.TweetsFactory',
'universal-inbox.GmailFactory',
'universal-inbox.PostsFactory',
'linkify'
]);
<file_sep>'use strict';
function AuthController() {
//const vm = this;
}
angular
.module('universal-inbox.AuthController', [])
.controller('AuthController', AuthController);
AuthController.$inject = [];
<file_sep>TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_BEARER_TOKEN=
SESSION_SECRET=
GMAIL_ACCESS_TOKEN=<file_sep>'use strict';
function PostsFactory($http) {
function updateCompletedStatus(completedStatus, postId) {
return $http({
method: 'PUT',
url: '/api/posts/' + postId,
data: {
changeRequested: 'completedStatus',
newValue: completedStatus,
},
});
}
return { updateCompletedStatus };
}
angular
.module('universal-inbox.PostsFactory', [])
.factory('PostsFactory', PostsFactory);
// A different method to add dependency injection.
PostsFactory.$inject = ['$http'];
| 5c88012eb8dbd7968f3e6fbf153d7cf84fccde1a | [
"JavaScript",
"Shell"
] | 4 | JavaScript | bterrot/universal-inbox | 07bcae5a254038e5f695d4b6593791ceada4a990 | 8e40d5be99c39c26d9c53e95d9422ed701711860 |
refs/heads/master | <repo_name>kuzNRoman/gulp-angular-firebase<file_sep>/README.md
# My Gulp-AngularJs-Firebase
# Install
```sh
$ git clone https://github.com/kuzNRoman/gulp-angular-firebase.git && cd gulp-angular-firebase
$ bower install
$ npm install
$ gulp
```
## Description
You can use this 'gulp-angular-firebase' in your own projects. In folder 'builds' you have 2 folders: 'development' and 'dist'.
Work only in 'development'. I also added some useful libs in project!
And of course, you can improve it!
<file_sep>/builds/dist/app/app.js
$.material.init();
//Создание модуля
(function() {
'use strict';
angular
.module('ngFit', ['ngRoute',
'firebase',
'ngFit.main',
'ngFit.contact',
'ngFit.about'
])
.config(Config)
.constant('FIREBASE_URL', 'https://fitng-ea8bc.firebaseio.com/')
Config.$inject = ['$routeProvider', '$locationProvider', '$logProvider'];
function Config($routeProvider, $locationProvider, $logProvider){
$routeProvider.
otherwise({ redirectTo: '/'});
$locationProvider.html5Mode(true);
//$logProvider.debugEnabled(true);
}
})();
;(function (){
"use strict";
angular
.module('ngFit.about', ['ngRoute'])
.config(['$routeProvider', config])
.controller('AboutCtrl', AboutCtrl);
AboutCtrl.$inject = ['$scope', '$rootScope', '$log'];
function AboutCtrl($scope, $rootScope) {
var vm = this;
$rootScope.curPath = 'about';
};
function config($routeProvider){
$routeProvider.
when('/about', {
templateUrl: 'app/about/about.html',
controller: 'AboutCtrl',
controllerAs: 'vm' //это не тот vm, что в переменной var
});
};
})();
;(function (){
'use strict';
angular.module('ngFit.contact', ['ngRoute'])
.config(['$routeProvider', config])
.controller('ContactCtrl', ContactCtrl);
ContactCtrl.$inject = ['$scope', '$rootScope', '$log'];
function ContactCtrl($scope, $rootScope, $log) {
var vm = this;
$rootScope.curPath = 'contact';
};
function config($routeProvider){
$routeProvider.
when('/contact', {
templateUrl: 'app/contact/contact.html',
controller: 'ContactCtrl',
controllerAs: 'vm' //это не тот vm, что в переменной var
});
};
})();
;(function (){
"use strict";
angular
.module('ngFit.main', ['ngRoute'])
.config(configMain)
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$rootScope', '$log', '$firebaseObject', 'FIREBASE_URL'];
function MainCtrl($scope, $rootScope, $log, FIREBASE_URL, $firebaseObject) {
console.log('ctrl', FIREBASE_URL);
var vm = this;
// FIREBASE
var ref = new Firebase(FIREBASE_URL);
var refObj = $firebase(ref).$asObject();
refObj.$loaded(function () {
vm.db = refObj;
});
$rootScope.curPath = 'main';
vm.url = FIREBASE_URL;
vm.title = 'Это приветственная страница';
vm.name = 'Loftschool';
$scope.clickFunction = function(name) {
alert('Hi, '+ name);
};
};
configMain.$inject = ['$routeProvider', 'FIREBASE_URL'];
function configMain($routeProvider, FIREBASE_URL){
$routeProvider.
when('/', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl',
controllerAs: 'vm' //это не тот vm, что в переменной var
});
console.log('config', FIREBASE_URL);
};
})();
;(function () {
"use strict";
angular
.module('ngFit.navbar',[
'ngRoute'
]);
})(); | ae4bccffe27662019d5a559f48fd292e38db6a36 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | kuzNRoman/gulp-angular-firebase | 938de4497785a8f94556e58014d75e5ee35cbd20 | e60b20ff3c0ef8130a02e5c259c15536b2947e8e |
refs/heads/master | <file_sep>import algoliasearch from 'algoliasearch';
import { store } from '../store';
export function algolia() {
var client = algoliasearch('2LU01OUKRN', '02914a952f251d62334d1019959ca2ba');
var index = client.initIndex('6EuNqjHYcVKRWFky');
index.search(
{
query: store.getters.query,
attributesToRetrieve: ['title', 'type', 'objectID'],
hitsPerPage: 10,
typoTolerance: "true",
},
function searchDone(err, content) {
if (err) throw err;
store.commit("MUTATE_ITEMS", content.hits);
}
)
} | 1da6bbc7260ce16824352173d48134c6f9526397 | [
"JavaScript"
] | 1 | JavaScript | morotaiactivewear/morotai-searchbox | bd689d49cac932990e0f7ed49e262db5504d6a5d | 615d3419a3a25bdba8ece1e0412a3c29a9b97bad |
refs/heads/master | <repo_name>jim-mcandrew/polycraft<file_sep>/src/main/java/edu/utd/minecraft/mod/polycraft/worldgen/GenLayerAddOilDesert.java
package edu.utd.minecraft.mod.polycraft.worldgen;
import edu.utd.minecraft.mod.polycraft.PolycraftMod;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.gen.layer.GenLayer;
public class GenLayerAddOilDesert extends GenLayerBiomeReplacer {
protected static final double NOISE_FIELD_SCALE = 0.001;
protected static final double NOISE_FIELD_THRESHOLD = 0.7;
public GenLayerAddOilDesert(final long worldSeed, final long seed, final GenLayer parent) {
super(worldSeed, seed, parent, NOISE_FIELD_SCALE, NOISE_FIELD_THRESHOLD, PolycraftMod.biomeOilDesert.biomeID);
}
@Override
protected boolean canReplaceBiome(int biomeId) {
return biomeId == BiomeGenBase.desert.biomeID;
}
}
<file_sep>/README.md
polycraft
=========
<file_sep>/src/main/java/edu/utd/minecraft/mod/polycraft/PolycraftMod.java
package edu.utd.minecraft.mod.polycraft;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBow;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidRegistry;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import edu.utd.minecraft.mod.polycraft.proxy.CommonProxy;
import edu.utd.minecraft.mod.polycraft.worldgen.BiomeGenOilDesert;
import edu.utd.minecraft.mod.polycraft.worldgen.BiomeGenOilOcean;
@Mod(modid = PolycraftMod.MODID, version = PolycraftMod.VERSION)
public class PolycraftMod
{
public static final String MODID = "polycraft";
public static final String VERSION = "1.0";
@SidedProxy(clientSide="edu.utd.minecraft.mod.polycraft.proxy.CombinedClientProxy", serverSide="edu.utd.minecraft.mod.polycraft.proxy.DedicatedServerProxy")
public static CommonProxy proxy;
public static int oilWellScalar = 100; //large values mean more oil will spawn
public static BiomeGenOilDesert biomeOilDesert;
public static BiomeGenOilOcean biomeOilOcean;
public static Block blockOil;
public static Item bucketOil;
public static Item plasticHandle;
public static Item plasticHandleWoodPickaxe;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
proxy.preInit();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
proxy.init();
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
proxy.postInit();
}
}
<file_sep>/src/main/java/edu/utd/minecraft/mod/polycraft/worldgen/BiomeInitializer.java
package edu.utd.minecraft.mod.polycraft.worldgen;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import edu.utd.minecraft.mod.polycraft.PolycraftMod;
import net.minecraftforge.event.terraingen.WorldTypeEvent;
public class BiomeInitializer {
public BiomeInitializer() {
}
@SubscribeEvent
public void initBiomes(WorldTypeEvent.InitBiomeGens event) {
if (PolycraftMod.biomeOilDesert != null) {
event.newBiomeGens[0] = new GenLayerAddOilDesert(event.seed, 1500L, event.newBiomeGens[0]);
event.newBiomeGens[1] = new GenLayerAddOilDesert(event.seed, 1500L, event.newBiomeGens[1]);
event.newBiomeGens[2] = new GenLayerAddOilDesert(event.seed, 1500L, event.newBiomeGens[2]);
}
if (PolycraftMod.biomeOilOcean != null) {
event.newBiomeGens[0] = new GenLayerAddOilOcean(event.seed, 1500L, event.newBiomeGens[0]);
event.newBiomeGens[1] = new GenLayerAddOilOcean(event.seed, 1500L, event.newBiomeGens[1]);
event.newBiomeGens[2] = new GenLayerAddOilOcean(event.seed, 1500L, event.newBiomeGens[2]);
}
// int range = GenLayerBiomeReplacer.OFFSET_RANGE;
// Random rand = new Random(event.seed);
// double xOffset = rand.nextInt(range) - (range / 2);
// double zOffset = rand.nextInt(range) - (range / 2);
// double noiseScale = GenLayerAddOilOcean.NOISE_FIELD_SCALE;
// double noiseThreshold = GenLayerAddOilOcean.NOISE_FIELD_THRESHOLD;
// for (int x = -5000; x < 5000; x += 128) {
// for (int z = -5000; z < 5000; z += 128) {
// if (SimplexNoise.noise((x + xOffset) * noiseScale, (z + zOffset) * noiseScale) > noiseThreshold) {
// System.out.printf("Oil Biome: %d, %d\n", x, z);
// }
// }
// }
}
}
<file_sep>/src/main/java/edu/utd/minecraft/mod/polycraft/block/BlockFluid.java
package edu.utd.minecraft.mod.polycraft.block;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Random;
import edu.utd.minecraft.mod.polycraft.PolycraftMod;
import edu.utd.minecraft.mod.polycraft.render.EntityDropParticleFX;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.BlockFluidClassic;
import net.minecraftforge.fluids.Fluid;
public class BlockFluid extends BlockFluidClassic {
protected float particleRed;
protected float particleGreen;
protected float particleBlue;
public BlockFluid(Fluid fluid, Material material) {
super(fluid, material);
}
@SideOnly(Side.CLIENT)
protected IIcon[] theIcon;
protected boolean flammable;
protected int flammability = 0;
@Override
public IIcon getIcon(int side, int meta) {
return side != 0 && side != 1 ? this.theIcon[1] : this.theIcon[0];
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister) {
this.theIcon = new IIcon[] { iconRegister.registerIcon(PolycraftMod.MODID + ":" + fluidName + "_still"), iconRegister.registerIcon(PolycraftMod.MODID + ":" + fluidName + "_flow") };
}
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, Block block) {
super.onNeighborBlockChange(world, x, y, z, block);
if (flammable && world.provider.dimensionId == -1) {
world.newExplosion(null, x, y, z, 4F, true, true);
world.setBlockToAir(x, y, z);
}
}
public BlockFluid setFlammable(boolean flammable) {
this.flammable = flammable;
return this;
}
public BlockFluid setFlammability(int flammability) {
this.flammability = flammability;
return this;
}
@Override
public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) {
return flammable ? 300 : 0;
}
@Override
public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) {
return flammability;
}
@Override
public boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) {
return flammable;
}
@Override
public boolean isFireSource(World world, int x, int y, int z, ForgeDirection side) {
return flammable && flammability == 0;
}
public BlockFluid setParticleColor(float particleRed, float particleGreen, float particleBlue) {
this.particleRed = particleRed;
this.particleGreen = particleGreen;
this.particleBlue = particleBlue;
return this;
}
@Override
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World world, int x, int y, int z, Random rand) {
super.randomDisplayTick(world, x, y, z, rand);
if (rand.nextInt(10) == 0
&& World.doesBlockHaveSolidTopSurface(world, x, y - 1, z)
&& !world.getBlock(x, y - 2, z).getMaterial().blocksMovement()) {
double px = (double) ((float) x + rand.nextFloat());
double py = (double) y - 1.05D;
double pz = (double) ((float) z + rand.nextFloat());
EntityFX fx = new EntityDropParticleFX(world, px, py, pz, particleRed, particleGreen, particleBlue);
FMLClientHandler.instance().getClient().effectRenderer.addEffect(fx);
}
}
@Override
public boolean canDisplace(IBlockAccess world, int x, int y, int z) {
if (world.getBlock(x, y, z).getMaterial().isLiquid())
return false;
return super.canDisplace(world, x, y, z);
}
@Override
public boolean displaceIfPossible(World world, int x, int y, int z) {
if (world.getBlock(x, y, z).getMaterial().isLiquid())
return false;
return super.displaceIfPossible(world, x, y, z);
}
}<file_sep>/src/main/java/edu/utd/minecraft/mod/polycraft/proxy/CommonProxy.java
package edu.utd.minecraft.mod.polycraft.proxy;
import net.minecraft.block.Block;
import net.minecraft.block.BlockStone;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBucket;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fluids.BlockFluidClassic;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import edu.utd.minecraft.mod.polycraft.PolycraftMod;
import edu.utd.minecraft.mod.polycraft.block.BlockFluid;
import edu.utd.minecraft.mod.polycraft.handler.BucketHandler;
import edu.utd.minecraft.mod.polycraft.item.ItemPickaxePlasticHandle;
import edu.utd.minecraft.mod.polycraft.worldgen.BiomeGenOilDesert;
import edu.utd.minecraft.mod.polycraft.worldgen.BiomeGenOilOcean;
import edu.utd.minecraft.mod.polycraft.worldgen.BiomeInitializer;
import edu.utd.minecraft.mod.polycraft.worldgen.OilPopulate;
public class CommonProxy
{
public void preInit()
{
int oilDesertBiomeId = 215;
int oilOceanBiomeId = 216;
class BiomeIdException extends RuntimeException {
public BiomeIdException(String biome, int id) {
super(String.format("You have a Biome Id conflict at %d for %s", id, biome));
}
}
if (oilDesertBiomeId > 0) {
if (BiomeGenBase.getBiomeGenArray () [oilDesertBiomeId] != null) {
throw new BiomeIdException("oilDesert", oilDesertBiomeId);
}
PolycraftMod.biomeOilDesert = BiomeGenOilDesert.makeBiome(oilDesertBiomeId);
}
if (oilOceanBiomeId > 0) {
if (BiomeGenBase.getBiomeGenArray () [oilOceanBiomeId] != null) {
throw new BiomeIdException("oilOcean", oilOceanBiomeId);
}
PolycraftMod.biomeOilOcean = BiomeGenOilOcean.makeBiome(oilOceanBiomeId);
}
Fluid fluidOil = new Fluid("oil").setDensity(800).setViscosity(1500);
FluidRegistry.registerFluid(fluidOil);
PolycraftMod.blockOil = fluidOil.getBlock();
if (PolycraftMod.blockOil == null)
{
PolycraftMod.blockOil = new BlockFluid(fluidOil, Material.water).setFlammable(true).setFlammability(5).setParticleColor(0.7F, 0.7F, 0.0F).setBlockName("blockOil");
GameRegistry.registerBlock(PolycraftMod.blockOil, "blockOil");
fluidOil.setBlock(PolycraftMod.blockOil);
}
PolycraftMod.bucketOil = new ItemBucket(PolycraftMod.blockOil);
PolycraftMod.bucketOil.setUnlocalizedName("bucketOil").setContainerItem(Items.bucket);
PolycraftMod.bucketOil.setTextureName(PolycraftMod.MODID + ":bucket_oil");
GameRegistry.registerItem(PolycraftMod.bucketOil, PolycraftMod.bucketOil.getUnlocalizedName());
FluidContainerRegistry.registerFluidContainer(FluidRegistry.getFluidStack("oil", FluidContainerRegistry.BUCKET_VOLUME), new ItemStack(PolycraftMod.bucketOil), new ItemStack(Items.bucket));
BucketHandler.INSTANCE.buckets.put(PolycraftMod.blockOil, PolycraftMod.bucketOil);
MinecraftForge.EVENT_BUS.register(BucketHandler.INSTANCE);
PolycraftMod.plasticHandle = new Item().setUnlocalizedName("plasticHandle").setCreativeTab(CreativeTabs.tabTools).setTextureName(PolycraftMod.MODID + ":plastic_handle");
GameRegistry.registerItem(PolycraftMod.plasticHandle, "plasticHandle");
Item plasticHandleWoodPickaxe = new ItemPickaxePlasticHandle(ToolMaterial.WOOD).setUnlocalizedName("plasticHandleWoodPickaxe").setCreativeTab(CreativeTabs.tabTools).setTextureName(PolycraftMod.MODID + ":plastic_handle_wood_pickaxe");
GameRegistry.registerItem(plasticHandleWoodPickaxe, "plasticHandleWoodPickaxe");
}
public void init()
{
ItemStack dirtStack = new ItemStack(Blocks.dirt);
ItemStack oilBucketStack = new ItemStack(PolycraftMod.bucketOil);
ItemStack plasticHandleStack = new ItemStack(PolycraftMod.plasticHandle);
ItemStack woodPickaxeStack = new ItemStack(Items.wooden_axe);
ItemStack plasticHandleWoodPickaxeStack = new ItemStack(PolycraftMod.plasticHandleWoodPickaxe);
GameRegistry.addShapelessRecipe(oilBucketStack, dirtStack);
GameRegistry.addShapelessRecipe(plasticHandleStack, oilBucketStack);
GameRegistry.addShapelessRecipe(plasticHandleWoodPickaxeStack, plasticHandleStack, woodPickaxeStack);
}
public void postInit()
{
MinecraftForge.EVENT_BUS.register(OilPopulate.INSTANCE);
MinecraftForge.TERRAIN_GEN_BUS.register(new BiomeInitializer());
}
}
| b2bc3f4a2b4ddf3cc6b6b249e6a1491e7a225b55 | [
"Markdown",
"Java"
] | 6 | Java | jim-mcandrew/polycraft | e86faf31368b099c4e31fc125e850dc9cdef384d | 696633ca32098d652781ba994c79b04b565fca5e |
refs/heads/master | <file_sep>from django.shortcuts import render_to_response
def home(request):
context = {}
return render_to_response('home.html',context)<file_sep>from django.urls import path
from .import views
app_name = 'blog'
urlpatterns = [
#http://localhost:8000/blog/
path('<int:blog_pk>',views.blog_detail,name = 'blog_detail'),
path('',views.blog_list,name = 'blog_list'),
]<file_sep>from django.shortcuts import render_to_response,get_object_or_404
from .models import Blog
from datetime import datetime
# Create your views here.
def blog_list(request):
context = {}
context['blogs'] = Blog.objects.all()
#context['blog_count'] = Blog.objects.all().count() //另一种统计博客数量的方法
return render_to_response('blog_list.html',context)
def blog_detail(request,blog_pk):
blog = get_object_or_404(Blog,pk = blog_pk)
if not request.COOKIES.get('blog_%s_readed' % blog_pk):
blog.readed_num += 1
blog.save()
context = {}
context['blog'] = get_object_or_404(Blog,pk = blog_pk)
response = render_to_response('blog_detail.html',context)
response.set_cookie('blog_%s_readed' % blog_pk,'true')
return response
<file_sep># mysite
django项目
##shuoming
markdown
| 3d4de3ace1b97d0d18a82bed67c7f833c6667ca4 | [
"Markdown",
"Python"
] | 4 | Python | jupeiji/mysite | 371594efe19106eb7cb3eb98debe18adead36839 | b341e9e976ef9d0415eac62344e6cca29ec6e866 |
refs/heads/master | <file_sep>Aqui precisamos colocar uma descrição da página
Vai bem também uma lista de TODOs do programa e um roadmap, ou seja, quais a características futuras.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 16:31:46 2019
@author: Marcos
"""
import os
import xlsxwriter
import xlrd
import statistics
Cycles = 100
Classes = 11
def main():
ExcelFileName = "Data.xlsx"
workbook = xlsxwriter.Workbook(ExcelFileName)
worksheet = workbook.add_worksheet()
HorizAlign = workbook.add_format()
HorizAlign.set_align('center')
LastRowAvailable = 0
worksheet.write(LastRowAvailable, 0, "Cycle")
worksheet.write(LastRowAvailable, 1, "Stats")
for Class in range(Classes):
worksheet.write(LastRowAvailable, 2 + Class, "R" + str(Class))
LastRowAvailable += 1
for root, dirs, files in os.walk('C:\Taima_Furuyama\Mestrado_UNIFESP\Programacao\Python\Simulacoes\TestesEstatisticos\ENVELOPE'):
SourceFiles = [ _ for _ in files if _.endswith('.xlsx') ]
NumberOfFiles = len(SourceFiles)
print(NumberOfFiles)
PercentArray = [[[None for i in range(NumberOfFiles)] for x in range(Classes)] for y in range(Cycles)]
for xlsfile in SourceFiles:
SourceFile = xlrd.open_workbook(os.path.join(root,xlsfile))
SourceSheet = SourceFile.sheet_by_index(0)
for Cycle in range(Cycles): #Ciclos
for Class in range(Classes): #Classes R
RParticles = SourceSheet.cell_value(rowx = Cycle + 1, colx = Class + 8)
CycleTotal = SourceSheet.cell_value(rowx = Cycle + 1, colx = 1)
Percent = (RParticles/CycleTotal)*100
PercentArray[Cycle][Class].pop(0)
PercentArray[Cycle][Class].append(Percent)
# print(PercentArray[9][10][0])
# print(len(PercentArray[9][10]))
MeanArray = [[None for x in range(Classes)] for y in range(Cycles)]
MedianArray = [[None for x in range(Classes)] for y in range(Cycles)]
StdDevArray = [[None for x in range(Classes)] for y in range(Cycles)]
MinArray = [[None for x in range(Classes)] for y in range(Cycles)]
MaxArray = [[None for x in range(Classes)] for y in range(Cycles)]
VarArray = [[None for x in range(Classes)] for y in range(Cycles)]
# print(MeanArray)
# these 2 FOR LOOPS calculate the statistical parameters
for Cycle in range(Cycles):
for Class in range(Classes):
MeanArray[Cycle].pop(0)
Mean = statistics.mean(PercentArray[Cycle][Class])
MeanArray[Cycle].append(Mean)
MedianArray[Cycle].pop(0)
Median = statistics.median(PercentArray[Cycle][Class])
MedianArray[Cycle].append(Median)
StdDevArray[Cycle].pop(0)
StdDev = statistics.pstdev(PercentArray[Cycle][Class])
StdDevArray[Cycle].append(StdDev)
MinArray[Cycle].pop(0)
Min = min(PercentArray[Cycle][Class])
MinArray[Cycle].append(Min)
MaxArray[Cycle].pop(0)
Max = max(PercentArray[Cycle][Class])
MaxArray[Cycle].append(Max)
VarArray[Cycle].pop(0)
Var = statistics.pvariance(PercentArray[Cycle][Class])
VarArray[Cycle].append(Var)
# print(MeanArray)
# print(MedianArray)
# print(StdDevArray)
# print(MinArray)
# print(MaxArray)
# these 2 FOR LOOPS write the data to a Excel file
for Cycle in range(Cycles):
worksheet.write(LastRowAvailable, 0, Cycle)
for Class in range(Classes):
worksheet.write(LastRowAvailable, 1, "Mean")
worksheet.write(LastRowAvailable + 1, 1, "Median")
worksheet.write(LastRowAvailable + 2, 1, "StdDev")
worksheet.write(LastRowAvailable + 3, 1, "Min")
worksheet.write(LastRowAvailable + 4, 1, "Max")
worksheet.write(LastRowAvailable + 5, 1, "Var")
worksheet.write(LastRowAvailable, Class + 2, MeanArray[Cycle][Class])
worksheet.write(LastRowAvailable + 1, Class + 2, MedianArray[Cycle][Class])
worksheet.write(LastRowAvailable + 2, Class + 2, StdDevArray[Cycle][Class])
worksheet.write(LastRowAvailable + 3, Class + 2, MinArray[Cycle][Class])
worksheet.write(LastRowAvailable + 4, Class + 2, MaxArray[Cycle][Class])
worksheet.write(LastRowAvailable + 5, Class + 2, VarArray[Cycle][Class])
LastRowAvailable += 6
workbook.close()
# print("Worksheet name(s): {0}".format(book.sheet_names()))
if __name__ == '__main__':
main()<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
// TODO opção de definir probabilidade da mutação deletéria em cada infecção, de acordo com o ciclo determinado (trabalhar com intervalos)
// esta probabilidade estará sempre atrelada ao ciclo de infecção
// TODO BUG para poucas partículas, porcentagem de partículas que descem de classe pode dar mais de 100%, pois cálculo é feito
// no final do código, e o valor utilizado para o código é o da mutação
// TODO *** avaliar quando encerrar um paciente e passar para o próximo (média das classes for constante)
// TODO fazer simulação definindo em quais ciclos ocorrem infecções
// TODO interface gráfica (gráficos em tempo real, novas janelas para cada paciente etc)
// TODO: A INTRO explanation about this program, the main use, the aim, how it works, the output and what to do with.
namespace Founder_Console_MarcosPC
{
class ProgramGenerations
{
// Number of Generations
// Generation 0 always have only 1 patient
// Generations 1 and forward have the number of patients defined in the PATIENTS variable
public const int Generations = 20;
// this array is called inside the RunPatients function
// it is an array because if there is increment from the infection cycle from one patient to another,
// different values for infection cycle have to be stored
//static int[][] InfectionCycle = new int[Generations][];
static int[] InfectionCycle = new int[] { 2, 4 };
// Number of Patients in Generation 1
public static int Gen1Patients;
// Number of Cycles
public const int Cycles = 10;
// Number of Classes
public const int Classes = 11;
// The "InitialParticles" is the initial amount of viral particles, that is: the initial virus population of a infection.
public const int InitialParticles = 5;
public const int InfectionParticles = 20;
public const int MaxParticles = 1000000; // Limite máximo de partículas que quero impor para cada ciclo (linha)
static double[] DeleteriousProbability = new double[Cycles];
static double[] BeneficialProbability = new double[Cycles];
public const bool BeneficialIncrement = false; // if true, beneficial probability will increase by INCREMENT each cycle
// if false, it will change from a fixed value to another fixed value, at the chosen cycle
public const bool DeleteriousIncrement = false; // if true, deleterious probability will increase by INCREMENT each cycle
// if false, it will change from a fixed value to another fixed value, at the chosen cycle
// Lists to keep the number of particles that go up or down the classes, during mutations
static int[][,] ClassUpParticles = new int[Generations][,];
static int[][,] ClassDownParticles = new int[Generations][,];
static void MainFunction(string[] args)
{
Random rnd = new Random();
//Console.WriteLine(InfectionCycle.GetLength(0));
Gen1Patients = InfectionCycle.GetLength(0);
// create and start the Stopwatch Class. From: https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//Thread.Sleep(10000);
// Declaring the three-dimensional Matrix: it has p Patient, x lines of Cycles and y columns of Classes, defined by the variables above.
int[][,,] Matrix = new int[Generations][,,];
for(int g = 0; g < Generations; g++)
{
Matrix[g] = new int[(int)Math.Pow(Gen1Patients, g), Cycles, Classes];
//InfectionCycle[g] = new int[(int)Math.Pow(Gen1Patients, g)];
ClassUpParticles[g] = new int[(int)Math.Pow(Gen1Patients, g), Cycles];
ClassDownParticles[g] = new int[(int)Math.Pow(Gen1Patients, g), Cycles];
}
//FillInfectionCycleArray(6, 0); // FIRST PARAMETER: initial cycle, SECOND PARAMENTER: increment
if (DeleteriousIncrement)
{
FillDeleteriousArrayWithIncrement(0.3, 0.1); // FIRST PARAMETER: initial probability, SECOND PARAMENTER: increment
}
else
{
FillDeleteriousArray(0.8, 0.9, 5); // FIRST PARAMETER: first probability, SECOND PARAMENTER: second probability
// THIRD PARAMETER: cycle to change from first probability to second probability
}
if (BeneficialIncrement)
{
FillBeneficialArrayWithIncrement(0.0003, 0.0001); // FIRST PARAMETER: initial probability, SECOND PARAMENTER: increment
}
else
{
FillBeneficialArray(0.0003, 0.0008, 5); // FIRST PARAMETER: first probability, SECOND PARAMENTER: second probability
// THIRD PARAMETER: cycle to change from first probability to second probability
}
// The Matrix starts on the Patient 0, 10th position (column) on the line zero.
// The "InitialParticles" is the amount of viral particles that exists in the class 10 on the cycle zero.
// That is: these 5 particles have the potential to create 10 particles each.
Matrix[0][0, 0, 10] = InitialParticles;
RunPatients(Matrix, rnd);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
PrintOutput(Matrix);
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("Total Run Time: " + elapsedTime);
Console.Write("\n");
Console.ReadKey();
}
//static void FillInfectionCycleArray(int InitialCycle, int Increment)
//{
// for(int g = 0; g < Generations; g++)
// {
// for (int i = 0; i < InfectionCycle[g].GetLength(0); i++)
// {
// if (i == 0)
// {
// InfectionCycle[g][i] = InitialCycle;
// }
// else
// {
// if (InfectionCycle[g][i - 1] + Increment < Cycles)
// {
// InfectionCycle[g][i] = InfectionCycle[g][i - 1] + Increment;
// }
// else
// {
// InfectionCycle[g][i] = InfectionCycle[g][i - 1];
// }
// }
// }
// }
//}
static void FillDeleteriousArray(double FirstProbability, double SecondProbability, int ChangeCycle)
{
for (int i = 0; i < DeleteriousProbability.GetLength(0); i++)
{
if (i <= ChangeCycle)
{
DeleteriousProbability[i] = FirstProbability;
}
else
{
DeleteriousProbability[i] = SecondProbability;
}
}
}
static void FillDeleteriousArrayWithIncrement(double InitialProbability, double Increment)
{
for (int i = 0; i < DeleteriousProbability.GetLength(0); i++)
{
if (i == 0)
{
DeleteriousProbability[i] = InitialProbability;
}
else
{
if (DeleteriousProbability[i - 1] + Increment <= (1 - BeneficialProbability.GetLength(0)))
{
DeleteriousProbability[i] = DeleteriousProbability[i - 1] + Increment;
}
else
{
DeleteriousProbability[i] = DeleteriousProbability[i - 1];
}
}
}
}
static void FillBeneficialArray(double FirstProbability, double SecondProbability, int ChangeCycle)
{
for (int i = 0; i < BeneficialProbability.GetLength(0); i++)
{
if (i <= ChangeCycle)
{
BeneficialProbability[i] = FirstProbability;
}
else
{
BeneficialProbability[i] = SecondProbability;
}
}
}
static void FillBeneficialArrayWithIncrement(double InitialProbability, double Increment)
{
for (int i = 0; i < BeneficialProbability.GetLength(0); i++)
{
if (i == 0)
{
BeneficialProbability[i] = InitialProbability;
}
else
{
if (BeneficialProbability[i - 1] + Increment <= (1 - DeleteriousProbability.GetLength(0)))
{
BeneficialProbability[i] = BeneficialProbability[i - 1] + Increment;
}
else
{
BeneficialProbability[i] = BeneficialProbability[i - 1];
}
}
}
}
static void RunPatients(int[][,,] Matrix, Random rndx)
{
// Main Loop to create more particles on the next Cycles from the Cycle Zero (lines values).
// Each matrix position will bring a value. This value will be mutiplied by its own class number (column value).
for (int g = 0; g < Generations; g++)
{
for (int p = 0; p < Matrix[g].GetLength(0); p++)
{
Console.WriteLine("Patient started: GEN {0} - P {1}", g, p);
for (int i = 0; i < Cycles; i++)
{
for (int j = 0; j < Classes; j++)
{
if (i > 0)
{
// Multiplies the number os particles from de previous Cycle by the Class number which belongs.
// This is the progeny composition.
//Matrix[p, i, j] = Matrix[p, (i - 1), j] * j;
Matrix[g][p, i, j] = Matrix[g][p, (i - 1), j] * j;
}
}
CutOffMaxParticlesPerCycle(Matrix, g, p, i, rndx);
ApplyMutationsProbabilities(Matrix, g, p, i);
// if the INFECTIONCYLE array contains the cycle "i"
// and it is not the last generation, make infection
if (InfectionCycle.Contains(i) && (g < Generations - 1))
{
PickRandomParticlesForInfection(Matrix, g, p, i, rndx);
//Console.WriteLine("*** INFECTION CYCLE *** {0}", i);
}
// print which Cycle was finished just to give user feedback, because it may take too long to run.
//Console.WriteLine("Cycles processed: {0}", i);
}
//Console.WriteLine("Patients processed: GEN {0} - P {1}", g, p);
}
}
}
static void ApplyMutationsProbabilities(int[][,,] Matrix, int g, int p, int i)
{
// This function will apply three probabilities: Deleterious, Beneficial or Neutral.
// Their roles is to simulate real mutations of virus genome.
// So here, there are mutational probabilities, which will bring an stochastic scenario sorting the progenies by the classes.
int UpParticles = 0;
int DownParticles = 0;
// Here a random number greater than zero and less than one is selected.
Random rnd = new Random();
double RandomNumber;
// array to store the number of particles of each class, in the current cycle
int[] ThisCycle = new int[Classes];
for (int j = 0; j < Classes; j++)
{
// storing the number of particles of each class (j)
ThisCycle[j] = Matrix[g][p, i, j];
}
for (int j = 0; j < Classes; j++)
{
if (ThisCycle[j] > 0 && i > 0)
{
for (int particles = ThisCycle[j]; particles > 0; particles--)
{
// In this loop, for each particle removed from the Matrix [i,j], a random number is selected.
RandomNumber = rnd.NextDouble();
// If the random number is less than the DeleteriousProbability defined, one particle of the previous Cycle will
// decrease one Class number. Remember this function is inside a loop for each i and each j values.
// So this loop will run through the whole Matrix, particle by particle on its own positions.
if (RandomNumber < DeleteriousProbability[i])
// Deleterious Mutation = 90,0% probability (0.9)
{
Matrix[g][p, i, (j - 1)] = Matrix[g][p, i, (j - 1)] + 1;
Matrix[g][p, i, j] = Matrix[g][p, i, j] - 1;
DownParticles++;
}
else if (RandomNumber < (DeleteriousProbability[i] + BeneficialProbability[i]))
// Beneficial Mutation = 0,5% probability (0.005)
{
if (j < (Classes - 1))
{
Matrix[g][p, i, (j + 1)] = Matrix[g][p, i, (j + 1)] + 1;
Matrix[g][p, i, j] = Matrix[g][p, i, j] - 1;
}
if (j == Classes)
{
Matrix[g][p, i, j] = Matrix[g][p, i, j] + 1;
}
UpParticles++;
}
}
}
}
ClassUpParticles[g][p, i] = UpParticles;
ClassDownParticles[g][p, i] = DownParticles;
}
static int ParticlesInCycle(int[][,,] Matrix, int g, int p, int i)
{
// This funtion brings the sum value of particles by Cycle.
int Particles = 0;
for (int j = 0; j < Classes; j++)
{
Particles = Particles + Matrix[g][p, i, j];
}
return Particles;
}
static void CutOffMaxParticlesPerCycle(int[][,,] Matrix, int g, int p, int i, Random rndx)
{
int ParticlesInThisCycle = ParticlesInCycle(Matrix, g, p, i); // Quantidade de partículas somadas por ciclo (linha)
int[] StatusR = new int[Classes]; // Declarando o array que é a lista abaixo
// Se, x = ParticlesInCycle, for maior do que o núm MaxParticles definido, então...
if (ParticlesInThisCycle > MaxParticles)
{
// Para cada valor de x iniciando no valor de soma das partículas por ciclo;
// sendo x, ou seja, esta soma, maior do que o limite MaxParticles definido;
// então, diminua em uma unidade a soma das partículas por ciclo até que atinja o limite MaxParticles definido.
for (int Particles = ParticlesInCycle(Matrix, g, p, i); Particles > MaxParticles; Particles--)
// PARTICLES is equal to PARTICLESINTHISCYCLE, but we don't want to modifify PARTICLESINTHISCYCLE while the for loop is running
// also, PARTICLESINTHISCYCLE was created outside the for loop, for other purpose
{
StatusR[0] = Matrix[g][p, i, 0];
StatusR[1] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1];
StatusR[2] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2];
StatusR[3] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3];
StatusR[4] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4];
StatusR[5] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5];
StatusR[6] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6];
StatusR[7] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7];
StatusR[8] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7] + Matrix[g][p, i, 8];
StatusR[9] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7] + Matrix[g][p, i, 8] + Matrix[g][p, i, 9];
StatusR[10] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7] + Matrix[g][p, i, 8] + Matrix[g][p, i, 9] + Matrix[g][p, i, 10];
// Gero um número aleatório de 0 ao limite do valor de soma de partículas por ciclo (linha) = ParticlesInCycle
// int RandomMaxParticles;
int rndParticle = rndx.Next(1, ParticlesInCycle(Matrix, g, p, i));
// Aqui gero as condições para saber de qual classe serão retiradas as partículas para que
// ParticlesInCycle atinja o limite estipulado por MaxParticles
if (rndParticle > 0 && rndParticle <= StatusR[0])
{
Matrix[g][p, i, 0] = Matrix[g][p, i, 0] - 1;
}
if (rndParticle > StatusR[0] && rndParticle <= StatusR[1])
{
Matrix[g][p, i, 1] = Matrix[g][p, i, 1] - 1;
}
if (rndParticle > StatusR[1] && rndParticle <= StatusR[2])
{
Matrix[g][p, i, 2] = Matrix[g][p, i, 2] - 1;
}
if (rndParticle > StatusR[2] && rndParticle <= StatusR[3])
{
Matrix[g][p, i, 3] = Matrix[g][p, i, 3] - 1;
}
if (rndParticle > StatusR[3] && rndParticle <= StatusR[4])
{
Matrix[g][p, i, 4] = Matrix[g][p, i, 4] - 1;
}
if (rndParticle > StatusR[4] && rndParticle <= StatusR[5])
{
Matrix[g][p, i, 5] = Matrix[g][p, i, 5] - 1;
}
if (rndParticle > StatusR[5] && rndParticle <= StatusR[6])
{
Matrix[g][p, i, 6] = Matrix[g][p, i, 6] - 1;
}
if (rndParticle > StatusR[6] && rndParticle <= StatusR[7])
{
Matrix[g][p, i, 7] = Matrix[g][p, i, 7] - 1;
}
if (rndParticle > StatusR[7] && rndParticle <= StatusR[8])
{
Matrix[g][p, i, 8] = Matrix[g][p, i, 8] - 1;
}
if (rndParticle > StatusR[8] && rndParticle <= StatusR[9])
{
Matrix[g][p, i, 9] = Matrix[g][p, i, 9] - 1;
}
if (rndParticle > StatusR[9] && rndParticle <= StatusR[10])
{
Matrix[g][p, i, 10] = Matrix[g][p, i, 10] - 1;
}
}
}
}
static void PickRandomParticlesForInfection(int[][,,] Matrix, int g, int p, int i, Random rndx)
{
bool NoParticlesForInfection = false;
// array to store the particles that will infect patients of the next generation
// it is just a 1D array (a list) where each index is a class
int[] InfectedParticles = new int[Classes];
int ParticlesInThisCycle = ParticlesInCycle(Matrix, g, p, i); // Quantidade de partículas somadas por ciclo (linha)
int[] StatusR = new int[Classes]; // TODO melhorar o nome deste array
for (int ParticlesSelected = 0; ParticlesSelected < InfectionParticles; ParticlesSelected++)
{
StatusR[0] = Matrix[g][p, i, 0];
StatusR[1] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1];
StatusR[2] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2];
StatusR[3] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3];
StatusR[4] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4];
StatusR[5] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5];
StatusR[6] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6];
StatusR[7] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7];
StatusR[8] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7] + Matrix[g][p, i, 8];
StatusR[9] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7] + Matrix[g][p, i, 8] + Matrix[g][p, i, 9];
StatusR[10] = Matrix[g][p, i, 0] + Matrix[g][p, i, 1] + Matrix[g][p, i, 2] + Matrix[g][p, i, 3] + Matrix[g][p, i, 4] + Matrix[g][p, i, 5] + Matrix[g][p, i, 6] + Matrix[g][p, i, 7] + Matrix[g][p, i, 8] + Matrix[g][p, i, 9] + Matrix[g][p, i, 10];
// Gero um número aleatório de 0 ao limite do valor de soma de partículas por ciclo (linha) = ParticlesInCycle
// int RandomMaxParticles;
if (ParticlesInThisCycle > 0)
{
int rndParticle = rndx.Next(1, ParticlesInThisCycle);
// Aqui gero as condições para saber de qual classe serão retiradas as partículas para que
// ParticlesSelected atinja o limite estipulado por InfectioParticles
if (rndParticle > 0 && rndParticle <= StatusR[0])
{
InfectedParticles[0] += 1;
Matrix[g][p, i, 0] -= 1;
}
if (rndParticle > StatusR[0] && rndParticle <= StatusR[1])
{
InfectedParticles[1] += 1;
Matrix[g][p, i, 1] -= 1;
}
if (rndParticle > StatusR[1] && rndParticle <= StatusR[2])
{
InfectedParticles[2] += 1;
Matrix[g][p, i, 2] -= 1;
}
if (rndParticle > StatusR[2] && rndParticle <= StatusR[3])
{
InfectedParticles[3] += 1;
Matrix[g][p, i, 3] -= 1;
}
if (rndParticle > StatusR[3] && rndParticle <= StatusR[4])
{
InfectedParticles[4] += 1;
Matrix[g][p, i, 4] -= 1;
}
if (rndParticle > StatusR[4] && rndParticle <= StatusR[5])
{
InfectedParticles[5] += 1;
Matrix[g][p, i, 5] -= 1;
}
if (rndParticle > StatusR[5] && rndParticle <= StatusR[6])
{
InfectedParticles[6] += 1;
Matrix[g][p, i, 6] -= 1;
}
if (rndParticle > StatusR[6] && rndParticle <= StatusR[7])
{
InfectedParticles[7] += 1;
Matrix[g][p, i, 7] -= 1;
}
if (rndParticle > StatusR[7] && rndParticle <= StatusR[8])
{
InfectedParticles[8] += 1;
Matrix[g][p, i, 8] -= 1;
}
if (rndParticle > StatusR[8] && rndParticle <= StatusR[9])
{
InfectedParticles[9] += 1;
Matrix[g][p, i, 9] -= 1;
}
if (rndParticle > StatusR[9] && rndParticle <= StatusR[10])
{
InfectedParticles[10] += 1;
Matrix[g][p, i, 10] -= 1;
}
}
else
{
NoParticlesForInfection = true;
}
}
// if there are no particles for infection, there is no infection
if (NoParticlesForInfection)
{
Console.WriteLine("Patient {0} Cycle {1} has no particles.\t\t", p, i);
}
else
{
InfectPatients(Matrix, InfectedParticles, InfectionParticles, g, p, i, rndx);
}
}
static void InfectPatients(int[][,,] Matrix, int[] InfectedParticles, int InfectionParticles, int g, int p, int i, Random rndx)
{
int AmountOfParticlesAvailable = InfectedParticles[0] + InfectedParticles[1] + InfectedParticles[2] + InfectedParticles[3] +
InfectedParticles[4] + InfectedParticles[5] + InfectedParticles[6] + InfectedParticles[7] +
InfectedParticles[8] + InfectedParticles[9] + InfectedParticles[10];
//Console.WriteLine(AmountOfParticlesAvailable);
int[] PatientsToInfect = new int[Gen1Patients];
// each patient will infect a group of patients of size Gen1Patients
int LastPatient = ((p + 1) * Gen1Patients) - 1; // the last patient of this group
int FirstPatient = LastPatient - (Gen1Patients - 1); // the first patient of this group
for (int x = 0; x < Gen1Patients; x++)
{
PatientsToInfect[x] = FirstPatient + x;
//Console.WriteLine(PatientsToInfect[x]);
}
//Console.WriteLine(FirstPatient);
//Console.WriteLine(LastPatient);
int patient = PatientsToInfect[Array.IndexOf(InfectionCycle, i)];
while (AmountOfParticlesAvailable > 0)
{
int rndClass = rndx.Next(0, Classes);
if (InfectedParticles[rndClass] > 0) // there is at least one particle in the class selected
{
Matrix[g + 1][patient, 0, rndClass] += 1;
//ParticlesReceived[patient] += 1;
InfectedParticles[rndClass] -= 1;
AmountOfParticlesAvailable--;
}
}
Console.WriteLine("G {0} P {1} infected G {2} P {3}", g, p, g + 1, patient);
}
static void PrintOutput(int[][,,] Matrix)
{
double PercentageOfParticlesUp = 0.0;
double PercentageOfParticlesDown = 0.0;
StreamWriter writer = new StreamWriter("numbers.txt");
// The writer will bring the output file (txt in this case)
// Ensure the writer will be closed when no longer used
using (writer)
{
// Formatting Output for the Console screen.
Console.WriteLine("");
Console.Write("\t\t\tR0\tR1\tR2\tR3\tR4\tR5\tR6\tR7\tR8\tR9\t\tR10\n\n");
writer.Write("\t\tSoma\tR0\tR1\tR2\tR3\tR4\tR5\tR6\tR7\tR8\t\tR9\t\tR10\n\n");
writer.WriteLine("\n");
for (int g = 0; g < Generations; g++)
{
for (int p = 0; p < Matrix[g].GetLength(0); p++)
{
for (int i = 0; i < Cycles; i++)
{
Console.Write("G {0} P {1} Cic.{2}\t\t",g, p, i);
writer.Write("G {0} P {1} Cic.{2} {3}\t\t", g, p, i, ParticlesInCycle(Matrix, g, p, i));
for (int j = 0; j < Classes; j++)
{
Console.Write("{0}\t", Matrix[g][p, i, j]);
writer.Write("{0}\t", Matrix[g][p, i, j]);
}
PercentageOfParticlesUp = (Convert.ToDouble(ClassUpParticles[g][p, i]) / Convert.ToDouble(ParticlesInCycle(Matrix, g, p, i))) * 100;
PercentageOfParticlesDown = (Convert.ToDouble(ClassDownParticles[g][p, i]) / Convert.ToDouble(ParticlesInCycle(Matrix, g, p, i))) * 100;
Console.WriteLine("\nSoma do ciclo {0}: {1}", i, ParticlesInCycle(Matrix, g, p, i));
Console.WriteLine("Particles Up: {0}, {1} %", ClassUpParticles[g][p, i], PercentageOfParticlesUp);
Console.WriteLine("Particles Down: {0}, {1} %", ClassDownParticles[g][p, i], PercentageOfParticlesDown);
Console.Write("\n");
writer.WriteLine("\n");
}
Console.WriteLine("***************************************************************************************************************");
Console.Write("\n");
Console.Write("\n");
}
}
}
}
}
}
<file_sep>import sys
import platform
import random
import time
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
import xlsxwriter
#import numpy
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QDialog, QPushButton
from PyQt5.QtWidgets import QFileDialog, QTabWidget, QVBoxLayout, QTableWidget, QTableWidgetItem
from PyQt5.QtWidgets import QStatusBar, QCheckBox, QVBoxLayout, QComboBox, QSpinBox, QLineEdit
from PyQt5.QtWidgets import QGroupBox, QTableView, QAbstractItemView
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import QSize, Qt, QAbstractTableModel
from PyQt5.QtCore import QRunnable, pyqtSlot, QThreadPool, QObject, pyqtSignal
SimulationTimes = None
# Number of Generations
# Generation 0 always have only 1 patient
# Generations 1 and forward have the number of patients defined in the GEN1PATIENTS variable
Generations = None
# Number of Patients in Generation 1
Gen1Patients = None
NewWorksheetEachPatient = None
# Number of Cycles
Cycles = None
# Number of Classes
Classes = None
# Matrix containing all the data (generations, patients, cycles and classes)
Matrix = []
# The "InitialParticles" is the initial amount of viral particles, that is: the initial virus population of a infection.
InitialParticles = None
ClassOfInitialParticles = None
InfectionParticles = None
# array of strings to store when infection occurs, so that it can be written to output
InfectionWarnings = []
InfectionWarningsCycle = []
InfectionUserDefined = None
UserDefindedCycleForInfection = None
# this array is called inside the RunSimulation function
NumberOfInfectionCycles = Gen1Patients
# Example:
# {4: 10, 10: 20, 20: 30, 40: 40}
# 0 - 4 = 10%
# 5 - 10 = 20%
# 11 - 20 = 30%
# 21 - 50 = 40%
DrawIntervals = {4: 0, 13: 0, 24: 0, 42: 100}
DrawIntervalsKeys = list(DrawIntervals.keys())
InfectionCycle = {}
CyclesForDrawing = [] # an array with CYCLES number of values, from 0 to CYCLES
DrawingWeights = [] # an array with CYCLES number of values, each one is a weight for the respective cycle
DrawnCycles = [] # an array the size of NumberOfInfectionCycles
# Max particles per cycle
MaxParticles = None
DeleteriousProbability = None
BeneficialProbability = None
# if TRUE, beneficial probability will increase by INCREMENT each cycle
# if FALSE, it will change from a fixed value to another fixed value, at the chosen cycle
BeneficialIncrement = None
FirstBeneficial = None
SecondBeneficial = None
# if TRUE, deleterious probability will increase by INCREMENT each cycle
# if FALSE, it will change from a fixed value to another fixed value, at the chosen cycle
DeleteriousIncrement = False
FirstDeleterious = None
SecondDeleterious = None
ChangeCycle = None
# Maximum R Class that a patient has at cycle 0
# it is also the maximum R Class of received infection
MaxR = 0
# Lists to keep the number of particles that go up or down the classes, during mutations
# So, for example, the list ClassUpParticle[0][1, 4] will keep the number of particles
# that went up 1 class, in GENERATION 0, PATIENT 1, CYCLE 4
ClassUpParticles = []
ClassDownParticles = []
# Excel output global variables
MaxWorksheetSize = 0
workbook = None
worksheet = None
HorizAlign = None
bold = None
LastRowAvailable = 0
LastPatient = -1
# Qt
mainWin = None
ConsoleOut = None
TableOutput = None
TableView = None
class WorkerSignals(QObject):
started = pyqtSignal() # no data
finished = pyqtSignal() # no data
error = pyqtSignal(tuple) # `tuple` (exctype, value, traceback.format_exc() )
result = pyqtSignal(object) # `object` data returned from processing, anything
progress = pyqtSignal(int) # `int` indicating % progress
class Worker(QRunnable):
'''
Worker thread
'''
def __init__(self):
super(Worker, self).__init__()
self.signals = WorkerSignals()
@pyqtSlot()
def run(self):
self.signals.started.emit()
Run()
try:
pass
except:
pass
else:
pass
# self.signals.result.emit(result) # Return the result of the processing
finally:
self.signals.finished.emit() # Done
class MainWindow(QMainWindow):
SimulationStatus = pyqtSignal(int)
def __init__(self):
QMainWindow.__init__(self)
self.threadpool = QThreadPool()
self.worker = Worker()
# self.setMinimumSize(QSize(1200, 950)) # TODO open maximized
# self.showMaximized()
self.setWindowState(QtCore.Qt.WindowMaximized)
self.setWindowTitle("T-Founder") # TODO not "2" actually, change this later
Menu = self.menuBar()
file_menu = Menu.addMenu('File')
# open_action = QtWidgets.QAction('Open', self)
quit_action = QtWidgets.QAction('Quit', self)
# file_menu.addAction(open_action)
file_menu.addAction(quit_action)
quit_action.triggered.connect(self.close)
# open_action.triggered.connect(self.OpenFiles)
# edit_menu = Menu.addMenu('Edit')
# undo_action = QtWidgets.QAction('Undo', self)
# redo_action = QtWidgets.QAction('Redo', self)
# edit_menu.addAction(undo_action)
# edit_menu.addAction(redo_action)
help_menu = Menu.addMenu('Help')
about_action = QtWidgets.QAction('About', self)
help_menu.addAction(about_action)
about_action.triggered.connect(self.AboutDialog)
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.gridLayout = QGridLayout(self)
# self.setLayout(self.gridLayout)
self.gridLayout.setSpacing(0)
self.gridLayout.setContentsMargins(0, 0, 0, 0) # int LEFT, TOP, RIGHT, BOTTOM
centralWidget.setLayout(self.gridLayout)
# self.statusBar().showMessage("System Status | Normal")
self.MainTabBar = TabBar(self)
# MainTabBar.setFixedSize(QSize(800, 800))
self.MainTabBar.setMinimumWidth(800)
self.gridLayout.addWidget(self.MainTabBar, 1, 0)
""""""""""""""""""""""""""""""
""" Run Simulation Button """
""""""""""""""""""""""""""""""
self.RunButton = QPushButton("Run Simulation")
self.gridLayout.addWidget(self.RunButton, 0, 0)
self.RunButton.clicked.connect(self.RunWorker)
# self.RunButton.clicked.connect(Run)
self.StatusBar = QStatusBar()
self.StatusBar.setMaximumHeight(30)
self.StatusBar.setStyleSheet("background: lightgray")
self.StatusBar.showMessage("T-Founder Ready")
# addWidget(int fromRow, int fromColumn, int rowSpan, int columnSpan)
self.gridLayout.addWidget(self.StatusBar, 31, 0, 1, 4)
def RunWorker(self):
self.StatusBar.setStyleSheet("background: yellow")
self.StatusBar.showMessage("Simulations running")
# here we reassign self.worker, because it is deleted after a thread
# is finished
self.worker = Worker()
self.threadpool.start(self.worker)
self.worker.signals.finished.connect(self.SimComplete)
def SimComplete(self):
self.StatusBar.setStyleSheet("background: lightgreen")
self.StatusBar.showMessage("Simulations complete. Excel file with results saved")
# if the simulation takes less than 1 second to process
# we may lose (overwrite) Excel files, so, we wait 1 second before next simulation
# TODO it can't be a time.sleep because it freezes the program
time.sleep(1.0)
self.StatusBar.setStyleSheet("background: lightgray")
self.StatusBar.showMessage("T-Founder Ready")
print("Simulation Complete")
def AboutDialog(self):
AboutDialog = QDialog(None, QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowTitleHint)
AboutDialog.setMinimumSize(QSize(500, 400))
gridLayout = QGridLayout(AboutDialog)
AboutDialog.setLayout(gridLayout)
TitleText = "T-Founder"
InfoText = '''(C) 2019 T-Founder'''
DevelopersText = '''Developers:
<NAME>
https://github.com/taimafuruyama/Projetos_UNIFESP'''
RequirementsText = '''
Requirements:
Python version 3.6 or higher
PyQt5 or higher
Download the Anaconda distribution to easily get all the packages:
https://www.anaconda.com/distribution/'''
TitelLabel = QLabel(TitleText, AboutDialog)
TitelLabel.setFixedSize(QSize(500, 25))
TitelLabel.setAlignment(QtCore.Qt.AlignCenter)
TitelLabel.setStyleSheet("font: bold 20px;")
gridLayout.addWidget(TitelLabel, 0, 0)
InfoLabel = QLabel(InfoText, AboutDialog)
InfoLabel.setFixedSize(QSize(500, 50))
InfoLabel.setAlignment(QtCore.Qt.AlignCenter)
InfoLabel.setStyleSheet("text-align: justify")
gridLayout.addWidget(InfoLabel, 1, 0)
DevelopersLabel = QLabel(DevelopersText, AboutDialog)
DevelopersLabel.setFixedSize(QSize(500, 80))
DevelopersLabel.setAlignment(QtCore.Qt.AlignCenter)
gridLayout.addWidget(DevelopersLabel, 2, 0)
RequirementsLabel = QLabel(RequirementsText, AboutDialog)
RequirementsLabel.setFixedSize(QSize(500, 150))
RequirementsLabel.setAlignment(QtCore.Qt.AlignCenter)
gridLayout.addWidget(RequirementsLabel, 3, 0)
OkButton = QPushButton("OK",AboutDialog)
gridLayout.addWidget(OkButton, 4, 0)
OkButton.clicked.connect(AboutDialog.close)
AboutDialog.setWindowTitle("About T-Founder")
AboutDialog.setWindowModality(Qt.ApplicationModal)
AboutDialog.exec_()
class TabBar(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
self.parent = parent
# Initialize tab screen
self.tabs = QTabWidget()
self.tabs.setMovable(True)
self.SetupTab = QWidget()
self.PlotTab = QWidget()
self.TableTab = QWidget()
self.ConsoleTab = QWidget()
# Add tabs
self.tabs.addTab(self.SetupTab,"Setup")
self.tabs.addTab(self.PlotTab ,"Plot")
self.tabs.addTab(self.TableTab,"Table Output")
self.tabs.addTab(self.ConsoleTab,"Console Output")
""""""""""""""""""
""" Setup Tab """
""""""""""""""""""
self.SetupTab.layout = QGridLayout(self)
self.SetupTab.setLayout(self.SetupTab.layout)
self.SetupTab.layout.setSpacing(10)
self.SetupTab.layout.setContentsMargins(10, 5, 10, 0) # int LEFT, TOP, RIGHT, BOTTOM
# self.tab1.setStyleSheet("background: lightgray")
self.SimulationTimesLabel = QLabel("Simulations")
self.SetupTab.layout.addWidget(self.SimulationTimesLabel, 0, 0)
self.SimulationTimesField = QLineEdit("1")
self.SetupTab.layout.addWidget(self.SimulationTimesField, 0, 1)
self.GenerationsLabel = QLabel("Generations")
self.SetupTab.layout.addWidget(self.GenerationsLabel, 1, 0)
self.GenerationsField = QLineEdit("1")
self.SetupTab.layout.addWidget(self.GenerationsField, 1, 1)
self.Gen1PatientsLabel = QLabel("Patients at Generation 1")
self.SetupTab.layout.addWidget(self.Gen1PatientsLabel, 2, 0)
self.Gen1PatientsField = QLineEdit("1")
self.SetupTab.layout.addWidget(self.Gen1PatientsField, 2, 1)
self.Gen1PatientsField.textChanged.connect(self.Gen1PatientsChanged)
self.CyclesLabel = QLabel("Cycles")
self.SetupTab.layout.addWidget(self.CyclesLabel, 3, 0)
self.CyclesField = QLineEdit("10")
self.SetupTab.layout.addWidget(self.CyclesField, 3, 1)
self.ClassesLabel = QLabel("Classes")
self.SetupTab.layout.addWidget(self.ClassesLabel, 4, 0)
self.ClassesField = QLineEdit("11")
self.SetupTab.layout.addWidget(self.ClassesField, 4, 1)
self.InitialParticlesLabel = QLabel("Initial Particles")
self.SetupTab.layout.addWidget(self.InitialParticlesLabel, 5, 0)
self.InitialParticlesField = QLineEdit("5")
self.SetupTab.layout.addWidget(self.InitialParticlesField, 5, 1)
self.ClassOfInitialParticlesLabel = QLabel("Class Of Initial Particles")
self.SetupTab.layout.addWidget(self.ClassOfInitialParticlesLabel, 6, 0)
self.ClassOfInitialParticlesField = QLineEdit("10")
self.SetupTab.layout.addWidget(self.ClassOfInitialParticlesField, 6, 1)
self.InfectionParticlesLabel = QLabel("Infection Particles")
self.SetupTab.layout.addWidget(self.InfectionParticlesLabel, 7, 0)
self.InfectionParticlesField = QLineEdit("5")
self.SetupTab.layout.addWidget(self.InfectionParticlesField, 7, 1)
self.NumberOfInfectionCyclesLabel = QLabel("Infection Cycles")
self.SetupTab.layout.addWidget(self.NumberOfInfectionCyclesLabel, 8, 0)
self.NumberOfInfectionCyclesField = QLabel("1")
self.SetupTab.layout.addWidget(self.NumberOfInfectionCyclesField, 8, 1)
self.NumberOfInfectionCyclesField.setMaximumHeight(10)
self.MaxParticlesLabel = QLabel("Max Particles Per Cycle")
self.SetupTab.layout.addWidget(self.MaxParticlesLabel, 9, 0)
self.MaxParticlesField = QLineEdit("10000")
self.SetupTab.layout.addWidget(self.MaxParticlesField, 9, 1)
self.BeneficialIncrementField = QCheckBox("Beneficial Increment")
self.SetupTab.layout.addWidget(self.BeneficialIncrementField, 10, 0)
self.BeneficialIncrementField.setChecked(False)
self.BeneficialIncrementField.stateChanged.connect(self.BeneficialIncrementChanged)
self.FirstBeneficialLabel = QLabel("First Beneficial")
self.SetupTab.layout.addWidget(self.FirstBeneficialLabel, 11, 0)
self.FirstBeneficialField = QLineEdit("0.0003")
self.SetupTab.layout.addWidget(self.FirstBeneficialField, 11, 1)
self.SecondBeneficialLabel = QLabel("Second Beneficial")
self.SetupTab.layout.addWidget(self.SecondBeneficialLabel, 12, 0)
self.SecondBeneficialField = QLineEdit("0.0008")
self.SetupTab.layout.addWidget(self.SecondBeneficialField, 12, 1)
self.SecondBeneficialField.setReadOnly(True)
self.SecondBeneficialField.setStyleSheet("color: gray")
self.DeleteriousIncrementField = QCheckBox("Deleterious Increment")
self.SetupTab.layout.addWidget(self.DeleteriousIncrementField, 13, 0)
self.DeleteriousIncrementField.setChecked(False)
self.DeleteriousIncrementField.stateChanged.connect(self.DeleteriousIncrementChanged)
self.FirstDeleteriousLabel = QLabel("First Deleterious")
self.SetupTab.layout.addWidget(self.FirstDeleteriousLabel, 14, 0)
self.FirstDeleteriousField = QLineEdit("0.3")
self.SetupTab.layout.addWidget(self.FirstDeleteriousField, 14, 1)
self.SecondDeleteriousLabel = QLabel("Second Deleterious")
self.SetupTab.layout.addWidget(self.SecondDeleteriousLabel, 15, 0)
self.SecondDeleteriousField = QLineEdit("0.8")
self.SetupTab.layout.addWidget(self.SecondDeleteriousField, 15, 1)
self.SecondDeleteriousField.setReadOnly(True)
self.SecondDeleteriousField.setStyleSheet("color: gray")
self.ChangeCycleLabel = QLabel("Change Cycle")
self.SetupTab.layout.addWidget(self.ChangeCycleLabel, 16, 0)
self.ChangeCycleField = QLineEdit("8")
self.SetupTab.layout.addWidget(self.ChangeCycleField, 16, 1)
self.InfectionUserDefinedField = QCheckBox("Infection Cycles User Defined")
self.SetupTab.layout.addWidget(self.InfectionUserDefinedField, 17, 0)
self.InfectionUserDefinedField.setChecked(False)
self.InfectionUserDefinedField.stateChanged.connect(self.InfectionUserDefinedChanged)
self.UserDefindedCycleForInfectionLabel = QLabel("User Defined Cycle For Infection")
self.SetupTab.layout.addWidget(self.UserDefindedCycleForInfectionLabel, 18, 0)
self.UserDefindedCycleForInfectionField = QLineEdit("4")
self.SetupTab.layout.addWidget(self.UserDefindedCycleForInfectionField, 18, 1)
self.UserDefindedCycleForInfectionField.setReadOnly(True)
self.UserDefindedCycleForInfectionField.setStyleSheet("color: gray")
self.InfectionIntervalsGroup = QGroupBox("Infection Intervals Probabilities")
self.SetupTab.layout.addWidget(self.InfectionIntervalsGroup, 19, 0, 2, 2)
self.InfectionIntervalsGroup.layout = QGridLayout(self)
self.InfectionIntervalsGroup.setLayout(self.InfectionIntervalsGroup.layout)
self.IntervalsLabels = []
self.IntervalsFields = []
self.ProbLabels = []
self.ProbFields = []
# DrawIntervals = {4: 0, 13: 0, 24: 0, 42: 100}
for i in range(4):
if i == 0:
Interval = 4
p = 0
elif i == 1:
Interval = 13
p = 25
elif i == 2:
Interval = 24
p = 25
else:
Interval = 42
p = 50
self.IntervalsLabels.append(QLabel("Interval " + str(i + 1)))
self.InfectionIntervalsGroup.layout.addWidget(self.IntervalsLabels[i], 0 + i, 0)
self.IntervalsFields.append(QLineEdit(str(Interval)))
self.InfectionIntervalsGroup.layout.addWidget(self.IntervalsFields[i], 0 + i, 1)
self.ProbLabels.append(QLabel("Probability " + str(i + 1)))
self.InfectionIntervalsGroup.layout.addWidget(self.ProbLabels[i], 0 + i, 2)
self.ProbFields.append(QLineEdit(str(p)))
self.InfectionIntervalsGroup.layout.addWidget(self.ProbFields[i], 0 + i, 3)
self.NewWorksheetEachPatientField = QCheckBox("New Worksheet Each Patient")
self.SetupTab.layout.addWidget(self.NewWorksheetEachPatientField, 0, 2)
self.NewWorksheetEachPatientField.setChecked(True)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
""""""""""""""""""
""" Plot Tab """
""""""""""""""""""
self.PlotTab.layout = QVBoxLayout(self)
self.PlotTab.setLayout(self.PlotTab.layout)
self.classes = ['R0', 'R1', 'R2', 'R3', 'R4', 'R5',
'R6', 'R7', 'R8', 'R9', 'R10']
self.values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self.PlotTab.x = range(11)
self.PlotTab.labels = self.classes
#self.PlotTab.width = 0.5 # the width of the bars
self.figure, self.axis = plt.subplots()
self.canvas = FigureCanvasQTAgg(self.figure)
self.axis.bar(self.classes, self.values)
self.axis.set_title("Percentage of classes")
self.axis.set_ylabel("% of Classes")
self.axis.set_xlabel("R Classes")
self.axis.set_xticks(self.PlotTab.x)
start, end = 0, 110
self.axis.yaxis.set_ticks(range(start, end, 10))
self.axis.set_xticklabels(self.PlotTab.labels)
self.axis.yaxis.grid(which="major", color='lightgray', linestyle='-', linewidth=1)
self.PlotTab.layout.addWidget(self.canvas)
""""""""""""""""""""""""
""" Table Output Tab """
""""""""""""""""""""""""
self.TableTab.layout = QVBoxLayout(self)
self.TableTab.setLayout(self.TableTab.layout)
self.Data = QStandardItemModel(0, 10 , self)
self.Data.setHorizontalHeaderLabels(['Cycle', 'R0', 'R1', 'R2', 'R3',
'R4', 'R5', 'R6', 'R7', 'R8', 'R9',
'R10', 'Cycle Particles', 'Mi',
'Particles Up', 'Particles Up - %',
'Particles Down', 'Particles Down - %'])
#item = QStandardItem(str(5))
'''List = []
for i in range(4):
List.append(QStandardItem(str(i)))
self.Data.appendRow(List)'''
#for i in range(4):
# self.Data.setItem(i, 0, item);
self.table = QTableView(self)
self.table.setModel(self.Data)
self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.table.setAlternatingRowColors(True)
self.TableTab.layout.addWidget(self.table)
#self.table.setColumnWidth(1, 50)
self.table.resizeColumnsToContents()
#TODO Save to Excel button
# self.TableTab.SaveToExcelButton = QPushButton("Save to Excel")
# self.TableTab.layout.addWidget(self.TableTab.SaveToExcelButton)
#self.TableTab.table.setItem(0,0, QTableWidgetItem("Cell (1,1)"))
""""""""""""""""""""""""""
""" Console Output Tab """
""""""""""""""""""""""""""
self.ConsoleTab.layout = QVBoxLayout(self)
self.ConsoleTab.setLayout(self.ConsoleTab.layout)
self.ConsoleTab.layout.setSpacing(0)
self.ConsoleTab.layout.setContentsMargins(0, 0, 0, 0) # int LEFT, TOP, RIGHT, BOTTOM
self.scrollArea = QtWidgets.QScrollArea(self.ConsoleTab)
self.scrollArea.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.scrollArea.setWidgetResizable(True)
widget = QWidget()
self.scrollArea.setWidget(widget)
self.layoutScrollArea = QVBoxLayout(widget)
self.ConsoleOutput = QtWidgets.QTextEdit()
self.ConsoleOutput.setReadOnly(True)
self.ConsoleOutput.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.layoutScrollArea.addWidget(self.ConsoleOutput)
self.ConsoleTab.layout.addWidget(self.scrollArea)
def Gen1PatientsChanged(self, text):
if text != "":
if int(text) == 0:
self.Gen1PatientsField.setText(str(1))
text = "1"
if text != "" and int(text) > 4:
self.Gen1PatientsField.setText(str(4))
text = "4"
self.NumberOfInfectionCyclesField.setText(text)
def InfectionUserDefinedChanged(self):
if self.InfectionUserDefinedField.isChecked():
self.UserDefindedCycleForInfectionField.setReadOnly(False)
self.UserDefindedCycleForInfectionField.setStyleSheet("color: black")
for i in range(4):
self.IntervalsFields[i].setReadOnly(True)
self.IntervalsFields[i].setStyleSheet("color: gray")
self.ProbFields[i].setReadOnly(True)
self.ProbFields[i].setStyleSheet("color: gray")
else:
self.UserDefindedCycleForInfectionField.setReadOnly(True)
self.UserDefindedCycleForInfectionField.setStyleSheet("color: gray")
for i in range(4):
self.IntervalsFields[i].setReadOnly(False)
self.IntervalsFields[i].setStyleSheet("color: black")
self.ProbFields[i].setReadOnly(False)
self.ProbFields[i].setStyleSheet("color: black")
def BeneficialIncrementChanged(self):
if self.BeneficialIncrementField.isChecked():
self.SecondBeneficialField.setReadOnly(False)
self.SecondBeneficialField.setStyleSheet("color: black")
else:
self.SecondBeneficialField.setReadOnly(True)
self.SecondBeneficialField.setStyleSheet("color: gray")
def DeleteriousIncrementChanged(self):
if self.DeleteriousIncrementField.isChecked():
self.SecondDeleteriousField.setReadOnly(False)
self.SecondDeleteriousField.setStyleSheet("color: black")
else:
self.SecondDeleteriousField.setReadOnly(True)
self.SecondDeleteriousField.setStyleSheet("color: gray")
def main():
global ConsoleOut, mainWin, TableOutput, TableView
global PlotClasses, PlotData, PlotOutput, PlotCanvas
app = QtCore.QCoreApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
# mainWin.showMaximized()
ConsoleOut = mainWin.MainTabBar.ConsoleOutput
TableOutput = mainWin.MainTabBar.Data
TableView = mainWin.MainTabBar.table
PlotClasses = mainWin.MainTabBar.classes
PlotData = mainWin.MainTabBar.values
PlotOutput = mainWin.MainTabBar.axis
PlotCanvas = mainWin.MainTabBar.canvas
IdentifyMachine()
sys.exit(app.exec_())
def SetupInitialParameters():
global SimulationTimes, Generations, Gen1Patients, NumberOfInfectionCycles
global Cycles, Classes, InitialParticles, ClassOfInitialParticles, InfectionParticles
global Matrix, InfectionWarnings, InfectionWarningsCycle, InfectionCycle
global BeneficialIncrement, DeleteriousIncrement
global FirstBeneficial, SecondBeneficial, FirstDeleterious, SecondDeleterious
global MaxParticles
global CyclesForDrawing, DrawingWeights, DrawnCycles, ChangeCycle, DrawIntervals
global DeleteriousProbability, BeneficialProbability, DrawIntervalsKeys
global InfectionUserDefined, UserDefindedCycleForInfection
global NewWorksheetEachPatient
SimulationTimes = int(mainWin.MainTabBar.SimulationTimesField.text())
Generations = int(mainWin.MainTabBar.GenerationsField.text())
Gen1Patients = int(mainWin.MainTabBar.Gen1PatientsField.text())
NumberOfInfectionCycles = int(mainWin.MainTabBar.Gen1PatientsField.text())
Cycles = int(mainWin.MainTabBar.CyclesField.text())
Classes = int(mainWin.MainTabBar.ClassesField.text())
InitialParticles = int(mainWin.MainTabBar.InitialParticlesField.text())
ClassOfInitialParticles = int(mainWin.MainTabBar.ClassOfInitialParticlesField.text())
InfectionParticles = int(mainWin.MainTabBar.InfectionParticlesField.text())
MaxParticles = int(mainWin.MainTabBar.MaxParticlesField.text())
# TODO make this variables activate or not the second beneficial and deleterious
if mainWin.MainTabBar.BeneficialIncrementField.isChecked():
BeneficialIncrement = True
else:
BeneficialIncrement = False
if mainWin.MainTabBar.DeleteriousIncrementField.isChecked():
DeleteriousIncrement = True
else:
DeleteriousIncrement = False
FirstBeneficial = float(mainWin.MainTabBar.FirstBeneficialField.text())
SecondBeneficial = float(mainWin.MainTabBar.SecondBeneficialField.text())
FirstDeleterious = float(mainWin.MainTabBar.FirstDeleteriousField.text())
SecondDeleterious = float(mainWin.MainTabBar.SecondDeleteriousField.text())
ChangeCycle = int(mainWin.MainTabBar.ChangeCycleField.text())
if mainWin.MainTabBar.InfectionUserDefinedField.isChecked():
InfectionUserDefined = True
else:
InfectionUserDefined = False
UserDefindedCycleForInfection = int(mainWin.MainTabBar.UserDefindedCycleForInfectionField.text())
for i in range(4):
key = int(mainWin.MainTabBar.IntervalsFields[i].text())
value = int(mainWin.MainTabBar.ProbFields[i].text())
DrawIntervals.update({key : value})
# DrawIntervals = {4: 0, 13: 0, 24: 0, 42: 100}
Matrix = []
InfectionWarnings = []
InfectionWarningsCycle = []
InfectionCycle = {}
CyclesForDrawing = []
DrawingWeights = []
DrawnCycles = []
DeleteriousProbability = [0] * Cycles
BeneficialProbability = [0] * Cycles
DrawIntervalsKeys = list(DrawIntervals.keys())
if mainWin.MainTabBar.NewWorksheetEachPatientField.isChecked():
NewWorksheetEachPatient = True
else:
NewWorksheetEachPatient = False
def Setup():
# number of patients at 1st generation is defined by the number of cycles that
# occur infection
#Gen1Patients = InfectionCycle.GetLength(0)
# Declaring the three-dimensional Matrix:
# it has p Patients, Cy lines of Cycles,
# defined by the variables at the begginning of the code.
for g in range(Generations):
Matrix.append([])
ClassUpParticles.append([])
ClassDownParticles.append([])
PatientsPerGen = pow(Gen1Patients, g)
# in the FOR LOOP below, we append 1 array for each patient.
# and 1 array for each cycle.
# we only append cycle here (Cycle 0) because the cycles will be maked at the time
# each progeny is composed
for patients in range(PatientsPerGen):
Matrix[g].append([]) # patient
Matrix[g][patients].append([]) # cycle
ClassUpParticles[g].append([]) # patient
ClassUpParticles[g][patients].append([]) # cycle
ClassDownParticles[g].append([]) # patient
ClassDownParticles[g][patients].append([]) # cycle
#FillInfectionCycleArray(6, 0); // FIRST PARAMETER: initial cycle, SECOND PARAMENTER: increment
if DeleteriousIncrement == True:
FillDeleteriousArrayWithIncrement(FirstDeleterious, 0.1)
# FIRST PARAMETER: initial probability
# SECOND PARAMENTER: increment
else:
FillDeleteriousArray(FirstDeleterious, SecondDeleterious, ChangeCycle)
# FIRST PARAMETER: first probability
# SECOND PARAMENTER: second probability
# THIRD PARAMETER: cycle to change from first probability to second probability
if BeneficialIncrement == True:
FillBeneficialArrayWithIncrement(FirstBeneficial, 0.1)
# FIRST PARAMETER: initial probability
# SECOND PARAMENTER: increment
else:
FillBeneficialArray(FirstBeneficial, SecondBeneficial, ChangeCycle)
# FIRST PARAMETER: first probability
# SECOND PARAMENTER: second probability
# THIRD PARAMETER: cycle to change from first probability to second probability
# The Matrix starts on the Patient 0, 10th position (column) on the line zero.
# The "InitialParticles" is the amount of viral particles that exists in the class 10 on the cycle zero.
# That is: these 5 particles have the potential to create 10 particles each.
for i in range(InitialParticles):
Matrix[0][0][0].append(ClassOfInitialParticles)
def ConfigureExcel():
global MaxWorksheetSize, workbook, worksheet, HorizAlign, LastRowAvailable, bold
MaxWorksheetSize = 1000000 # Max number of lines per worksheet
ExcelFileName = "TFounderSim" + datetime.now().strftime('%d-%m-%Y_%H-%M-%S') + '.xlsx'
workbook = xlsxwriter.Workbook(ExcelFileName, {'constant_memory': True})
#workbook = xlsxwriter.Workbook(ExcelFileName)
worksheet = workbook.add_worksheet()
HorizAlign = workbook.add_format()
HorizAlign.set_align('center')
bold = workbook.add_format({'bold': True})
LastRowAvailable = 0
# set_column(column1, column2, size)
worksheet.set_column(0, 0, 20)
worksheet.set_column(2, 2, 8)
worksheet.set_column(14, 14, 12)
worksheet.set_column(15, 15, 10)
worksheet.set_column(16, 16, 13)
worksheet.set_column(17, 17, 13)
worksheet.set_column(18, 18, 16)
worksheet.write(LastRowAvailable, 0, "Generations", bold)
worksheet.write(LastRowAvailable, 1, Generations)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Gen1Patients", bold)
worksheet.write(LastRowAvailable, 1, Gen1Patients)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "InfectionCycle", bold)
worksheet.write(LastRowAvailable, 1, str(InfectionCycle))
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Cycles", bold)
worksheet.write(LastRowAvailable, 1, Cycles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "InitialParticles", bold)
worksheet.write(LastRowAvailable, 1, InitialParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "ClassOfInitialParticles", bold)
worksheet.write(LastRowAvailable, 1, ClassOfInitialParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "InfectionParticles", bold)
worksheet.write(LastRowAvailable, 1, InfectionParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "MaxParticles", bold)
worksheet.write(LastRowAvailable, 1, MaxParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "First Beneficial", bold)
worksheet.write(LastRowAvailable, 1, FirstBeneficial)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Second Beneficial", bold)
worksheet.write(LastRowAvailable, 1, SecondBeneficial)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "First Deleterious", bold)
worksheet.write(LastRowAvailable, 1, FirstDeleterious)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Second Deleterious", bold)
worksheet.write(LastRowAvailable, 1, SecondDeleterious)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Change Cycle", bold)
worksheet.write(LastRowAvailable, 1, ChangeCycle)
LastRowAvailable += 1
def MakeNewWorksheet():
global MaxWorksheetSize, workbook, worksheet, HorizAlign, LastRowAvailable, bold, LastPatient
worksheet = workbook.add_worksheet()
HorizAlign = workbook.add_format()
HorizAlign.set_align('center')
bold = workbook.add_format({'bold': True})
LastRowAvailable = 0
LastPatient = -1
# set_column(column1, column2, size)
worksheet.set_column(0, 0, 20)
worksheet.set_column(2, 2, 8)
worksheet.set_column(14, 14, 12)
worksheet.set_column(15, 15, 10)
worksheet.set_column(16, 16, 13)
worksheet.set_column(17, 17, 13)
worksheet.set_column(18, 18, 16)
def FillDeleteriousArray(FirstProbability, SecondProbability, ChangeCycle):
for i in range(Cycles):
if i <= ChangeCycle:
DeleteriousProbability[i] = FirstProbability
else:
DeleteriousProbability[i] = SecondProbability
def FillDeleteriousArrayWithIncrement(InitialProbability, Increment):
for i in range(Cycles):
if i == 0:
DeleteriousProbability[i] = InitialProbability
else:
if (DeleteriousProbability[i - 1] + Increment <= (1 - len(BeneficialProbability))):
DeleteriousProbability[i] = DeleteriousProbability[i - 1] + Increment
else:
DeleteriousProbability[i] = DeleteriousProbability[i - 1]
def FillBeneficialArray(FirstProbability, SecondProbability, ChangeCycle):
for i in range(Cycles):
if i <= ChangeCycle:
BeneficialProbability[i] = FirstProbability
else:
BeneficialProbability[i] = SecondProbability
def FillBeneficialArrayWithIncrement(InitialProbability, Increment):
for i in range(Cycles):
if i == 0:
BeneficialProbability[i] = InitialProbability
else:
if (BeneficialProbability[i - 1] + Increment <= (1 - len(DeleteriousProbability))):
BeneficialProbability[i] = BeneficialProbability[i - 1] + Increment
else:
BeneficialProbability[i] = BeneficialProbability[i - 1]
def Run():
SetupInitialParameters()
for i in range(SimulationTimes):
RunSimulation(i)
def RunSimulation(SimulationNumber):
global LastPatient, workbook, worksheet, HorizAlign, LastRowAvailable, MaxR, Simulating
ConfigureExcel()
MakeNewWorksheet()
ConsoleOut = mainWin.MainTabBar.ConsoleOutput
ConsoleOut.append("Simulation started: " + str(datetime.now()))
ConsoleOut.append("")
startTime = datetime.now()
Setup()
# Populates the CyclesForDrawing array with number of cycles
for i in range(Cycles):
CyclesForDrawing.append(i)
# Main Loop to create more particles on the next Cycles from the Cycle Zero.
# Each matrix position will bring a value. This value will be mutiplied by its own class number.
for g in range(Generations):
for p in range(pow(Gen1Patients, g)): # pow(Gen1Patients, g) gives the generation size
print("Patient started: GEN " + str(g) + " - P " + str(p))
ConsoleOut.append("Patient started: GEN " + str(g) + " - P " + str(p))
# worksheet.write(LastRowAvailable + 1, 0, "Patient:")
TableOutput.appendRow(QStandardItem("Generation: " + str(g)))
TableOutput.appendRow(QStandardItem("Patient: " + str(p)))
worksheet.write(LastRowAvailable + 1, 1, "Generation: ")
worksheet.write(LastRowAvailable + 1, 2, str(g))
worksheet.write(LastRowAvailable + 1, 3, "Patient: ")
worksheet.write(LastRowAvailable + 1, 4, str(p))
LastRowAvailable += 1
RunPatient(g, p)
Matrix[g][p].clear()
LastPatient = 0
DrawingWeights.clear()
InfectionWarnings.clear()
InfectionWarningsCycle.clear()
MaxR = 0
if LastRowAvailable >= MaxWorksheetSize or NewWorksheetEachPatient:
worksheet = workbook.add_worksheet()
worksheet.set_column(0, 0, 20)
worksheet.set_column(14, 14, 12)
worksheet.set_column(15, 15, 10)
worksheet.set_column(16, 16, 13)
worksheet.set_column(17, 17, 13)
worksheet.set_column(18, 18, 16)
LastRowAvailable = 0
LastPatient = -1
CyclesForDrawing.clear()
ConsoleOut.append("")
ConsoleOut.append("Simulation ended: " + str(datetime.now()))
ConsoleOut.append("Total run time: " + str(datetime.now() - startTime))
ConsoleOut.append("Date: " + str(datetime.now()))
ConsoleOut.append("Python Implementation: " + platform.python_implementation())
ConsoleOut.append("")
ConsoleOut.append("*******************************************************")
ConsoleOut.append("")
TableOutput.appendRow(QStandardItem("Simulation ended: " + str(datetime.now())))
TableOutput.appendRow(QStandardItem("Total run time: " + str(datetime.now() - startTime)))
TableOutput.appendRow(QStandardItem("Date: " + str(datetime.now())))
TableOutput.appendRow(QStandardItem("Python Implementation: " + platform.python_implementation()))
TableView.resizeColumnsToContents()
TableView.resizeRowsToContents()
TableView.scrollToBottom()
# worksheet.write(Row, Column, String, format)
LastRowAvailable += 2
worksheet.write(LastRowAvailable, 0, "Total run time: " + str(datetime.now() - startTime), bold)
worksheet.write(LastRowAvailable + 1, 0, "Date: " + str(datetime.now()), bold)
workbook.close()
def RunPatient(g, p):
global LastRowAvailable, InfectionCycle
if InfectionUserDefined:
for i in range(1, NumberOfInfectionCycles + 1):
InfectionCycle[i] = UserDefindedCycleForInfection
else:
for i in range(Cycles):
# Populates the DrawingWeights array
if i <= DrawIntervalsKeys[0]:
DrawingWeights.append(DrawIntervals[4])
elif i > DrawIntervalsKeys[0] and i <= DrawIntervalsKeys[1]:
DrawingWeights.append(DrawIntervals[13])
elif i > DrawIntervalsKeys[1] and i <= DrawIntervalsKeys[2]:
DrawingWeights.append(DrawIntervals[24])
else:
DrawingWeights.append(DrawIntervals[42])
# print(DrawingWeights)
DrawnCycles = random.choices(CyclesForDrawing, DrawingWeights, k = NumberOfInfectionCycles)
for i in range(1, NumberOfInfectionCycles + 1):
InfectionCycle[i] = DrawnCycles[i - 1]
# print(InfectionCycle)
for Cy in range(Cycles):
# print(Cy)
if(Cy > 0):
Matrix[g][p].append([]) # adds 1 cycle
ClassUpParticles[g][p].append([]) # adds 1 cycle
ClassDownParticles[g][p].append([]) # adds 1 cycle
for particle in Matrix[g][p][Cy - 1]: # takes 1 particle from previous cycle
for i in range(particle): # creates N new particles, based on the R class
Matrix[g][p][Cy].append(particle)
CutOffMaxParticlesPerCycle(g, p, Cy)
ApplyMutationsProbabilities(g, p, Cy)
#print("Cycle " + str(Cy) + " " + str(Matrix[g][p, Cy]))
for cycle in InfectionCycle:
# IF the current cycle (Cy) is contained inside the INFECTIONCYCLE dictionary
# AND it is not the last generation, make infection
# Cy == InfectionCycle[cycle] is comparing the current the cycle with
# the value, not the key
if Cy == InfectionCycle[cycle] and g < (Generations - 1):
# here we are passing cycle as the key, not the value
PickRandomParticlesForInfection(g, p, Cy, cycle)
SaveData(g, p, Cy)
if Cy > 0:
Matrix[g][p][Cy - 1].clear()
#print which Cycle was finished just to give user feedback, because it may take too long to run.
#print("Cycles processed: " + str(Cy));
#print("Patients processed: GEN " + str(g) + " - P " + str(p));
# memory()
def CutOffMaxParticlesPerCycle(g, p, Cy):
if(len(Matrix[g][p][Cy]) > MaxParticles):
rndParticles = random.sample(Matrix[g][p][Cy], MaxParticles)
Matrix[g][p][Cy] = rndParticles
def ApplyMutationsProbabilities(g, p, Cy):
# This function will apply three probabilities: Deleterious, Beneficial or Neutral.
# Their roles is to simulate real mutations of virus genome.
# So here, there are mutational probabilities, which will bring an
# stochastic scenario sorting the progenies by the classes.
UpParticles = 0
DownParticles = 0
i = 0
if(Cy > 0):
while i < len(Matrix[g][p][Cy]):
# In this loop, for each particle a random number is selected.
# Here a random (float) number greater than zero and less than one is selected.
RandomNumber = random.random()
# If the random number is less than the DeleteriousProbability
# defined, one particle of the previous Cycle will
# decrease one Class number. Remember this function is
# inside a loop for each Cy and each Cl values.
# So this loop will run through the whole Matrix,
# particle by particle on its own positions.
if RandomNumber < DeleteriousProbability[Cy]:
# Deleterious Mutation = 90,0% probability (0.9)
if Matrix[g][p][Cy][i] > 0:
Matrix[g][p][Cy][i] -= 1
else:
Matrix[g][p][Cy][i].pop(i)
DownParticles += 1
elif (RandomNumber < (DeleteriousProbability[Cy] + BeneficialProbability[Cy])):
# Beneficial Mutation = 0,5% probability (0.005)
if Matrix[g][p][Cy][i] < 10:
Matrix[g][p][Cy][i] += 1
UpParticles += 1
i += 1
ClassUpParticles[g][p][Cy] = UpParticles
ClassDownParticles[g][p][Cy] = DownParticles
def PickRandomParticlesForInfection(g, p, Cy, cycleForInfection):
NoParticlesForInfection = False
ParticlesInThisCycle = len(Matrix[g][p][Cy])
# TODO remove selected infection particles from the Matrix, or
if (ParticlesInThisCycle > 0):
if(ParticlesInThisCycle >= InfectionParticles):
InfectedParticles = random.sample(Matrix[g][p][Cy], InfectionParticles)
else:
InfectedParticles = random.sample(Matrix[g][p][Cy], ParticlesInThisCycle)
else:
NoParticlesForInfection = True
# if there are no particles for infection, there is no infection
if (NoParticlesForInfection):
print("Patient " + str(p) + " Cycle " + str(Cy) + " has no particles.")
ConsoleOut.append("Patient " + str(p) + " Cycle " + str(Cy) + " has no particles.")
# OutputFile.write("Patient " + str(p) + " Cycle " + str(Cy) + " has no particles.")
text = "G" + str(g) + " " + "P" + str(p) + " Cycle " + str(Cy) + " has no particles."
InfectionWarnings.append(text)
InfectionWarningsCycle.append(None)
else:
InfectPatients(InfectedParticles, g, p, Cy,cycleForInfection)
def InfectPatients(InfectedParticles, g, p, Cy, cycleForInfection):
global LastRowAvailable
PatientsToInfect = [0] * Gen1Patients
# each patient will infect a group of patients of size Gen1Patients
LastPatient = ((p + 1) * Gen1Patients) - 1; # the last patient of this group
FirstPatient = LastPatient - (Gen1Patients - 1); # the first patient of this group
for x in range(Gen1Patients):
PatientsToInfect[x] = FirstPatient + x
#print(PatientsToInfect[x]);
#print(FirstPatient);
#print(LastPatient);
# Example: if INFECTIONCYCLE is {1: 8, 2: 4, 3: 6, 4: 2}
# and cycleForInfection is 3 (3 is the key, not the value),
# patient = PatientsToInfect[3 - 1] = PatientsToInfect[2]
patient = PatientsToInfect[cycleForInfection - 1]
for particle in InfectedParticles:
# creates 1 new particle, on a patient in the next generation
# in cycle 0. The new particle will be of the same class of the
# one that infected the patient
Matrix[g + 1][patient][0].append(particle)
print("G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy))
# OutputFile.write("G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy) + "\n")
text = "G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy)
InfectionWarnings.append(text)
InfectionWarningsCycle.append(Cy)
# worksheet.write(LastRowAvailable, 0, "G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy))
# LastRowAvailable += 1
def SaveData(g, p, Cy):
global LastRowAvailable, LastPatient, MaxR, PlotData, PlotOutput
Mi = 0
PercentageOfParticlesUp = 0.0
PercentageOfParticlesDown = 0.0
PercentageOfParticlesPerClass = [0] * (Classes + 1)
LastRowAvailable += 1
if LastPatient != p:
for R in range(Classes):
# fill a line in the Excel file with R0, R1, R2 .... R10
worksheet.write(LastRowAvailable, R + 1, "R" + str(R), HorizAlign)
worksheet.write(LastRowAvailable, 0, "Cycle", HorizAlign)
worksheet.write(LastRowAvailable, 12, "Cycle Particles", HorizAlign)
worksheet.write(LastRowAvailable, 13, "Mi", HorizAlign)
worksheet.write(LastRowAvailable, 14, "Particles Up", HorizAlign)
worksheet.write(LastRowAvailable, 15, "Particles Up - %", HorizAlign)
worksheet.write(LastRowAvailable, 16, "Particles Down", HorizAlign)
worksheet.write(LastRowAvailable, 17, "Particles Down - %", HorizAlign)
LastRowAvailable += 1
ClassCount = [0] * (Classes + 1) # We want ClassCount to be an array of 11 positions, from 0 to 10, not 0 to 9
for particle in Matrix[g][p][Cy]:
try:
ClassCount[particle] += 1
except:
print("Error: " + str(particle))
if(len(Matrix[g][p][Cy]) > 0):
PercentageOfParticlesUp = (ClassUpParticles[g][p][Cy] / len(Matrix[g][p][Cy]))
PercentageOfParticlesDown = (ClassDownParticles[g][p][Cy] / len(Matrix[g][p][Cy]))
else:
PercentageOfParticlesUp = 0.0
PercentageOfParticlesDown = 0.0
if(Cy == 0):
if(len(Matrix[g][p][Cy]) > 0):
MaxR = GetMaxR(ClassCount)
if (len(Matrix[g][p][Cy]) == 0):
MaxR = 999
# MaxR = str(GetMaxR(ClassCount)).replace(str(0), str(numpy.NaN))
# variable to store row and write to Qt table
Row = []
Row.append(QStandardItem(str(Cy)))
#PlotData.clear()
for R in range(Classes):
# fill a line in the Excel file with number of particles from R0, R1, R2 .... R10
worksheet.write(LastRowAvailable, R + 1, ClassCount[R], HorizAlign)
Row.append(QStandardItem(str(ClassCount[R])))
if(len(Matrix[g][p][Cy]) > 0):
PercentageOfParticlesPerClass[R] = (ClassCount[R] / len(Matrix[g][p][Cy])) * 100
else:
PercentageOfParticlesPerClass[R] = 0.0
# print(str(R) + " " + str(PercentageOfParticlesPerClass[R]))
#PlotData.append(PercentageOfParticlesPerClass[R])
PlotData[R] = PercentageOfParticlesPerClass[R]
PlotOutput.clear()
PlotOutput.bar(PlotClasses, PlotData)
PlotOutput.set_title("Percentage of classes - Generation "
+ str(g) + " "
+ "Patient " + str(p) + " "
+ "Cycle " + str(Cy))
PlotOutput.set_ylabel("% of Classes")
PlotOutput.set_xlabel("R Classes")
start, end = 0, 110
PlotOutput.yaxis.set_ticks(range(start, end, 10))
PlotOutput.yaxis.grid(which="major", color='lightgray', linestyle='-', linewidth=1)
PlotCanvas.draw()
PlotCanvas.flush_events()
worksheet.write(LastRowAvailable, 0, Cy, HorizAlign)
worksheet.write(LastRowAvailable, 12, len(Matrix[g][p][Cy]), HorizAlign)
Row.append(QStandardItem(str(len(Matrix[g][p][Cy]))))
Mi = GetMi(ClassCount, len(Matrix[g][p][Cy]))
worksheet.write(LastRowAvailable, 13, Mi, HorizAlign)
Row.append(QStandardItem(str(Mi)))
worksheet.write(LastRowAvailable, 14, ClassUpParticles[g][p][Cy], HorizAlign)
worksheet.write(LastRowAvailable, 15, PercentageOfParticlesUp, HorizAlign)
worksheet.write(LastRowAvailable, 16, ClassDownParticles[g][p][Cy], HorizAlign)
worksheet.write(LastRowAvailable, 17, PercentageOfParticlesDown, HorizAlign)
Row.append(QStandardItem(str(ClassUpParticles[g][p][Cy])))
Row.append(QStandardItem(str(PercentageOfParticlesUp)))
Row.append(QStandardItem(str(ClassDownParticles[g][p][Cy])))
Row.append(QStandardItem(str(PercentageOfParticlesDown)))
# LastRowAvailable += 1
TableOutput.appendRow(Row)
TableView.resizeColumnsToContents()
TableView.resizeRowsToContents()
TableView.scrollToBottom()
if Cy == Cycles - 1:
LastRowAvailable += 2
worksheet.write(LastRowAvailable, 0, "Max R at Cycle 0")
worksheet.write(LastRowAvailable, 1, MaxR, HorizAlign)
TableOutput.appendRow(QStandardItem("Max R at Cycle 0: " + str(MaxR)))
LastRowAvailable += 1
for i in range(len(InfectionWarnings)):
worksheet.write(LastRowAvailable, 0, InfectionWarnings[i])
worksheet.write(LastRowAvailable, 2, InfectionWarningsCycle[i])
TableOutput.appendRow(QStandardItem(InfectionWarnings[i]))
#TableOutput.appendRow(QStandardItem(InfectionWarningsCycle[i]))
LastRowAvailable += 1
LastPatient = p
def GetMi(ClassCount, CycleParticles):
# ClassCount = number of particles per cycle, in a 11 position array
MaxPotentialParticles = 0
for R in range(Classes):
MaxPotentialParticles += ClassCount[R] * R
if CycleParticles != 0:
Mi = MaxPotentialParticles/CycleParticles
else:
Mi = 0
return Mi
def GetMaxR(ClassCount):
# ClassCount = number of particles per cycle, in a 11 position array
MaxR = 0
for R in range(Classes):
if ClassCount[R] > 0:
MaxR = R
return MaxR
def memory():
import os
import psutil
process = psutil.Process(os.getpid())
print("Memory used: " + str((process.memory_info().rss)/1048576) + " MB") # in Megabytes
def IdentifyMachine():
# global LastRowAvailable
# worksheet.write(LastRowAvailable, 0, "Python Implementation", bold)
# LastRowAvailable += 1
#
# worksheet.write(LastRowAvailable, 0, platform.python_implementation(), bold)
# LastRowAvailable += 1
try:
import cpuinfo
print("CPU: " + cpuinfo.cpu.info[0]['ProcessorNameString'])
ConsoleOut.append("CPU: " + cpuinfo.cpu.info[0]['ProcessorNameString'])
# worksheet.write(LastRowAvailable, 0, "CPU: " + cpuinfo.cpu.info[0]['ProcessorNameString'])
# LastRowAvailable += 1
except:
print("No cpuinfo.py module. Download it at https://github.com/pydata/numexpr/blob/master/numexpr/cpuinfo.py")
ConsoleOut.append("No cpuinfo.py module. Download it at https://github.com/pydata/numexpr/blob/master/numexpr/cpuinfo.py")
# worksheet.write(LastRowAvailable, 0, "No cpuinfo.py module. Download it at https://github.com/pydata/numexpr/blob/master/numexpr/cpuinfo.py")
# LastRowAvailable += 1
print("Processor: " + platform.processor())
print("Architecture (32 or 64 bits): " + platform.machine())
print("OS: " + platform.platform())
ConsoleOut.append("Processor: " + platform.processor())
ConsoleOut.append("Architecture (32 or 64 bits): " + platform.machine())
ConsoleOut.append("OS: " + platform.platform())
ConsoleOut.append("")
# worksheet.write(LastRowAvailable, 0, "Processor: " + platform.processor())
# LastRowAvailable += 1
# worksheet.write(LastRowAvailable, 0, "Architecture (32 or 64 bits): " + platform.machine())
# LastRowAvailable += 1
# worksheet.write(LastRowAvailable, 0, "OS: " + platform.platform() + "\n")
# LastRowAvailable += 1
if __name__ == "__main__":
main()
# TODO fazer gráficos com frequência relativa: porcentagem de partículas em cada classe
# TODO gerar gráfico boxplot com R Max (Fig.14 pré-dissertação).
# TODO Colocar opção de infectar paciente sempre com partículas das classes mais altas.
# TODO fazer um resumo de dados informando qual foi o paciente máximo com partículas virais dentro dele e qual o total de pacientes popssíveis.
<file_sep>import platform
import random
from datetime import datetime
#import matplotlib.pyplot as plt
import xlsxwriter
#import numpy
# Number of Generations
# Generation 0 always have only 1 patient
# Generations 1 and forward have the number of patients defined in the GEN1PATIENTS variable
Generations = 101
# Number of Patients in Generation 1
Gen1Patients = 1
NewWorksheetEachPatient = True
# Number of Cycles
Cycles = 45
# Number of Classes
Classes = 11
# Matrix containing all the data (generations, patients, cycles and classes)
Matrix = []
# The "InitialParticles" is the initial amount of viral particles, that is: the initial virus population of a infection.
InitialParticles = 5
ClassOfInitialParticles = 10
InfectionParticles = 5
# array of strings to store when infection occurs, so that it can be written to output
InfectionWarnings = []
InfectionWarningsCycle = []
InfectionUserDefined = False
UserDefindedCycleForInfection = 4
# this array is called inside the RunSimulation function
NumberOfInfectionCycles = Gen1Patients
# Example:
# {4: 10, 10: 20, 20: 30, 40: 40}
# 0 - 4 = 10%
# 5 - 10 = 20%
# 11 - 20 = 30%
# 21 - 50 = 40%
DrawIntervals = {4: 10, 13: 15, 24: 55, 42: 20}
DrawIntervalsKeys = list(DrawIntervals.keys())
InfectionCycle = {}
CyclesForDrawing = [] # an array with CYCLES number of values, from 0 to CYCLES
DrawingWeights = [] # an array with CYCLES number of values, each one is a weight for the respective cycle
DrawnCycles = [] # an array the size of NumberOfInfectionCycles
# Max particles per cycle
MaxParticles = 1000000
DeleteriousProbability = [0] * Cycles
BeneficialProbability = [0] * Cycles
# if TRUE, beneficial probability will increase by INCREMENT each cycle
# if FALSE, it will change from a fixed value to another fixed value, at the chosen cycle
BeneficialIncrement = False
FirstBeneficial = 0.0003
SecondBeneficial = 0.0008
# if TRUE, deleterious probability will increase by INCREMENT each cycle
# if FALSE, it will change from a fixed value to another fixed value, at the chosen cycle
DeleteriousIncrement = False
FirstDeleterious = 0.3
SecondDeleterious = 0.8
ChangeCycle = 8
# Maximum R Class that a patient has at cycle 0
# it is also the maximum R Class of received infection
MaxR = 0
# Lists to keep the number of particles that go up or down the classes, during mutations
# So, for example, the list ClassUpParticle[0][1, 4] will keep the number of particles
# that went up 1 class, in GENERATION 0, PATIENT 1, CYCLE 4
ClassUpParticles = []
ClassDownParticles = []
#OutputFile = open('Testfile.txt', 'w')
MaxWorksheetSize = 1000000 # Max number of lines per worksheet
ExcelFileName = "TFounderSim" + datetime.now().strftime('%d-%m-%Y_%H-%M-%S') + '.xlsx'
workbook = xlsxwriter.Workbook(ExcelFileName, {'constant_memory': True})
#workbook = xlsxwriter.Workbook(ExcelFileName)
worksheet = workbook.add_worksheet()
HorizAlign = workbook.add_format()
HorizAlign.set_align('center')
bold = workbook.add_format({'bold': True})
LastRowAvailable = 0
# set_column(column1, column2, size)
worksheet.set_column(0, 0, 20)
worksheet.set_column(2, 2, 8)
worksheet.set_column(14, 14, 12)
worksheet.set_column(15, 15, 10)
worksheet.set_column(16, 16, 13)
worksheet.set_column(17, 17, 13)
worksheet.set_column(18, 18, 16)
worksheet.write(LastRowAvailable, 0, "Generations", bold)
worksheet.write(LastRowAvailable, 1, Generations)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Gen1Patients", bold)
worksheet.write(LastRowAvailable, 1, Gen1Patients)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "InfectionCycle", bold)
worksheet.write(LastRowAvailable, 1, str(InfectionCycle))
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Cycles", bold)
worksheet.write(LastRowAvailable, 1, Cycles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "InitialParticles", bold)
worksheet.write(LastRowAvailable, 1, InitialParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "ClassOfInitialParticles", bold)
worksheet.write(LastRowAvailable, 1, ClassOfInitialParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "InfectionParticles", bold)
worksheet.write(LastRowAvailable, 1, InfectionParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "MaxParticles", bold)
worksheet.write(LastRowAvailable, 1, MaxParticles)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "First Beneficial", bold)
worksheet.write(LastRowAvailable, 1, FirstBeneficial)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Second Beneficial", bold)
worksheet.write(LastRowAvailable, 1, SecondBeneficial)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "First Deleterious", bold)
worksheet.write(LastRowAvailable, 1, FirstDeleterious)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Second Deleterious", bold)
worksheet.write(LastRowAvailable, 1, SecondDeleterious)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Change Cycle", bold)
worksheet.write(LastRowAvailable, 1, ChangeCycle)
LastRowAvailable += 1
def main():
global LastRowAvailable, LastPatient, worksheet, HorizAlign
print("\nMain function started: " + str(datetime.now()) + "\n")
startTime = datetime.now()
IdentifyMachine()
# number of patients at 1st generation is defined by the number of cycles that
# occur infection
#Gen1Patients = InfectionCycle.GetLength(0)
# Declaring the three-dimensional Matrix:
# it has p Patients, Cy lines of Cycles,
# defined by the variables at the begginning of the code.
worksheet = workbook.add_worksheet()
HorizAlign = workbook.add_format()
HorizAlign.set_align('center')
bold = workbook.add_format({'bold': True})
LastRowAvailable = 0
LastPatient = -1
# set_column(column1, column2, size)
worksheet.set_column(0, 0, 20)
worksheet.set_column(2, 2, 8)
worksheet.set_column(14, 14, 12)
worksheet.set_column(15, 15, 10)
worksheet.set_column(16, 16, 13)
worksheet.set_column(17, 17, 13)
worksheet.set_column(18, 18, 16)
for g in range(Generations):
Matrix.append([])
ClassUpParticles.append([])
ClassDownParticles.append([])
PatientsPerGen = pow(Gen1Patients, g)
# in the FOR LOOP below, we append 1 array for each patient.
# and 1 array for each cycle.
# we only append cycle here (Cycle 0) because the cycles will be maked at the time
# each progeny is composed
for patients in range(PatientsPerGen):
Matrix[g].append([]) # patient
Matrix[g][patients].append([]) # cycle
ClassUpParticles[g].append([]) # patient
ClassUpParticles[g][patients].append([]) # cycle
ClassDownParticles[g].append([]) # patient
ClassDownParticles[g][patients].append([]) # cycle
#FillInfectionCycleArray(6, 0); // FIRST PARAMETER: initial cycle, SECOND PARAMENTER: increment
if DeleteriousIncrement == True:
FillDeleteriousArrayWithIncrement(FirstDeleterious, 0.1)
# FIRST PARAMETER: initial probability
# SECOND PARAMENTER: increment
else:
FillDeleteriousArray(FirstDeleterious, SecondDeleterious, ChangeCycle)
# FIRST PARAMETER: first probability
# SECOND PARAMENTER: second probability
# THIRD PARAMETER: cycle to change from first probability to second probability
if BeneficialIncrement == True:
FillBeneficialArrayWithIncrement(FirstBeneficial, 0.1)
# FIRST PARAMETER: initial probability
# SECOND PARAMENTER: increment
else:
FillBeneficialArray(FirstBeneficial, SecondBeneficial, ChangeCycle)
# FIRST PARAMETER: first probability
# SECOND PARAMENTER: second probability
# THIRD PARAMETER: cycle to change from first probability to second probability
# The Matrix starts on the Patient 0, 10th position (column) on the line zero.
# The "InitialParticles" is the amount of viral particles that exists in the class 10 on the cycle zero.
# That is: these 5 particles have the potential to create 10 particles each.
for i in range(InitialParticles):
Matrix[0][0][0].append(ClassOfInitialParticles)
# print(Matrix[0][0][0][0])
#
# for i in range(InitialParticles):
# print(Matrix[0][0][0][i].id)
RunSimulation()
print("\nMain function ended: " + str(datetime.now()) + "\n")
print("Total run time: " + str(datetime.now() - startTime) + "\n")
print("Date: " + str(datetime.now()) + "\n")
print("Python Implementation: " + platform.python_implementation())
# OutputFile.write("Total run time: " + str(datetime.now() - startTime) + "\n")
# OutputFile.write("Date: " + str(datetime.now()) + "\n")
# OutputFile.close()
# worksheet.write(Row, Column, String, format)
LastRowAvailable += 2
worksheet.write(LastRowAvailable, 0, "Total run time: " + str(datetime.now() - startTime), bold)
worksheet.write(LastRowAvailable + 1, 0, "Date: " + str(datetime.now()), bold)
workbook.close()
def FillDeleteriousArray(FirstProbability, SecondProbability, ChangeCycle):
for i in range(Cycles):
if i <= ChangeCycle:
DeleteriousProbability[i] = FirstProbability
else:
DeleteriousProbability[i] = SecondProbability
def FillDeleteriousArrayWithIncrement(InitialProbability, Increment):
for i in range(Cycles):
if i == 0:
DeleteriousProbability[i] = InitialProbability
else:
if (DeleteriousProbability[i - 1] + Increment <= (1 - BeneficialProbability.GetLength(0))):
DeleteriousProbability[i] = DeleteriousProbability[i - 1] + Increment
else:
DeleteriousProbability[i] = DeleteriousProbability[i - 1]
def FillBeneficialArray(FirstProbability, SecondProbability, ChangeCycle):
for i in range(Cycles):
if i <= ChangeCycle:
BeneficialProbability[i] = FirstProbability
else:
BeneficialProbability[i] = SecondProbability
def FillBeneficialArrayWithIncrement(InitialProbability, Increment):
for i in range(Cycles):
if i == 0:
BeneficialProbability[i] = InitialProbability
else:
if (BeneficialProbability[i - 1] + Increment <= (1 - DeleteriousProbability.GetLength(0))):
BeneficialProbability[i] = BeneficialProbability[i - 1] + Increment
else:
BeneficialProbability[i] = BeneficialProbability[i - 1]
def RunSimulation():
global LastPatient, workbook, worksheet, HorizAlign, ExcelFileName, LastRowAvailable, MaxR
# Populates the CyclesForDrawing array with number of cycles
for i in range(Cycles):
CyclesForDrawing.append(i)
# pool = multiprocessing.Pool(multiprocessing.cpu_count())
# print("RunSimulation function started: " + str(datetime.now()) + "\n")
# Main Loop to create more particles on the next Cycles from the Cycle Zero.
# Each matrix position will bring a value. This value will be mutiplied by its own class number.
for g in range(Generations):
# if g > 8:
# # writes excel file to disk and creates another one
# # to avoid too large files
# workbook.close()
#
# if g == 9:
# # remove ".xlsx" from the string,
# # in the first time we a create another file
# ExcelFileName = ExcelFileName[:-5]
#
# else:
# # remove "_Gx.xlsx" from the string
# ExcelFileName = ExcelFileName[:-8]
#
# ExcelFileName += "_G" + str(g) + ".xlsx"
#
# workbook = xlsxwriter.Workbook(ExcelFileName, {'constant_memory': True})
# worksheet = workbook.add_worksheet()
#
# HorizAlign = workbook.add_format()
# HorizAlign.set_align('center')
#
# worksheet.set_column(0, 0, 20)
# worksheet.set_column(14, 14, 12)
# worksheet.set_column(15, 15, 10)
# worksheet.set_column(16, 16, 13)
# worksheet.set_column(17, 17, 13)
# worksheet.set_column(18, 18, 16)
#
# LastRowAvailable = 0
for p in range(pow(Gen1Patients, g)): # pow(Gen1Patients, g) gives the generation size
print("Patient started: GEN " + str(g) + " - P " + str(p))
# OutputFile.write("Patient started: GEN " + str(g) + " - P " + str(p) + "\n")
# worksheet.write(LastRowAvailable + 1, 0, "Patient:")
worksheet.write(LastRowAvailable + 1, 1, "Generation: ")
worksheet.write(LastRowAvailable + 1, 2, str(g))
worksheet.write(LastRowAvailable + 1, 3, "Patient: ")
worksheet.write(LastRowAvailable + 1, 4, str(p))
LastRowAvailable += 1
RunPatient(g, p)
Matrix[g][p].clear()
LastPatient = 0
DrawingWeights.clear()
InfectionWarnings.clear()
InfectionWarningsCycle.clear()
MaxR = 0
if LastRowAvailable >= MaxWorksheetSize or NewWorksheetEachPatient:
worksheet = workbook.add_worksheet()
worksheet.set_column(0, 0, 20)
worksheet.set_column(14, 14, 12)
worksheet.set_column(15, 15, 10)
worksheet.set_column(16, 16, 13)
worksheet.set_column(17, 17, 13)
worksheet.set_column(18, 18, 16)
LastRowAvailable = 0
LastPatient = -1
# pool.map(RunPatient, [(g, 0), (g, 1), (g, 2), (g, 3)])
def RunPatient(g, p):
global LastRowAvailable, InfectionCycle
if InfectionUserDefined:
for i in range(1, NumberOfInfectionCycles + 1):
InfectionCycle[i] = UserDefindedCycleForInfection
else:
for i in range(Cycles):
# Populates the DrawingWeights array
if i <= DrawIntervalsKeys[0]:
DrawingWeights.append(DrawIntervals[4])
elif i > DrawIntervalsKeys[0] and i <= DrawIntervalsKeys[1]:
DrawingWeights.append(DrawIntervals[13])
elif i > DrawIntervalsKeys[1] and i <= DrawIntervalsKeys[2]:
DrawingWeights.append(DrawIntervals[24])
else:
DrawingWeights.append(DrawIntervals[42])
# print(DrawingWeights)
DrawnCycles = random.choices(CyclesForDrawing, DrawingWeights, k = NumberOfInfectionCycles)
for i in range(1, NumberOfInfectionCycles + 1):
InfectionCycle[i] = DrawnCycles[i - 1]
# print(InfectionCycle)
for Cy in range(Cycles):
# print(Cy)
if(Cy > 0):
Matrix[g][p].append([]) # adds 1 cycle
ClassUpParticles[g][p].append([]) # adds 1 cycle
ClassDownParticles[g][p].append([]) # adds 1 cycle
for particle in Matrix[g][p][Cy - 1]: # takes 1 particle from previous cycle
for i in range(particle): # creates N new particles, based on the R class
Matrix[g][p][Cy].append(particle)
CutOffMaxParticlesPerCycle(g, p, Cy)
ApplyMutationsProbabilities(g, p, Cy)
#print("Cycle " + str(Cy) + " " + str(Matrix[g][p, Cy]))
for cycle in InfectionCycle:
# IF the current cycle (Cy) is contained inside the INFECTIONCYCLE dictionary
# AND it is not the last generation, make infection
# Cy == InfectionCycle[cycle] is comparing the current the cycle with
# the value, not the key
if Cy == InfectionCycle[cycle] and g < (Generations - 1):
# here we are passing cycle as the key, not the value
PickRandomParticlesForInfection(g, p, Cy, cycle)
SaveData(g, p, Cy)
if Cy > 0:
Matrix[g][p][Cy - 1].clear()
#print which Cycle was finished just to give user feedback, because it may take too long to run.
#print("Cycles processed: " + str(Cy));
#print("Patients processed: GEN " + str(g) + " - P " + str(p));
# memory()
def CutOffMaxParticlesPerCycle(g, p, Cy):
if(len(Matrix[g][p][Cy]) > MaxParticles):
rndParticles = random.sample(Matrix[g][p][Cy], MaxParticles)
Matrix[g][p][Cy] = rndParticles
def ApplyMutationsProbabilities(g, p, Cy):
# This function will apply three probabilities: Deleterious, Beneficial or Neutral.
# Their roles is to simulate real mutations of virus genome.
# So here, there are mutational probabilities, which will bring an
# stochastic scenario sorting the progenies by the classes.
UpParticles = 0
DownParticles = 0
i = 0
if(Cy > 0):
while i < len(Matrix[g][p][Cy]):
# In this loop, for each particle a random number is selected.
# Here a random (float) number greater than zero and less than one is selected.
RandomNumber = random.random()
# If the random number is less than the DeleteriousProbability
# defined, one particle of the previous Cycle will
# decrease one Class number. Remember this function is
# inside a loop for each Cy and each Cl values.
# So this loop will run through the whole Matrix,
# particle by particle on its own positions.
if RandomNumber < DeleteriousProbability[Cy]:
# Deleterious Mutation = 90,0% probability (0.9)
if Matrix[g][p][Cy][i] > 0:
Matrix[g][p][Cy][i] -= 1
else:
Matrix[g][p][Cy][i].pop(i)
DownParticles += 1
elif (RandomNumber < (DeleteriousProbability[Cy] + BeneficialProbability[Cy])):
# Beneficial Mutation = 0,5% probability (0.005)
if Matrix[g][p][Cy][i] < 10:
Matrix[g][p][Cy][i] += 1
UpParticles += 1
i += 1
ClassUpParticles[g][p][Cy] = UpParticles
ClassDownParticles[g][p][Cy] = DownParticles
def PickRandomParticlesForInfection(g, p, Cy, cycleForInfection):
NoParticlesForInfection = False
ParticlesInThisCycle = len(Matrix[g][p][Cy])
# TODO remove selected infection particles from the Matrix, or
# copy the same particle, to keep the id
if (ParticlesInThisCycle > 0):
if(ParticlesInThisCycle >= InfectionParticles):
InfectedParticles = random.sample(Matrix[g][p][Cy], InfectionParticles)
else:
InfectedParticles = random.sample(Matrix[g][p][Cy], ParticlesInThisCycle)
else:
NoParticlesForInfection = True
# if there are no particles for infection, there is no infection
if (NoParticlesForInfection):
print("Patient " + str(p) + " Cycle " + str(Cy) + " has no particles.")
# OutputFile.write("Patient " + str(p) + " Cycle " + str(Cy) + " has no particles.")
text = "G" + str(g) + " " + "P" + str(p) + " Cycle " + str(Cy) + " has no particles."
InfectionWarnings.append(text)
InfectionWarningsCycle.append(None)
else:
InfectPatients(InfectedParticles, g, p, Cy,cycleForInfection)
def InfectPatients(InfectedParticles, g, p, Cy, cycleForInfection):
global LastRowAvailable
PatientsToInfect = [0] * Gen1Patients
# each patient will infect a group of patients of size Gen1Patients
LastPatient = ((p + 1) * Gen1Patients) - 1; # the last patient of this group
FirstPatient = LastPatient - (Gen1Patients - 1); # the first patient of this group
for x in range(Gen1Patients):
PatientsToInfect[x] = FirstPatient + x
#print(PatientsToInfect[x]);
#print(FirstPatient);
#print(LastPatient);
# Example: if INFECTIONCYCLE is {1: 8, 2: 4, 3: 6, 4: 2}
# and cycleForInfection is 3 (3 is the key, not the value),
# patient = PatientsToInfect[3 - 1] = PatientsToInfect[2]
patient = PatientsToInfect[cycleForInfection - 1]
for particle in InfectedParticles:
# creates 1 new particle, on a patient in the next generation
# in cycle 0. The new particle will be of the same class of the
# one that infected the patient
Matrix[g + 1][patient][0].append(particle)
print("G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy))
# OutputFile.write("G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy) + "\n")
text = "G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy)
InfectionWarnings.append(text)
InfectionWarningsCycle.append(Cy)
# worksheet.write(LastRowAvailable, 0, "G " + str(g) + " P " + str(p) + " infected G " + str(g + 1) + " P " + str(patient) + " at cycle " + str(Cy))
# LastRowAvailable += 1
def SaveData(g, p, Cy):
global LastRowAvailable, LastPatient, MaxR
Mi = 0
PercentageOfParticlesUp = 0.0
PercentageOfParticlesDown = 0.0
LastRowAvailable += 1
if LastPatient != p:
for R in range(Classes):
# fill a line in the Excel file with R0, R1, R2 .... R10
worksheet.write(LastRowAvailable, R + 1, "R" + str(R), HorizAlign)
worksheet.write(LastRowAvailable, 0, "Cycle", HorizAlign)
worksheet.write(LastRowAvailable, 12, "Cycle Particles", HorizAlign)
worksheet.write(LastRowAvailable, 13, "Mi", HorizAlign)
worksheet.write(LastRowAvailable, 14, "Particles Up", HorizAlign)
worksheet.write(LastRowAvailable, 15, "Particles Up - %", HorizAlign)
worksheet.write(LastRowAvailable, 16, "Particles Down", HorizAlign)
worksheet.write(LastRowAvailable, 17, "Particles Down - %", HorizAlign)
LastRowAvailable += 1
ClassCount = [0] * (Classes + 1) # We want ClassCount to be an array of 11 positions, from 0 to 10, not 0 to 9
for particle in Matrix[g][p][Cy]:
try:
ClassCount[particle] += 1
except:
print("Error: " + str(particle))
if(len(Matrix[g][p][Cy]) > 0):
PercentageOfParticlesUp = (ClassUpParticles[g][p][Cy] / len(Matrix[g][p][Cy]))
PercentageOfParticlesDown = (ClassDownParticles[g][p][Cy] / len(Matrix[g][p][Cy]))
else:
PercentageOfParticlesUp = 0.0
PercentageOfParticlesDown = 0.0
if(Cy == 0):
if(len(Matrix[g][p][Cy]) > 0):
MaxR = GetMaxR(ClassCount)
if (len(Matrix[g][p][Cy]) == 0):
MaxR = 999
# MaxR = str(GetMaxR(ClassCount)).replace(str(0), str(numpy.NaN))
for R in range(Classes):
# fill a line in the Excel file with number of particles from R0, R1, R2 .... R10
worksheet.write(LastRowAvailable, R + 1, ClassCount[R], HorizAlign)
worksheet.write(LastRowAvailable, 0, Cy, HorizAlign)
worksheet.write(LastRowAvailable, 12, len(Matrix[g][p][Cy]), HorizAlign)
Mi = GetMi(ClassCount, len(Matrix[g][p][Cy]))
worksheet.write(LastRowAvailable, 13, Mi, HorizAlign)
worksheet.write(LastRowAvailable, 14, ClassUpParticles[g][p][Cy], HorizAlign)
worksheet.write(LastRowAvailable, 15, PercentageOfParticlesUp, HorizAlign)
worksheet.write(LastRowAvailable, 16, ClassDownParticles[g][p][Cy], HorizAlign)
worksheet.write(LastRowAvailable, 17, PercentageOfParticlesDown, HorizAlign)
# LastRowAvailable += 1
if Cy == Cycles - 1:
LastRowAvailable += 2
worksheet.write(LastRowAvailable, 0, "Max R at Cycle 0")
worksheet.write(LastRowAvailable, 1, MaxR, HorizAlign)
LastRowAvailable += 1
for i in range(len(InfectionWarnings)):
worksheet.write(LastRowAvailable, 0, InfectionWarnings[i])
worksheet.write(LastRowAvailable, 2, InfectionWarningsCycle[i])
LastRowAvailable += 1
LastPatient = p
def GetMi(ClassCount, CycleParticles):
# ClassCount = number of particles per cycle, in a 11 position array
MaxPotentialParticles = 0
for R in range(Classes):
MaxPotentialParticles += ClassCount[R] * R
if CycleParticles != 0:
Mi = MaxPotentialParticles/CycleParticles
else:
Mi = 0
return Mi
def GetMaxR(ClassCount):
# ClassCount = number of particles per cycle, in a 11 position array
MaxR = 0
for R in range(Classes):
if ClassCount[R] > 0:
MaxR = R
return MaxR
def memory():
import os
import psutil
process = psutil.Process(os.getpid())
print("Memory used: " + str((process.memory_info().rss)/1048576) + " MB") # in Megabytes
def IdentifyMachine():
global LastRowAvailable
worksheet.write(LastRowAvailable, 0, "Python Implementation", bold)
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, platform.python_implementation(), bold)
LastRowAvailable += 1
try:
import cpuinfo
print("CPU: " + cpuinfo.cpu.info[0]['ProcessorNameString'])
worksheet.write(LastRowAvailable, 0, "CPU: " + cpuinfo.cpu.info[0]['ProcessorNameString'])
LastRowAvailable += 1
except:
print("No cpuinfo.py module. Download it at https://github.com/pydata/numexpr/blob/master/numexpr/cpuinfo.py")
worksheet.write(LastRowAvailable, 0, "No cpuinfo.py module. Download it at https://github.com/pydata/numexpr/blob/master/numexpr/cpuinfo.py")
LastRowAvailable += 1
print("Processor: " + platform.processor())
print("Architecture (32 or 64 bits): " + platform.machine())
print("OS: " + platform.platform())
worksheet.write(LastRowAvailable, 0, "Processor: " + platform.processor())
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "Architecture (32 or 64 bits): " + platform.machine())
LastRowAvailable += 1
worksheet.write(LastRowAvailable, 0, "OS: " + platform.platform() + "\n")
LastRowAvailable += 1
main()
# TODO fazer gráficos com frequência relativa: porcentagem de partículas em cada classe
# TODO gerar gráfico boxplot com R Max (Fig.14 pré-dissertação).
# TODO Colocar opção de infectar paciente sempre com partículas das classes mais altas.
# TODO fazer um resumo de dados informando qual foi o paciente máximo com partículas virais dentro dele e qual o total de pacientes popssíveis.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // used to create an output file (.txt)
using System.Diagnostics; // used for the Stopwatch Class
using System.Threading; // used for the Stopwatch Class
// TODO aumentar poder dos valores = números maiores (double por exemplo - maior e mais preciso).
// TODO limite de partículas por ciclo
// TODO fazer mutação benéfica e neutra com probabilidade fixa
// TODO fazer mutações com probabilidades aleatórias
// TODO *** avaliar quando encerrar um paciente e passar para o próximo (média das classes for constante)
// TODO fazer mais de um paciente
// TODO fazer simulação definindo em quais ciclos ocorrem infecções e deixar pacientes inicais rodando
// TODO interface gráfica (gráficos em tempo real, novas janelas para cada paciente etc)
// TODO: A INTRO explanation about this program, the main use, the aim, how it works, the output and what to do with.
namespace multi_dimensional_array
{
public class Program
{
// Definition of Cycle
public const int Cycle = 10;
// Definition of Class
public const int Class = 11;
// Definition of Patient
public const int Patient = 0;
// The "InitialParticles" is the initial amount of viral particles, that is: the initial virus population of a infection.
public const int InitialParticles = 5;
static void Main(string[] args)
{
Random rnd = new Random();
// create and start the Stopwatch Class. From: https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// Declaring the two-dimensional Matrix: it has x lines of Cycles and y columns of Classes, defined by the variables above.
int[,] Matrix = new int[Cycle, Class];
//int[,] TempMatrix = new int[Cycle, Class];
// The Matrix starts on the 10th position (column) on the line zero.
// The "InitialParticles" is the amount of viral particles that exists in the class 10 on the cycle zero.
// That is: these 5 particles have the potential to create 10 particles each.
Matrix[0, 10] = InitialParticles;
// TODO put the for loop below inside a function lik POPULATEMATRIX,
// because the main function is getting too big adaing
// Main Loop to create more particles on the next Cycles from the Cycle Zero (lines values).
// Each matrix position will bring a value. This value will be mutiplied by its own class number (column value).
int original, novas;
for (int i = 0; i < Cycle; i++)
{
for (int j = 0; j < Class; j++)
{
if (i > 0)
{
// Multiplies the number os particles from de previous Cycle by the Class number which belongs.
// This is the progeny composition.
Matrix[i, j] = Matrix[(i - 1), j] * j;
//Matrix[i, j] = TempMatrix[i, j];
//Matrix[i, j] = 0;
}
}
CutOffMaxParticlesPerCicle(Matrix, i, rnd);
novas = 0;
original = Matrix[i, 0];
for (int j = 0; j < Class; j++)
{
Matrix[i, j] = original;
if(j + 1 < Class) original = Matrix[i, j + 1];
ApplyMutationsProbabilities(Matrix, i, j, rnd);
Matrix[i, j] += novas;
if (j + 1 < Class)
novas = Matrix[i, j + 1] - original;
}
// print which Cycle was finished just to give a user feedback, because it was taking too long to run.
Console.WriteLine("Cycles processed: {0}", i);
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
PrintOutput(Matrix);
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("Total Run Time: " + elapsedTime);
Console.Write("\n");
}
static void ApplyMutationsProbabilities(int[,] Matrix, int i, int j, Random rnd)
{
// This function will apply three probabilities: Deleterious, Beneficial or Neutral.
// Their roles is to simulate real mutations of virus genome.
// So here, there are mutational probabilities, which will bring an stochastic scenario sorting the progenies by the classes.
// Here a random number greater than zero and less than one is selected.
double RandomNumber;
//RandomNumber = rnd.NextDouble();
//RandomNumber = 0.2;
// mutação deletéria = 90,0% de probabilidade (0,9)
// mutação benéfica = 0,5% de probabilidade (0,005)
// mutação neutra = 9,5% de probabilidade (0,095)
// para efeitos de sorteio, qualquer número entre 0 e 0,9 será mutação deletéria
// qualquer número acima de 0,995 será mutação benéfica.
// Ou seja, o número sorteado precisa estar em um pequeno intervalo de 0,005 só que colocamos este intervalo na
// parte superior do intervalo entre 0 e 1 e qualquer número entre 0,9 e 0,995 será mutação neutra.
// Não precisamos definir a mutação neutra, pois no código de comparação, o número sorteado deverá ser maior que 0,9 (deletéria)
// e menor que 0,995 (benéfica)
// Here the probabilities numbers for each mutation is defined.
double DeleteriousProbability = 0.9;
double BeneficialProbability = 0.005; // ou 1 - 0.005
if (Matrix[i, j] > 0)
{
for (int x = Matrix[i, j]; x > 0; x--)
{
// In this loop, for each particle removed from the Matrix [i,j], a random number is selected.
RandomNumber = rnd.NextDouble();
// If the random number is less than the DeleteriousProbability defined, one particle of the previous Cycle will
// decrease one Class number. Remember this function is inside a loop for each i and each j values.
// So this loop will run through the whole Matrix, particle by particle on its own positions.
if (RandomNumber < DeleteriousProbability)
// Deleterious Mutation = 90,0% probability (0.9)
{
if (i > 0)
{
//Matrix[(i - 1), j]++;
//TempMatrix[i, j]--;
Matrix[i, (j - 1)]++;
Matrix[i, j]--;
}
}
else if (RandomNumber < BeneficialProbability + DeleteriousProbability)
// Beneficial Mutation = 0,5% probability (0.005)
{
if (i > 0)
{
if (j < (Class - 1))
{
Matrix[i, (j + 1)]++;
Matrix[i, j]--;
}
}
}
}
}
// PSEUDOCODIGO (para melhor compreensão no desenvolvimento):
// se a classe R tiver partículas
// Para cada partícula da classe R, Ciclo n
// Pensar numa régua de 0 a 1 (O número sorteado é de 0 a 1):
// |____|____|____|____|____|____|____|____|____|____|
// 0 0.1 0.5 0.8 0.9 1
// MUTAÇÃO DELETÉRIA
// Se o valor sorteado for menor que a probabilidade da mutação deletéria (valor sorteado menor ou igual a 0,8)
// número de partículas da classe R recebe 1 partícula
// número de partículas da classe (R + 1) perde uma partícula
// MUTAÇÂO NEUTRA
// Se o valor sorteado for maior do que a mutação deletéria, mas menor do que a mutação neutra, ou seja,
// se o valor sorteado for maior do que 0.9 e menor do que 0.95
// as partículas não se alteram.
// MUTAÇÃO BENÉFICA
// Se o valor sorteado for maior ou igual à probalidade da mutação neutra (valor sorteado maior ou igual à 0.95)
// número de partículas da classe R perde 1 partícula
// número de partículas da classe (R + 1) recebe uma partícula
}
static int ParticlesInCycle(int[,] Matrix, int i)
{
// This funtion brings the sum value of particles by Cycle.
int Particles = 0;
for (int j = 0; j < Class; j++)
{
Particles = Particles + Matrix[i, j];
}
return Particles;
}
// PSEUDOCODIGO PARA SORTEIO E SELEÇÃO DE PARTÍCULAS PARA REDUÇÃO EM MAXPARTICLES POR CICLO (MÉTODO DIOGO)
// Para cada ciclo: enquanto SOMALINHA > MAXPARTICLES
// Sorteio de número (Sorteado) < SomaLinha
// Sorteado é menor do que a quantidade de partículas em R0?
// Se sim, tira uma partícula de R0; faz novo sorteio e recomeça o loop;
// Se não, faz Sorteado menos a quantidade de partículas em R0, este é Sort1.
// Sort1 é menor do que a quantidade de partículas em R1?
// Se sim, tira uma partícula de R1; faz novo sorteio e recomeça o loop até cumprir com a condição;
// Se não, faz Sort1 menos a quantidade de partículas em R2, este é Sort2.
// Assim até quando necessário.
// PSEUDOCODIGO PARA SORTEIO E SELEÇÃO DE PARTÍCULAS PARA REDUÇÃO EM MAXPARTICLES POR CICLO (MÉTODO MARCOS) = É o que será usado!!!
// Faz um arrray (lista) ordenando as quantidades de partículas da seguinte forma (em um mesmo ciclo):
// Array [0] = classe zero = quantidade de partículas na classe zero, ou seja, R0
// Array [1] = quantidade de partículas em R0 + quantidade de partículas em R1;
// Array [2] = quantidade de partículas em R0 + quantidade de partículas em R1 + quantidade de particulas em R2;
// E assim por diante. Dessa forma, cada posição deste array poderá ter um valor máximo.
// Para cada ciclo: enquanto SOMALINHA > MAXPARTICLES
// Sorteio de número (Sorteado) < SomaLinha
// Se o número sorteado for (0 < Sorteado <= Array[0]),
// Matriz [Ciclo, 0] perderá uma partícula.
// Assim vai até a SomaLinha chegar no MaxParticles determinado.
static void CutOffMaxParticlesPerCicle(int[,] Matrix, int i, Random rndx)
{
int MaxParticles = 1000000; // Limite máximo de partículas que quero impor para cada ciclo (linha)
int ParticlesInThisCycle = ParticlesInCycle(Matrix, i); // Quantidade de partículas somadas por ciclo (linha)
int[] StatusR = new int[Class]; // Declarando o array que é a lista abaixo
// Se, x = ParticlesInCycle, for maior do que o núm MaxParticles definido, então...
if (ParticlesInThisCycle > MaxParticles)
{
// Para cada valor de x iniciando no valor de soma das partículas por ciclo;
// sendo x, ou seja, esta soma, maior do que o limite MaxParticles definido;
// então, diminua em uma unidade a soma das partículas por ciclo até que atinja o limite MaxParticles definido.
for (int Particles = ParticlesInCycle(Matrix, i); Particles > MaxParticles; Particles--)
// PARTICLES is equal to PARTICLESINTHISCYCLE, but we don't want to modifify PARTICLESINTHISCYCLE while the for loop is running
// also, PARTICLESINTHISCYCLE was created outside the for loop, for other purpose
{
StatusR[0] = Matrix[i, 0];
StatusR[1] = Matrix[i, 0] + Matrix[i, 1];
StatusR[2] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2];
StatusR[3] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3];
StatusR[4] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3] + Matrix[i, 4];
StatusR[5] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3] + Matrix[i, 4] + Matrix[i, 5];
StatusR[6] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3] + Matrix[i, 4] + Matrix[i, 5] + Matrix[i, 6];
StatusR[7] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3] + Matrix[i, 4] + Matrix[i, 5] + Matrix[i, 6] + Matrix[i, 7];
StatusR[8] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3] + Matrix[i, 4] + Matrix[i, 5] + Matrix[i, 6] + Matrix[i, 7] + Matrix[i, 8];
StatusR[9] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3] + Matrix[i, 4] + Matrix[i, 5] + Matrix[i, 6] + Matrix[i, 7] + Matrix[i, 8] + Matrix[i, 9];
StatusR[10] = Matrix[i, 0] + Matrix[i, 1] + Matrix[i, 2] + Matrix[i, 3] + Matrix[i, 4] + Matrix[i, 5] + Matrix[i, 6] + Matrix[i, 7] + Matrix[i, 8] + Matrix[i, 9] + Matrix[i, 10];
// Gero um número aleatório de 0 ao limite do valor de soma de partículas por ciclo (linha) = ParticlesInCycle
// int RandomMaxParticles;
int rndParticle = rndx.Next(1, ParticlesInCycle(Matrix, i));
// Aqui gero as condições para saber de qual classe serão retiradas as partículas para que
// ParticlesInCycle atinja o limite estipulado por MaxParticles
if (rndParticle > 0 && rndParticle <= StatusR[0])
{
Matrix[i, 0] = Matrix[i, 0] - 1;
}
if (rndParticle > StatusR[0] && rndParticle <= StatusR[1])
{
Matrix[i, 1] = Matrix[i, 1] - 1;
}
if (rndParticle > StatusR[1] && rndParticle <= StatusR[2])
{
Matrix[i, 2] = Matrix[i, 2] - 1;
}
if (rndParticle > StatusR[2] && rndParticle <= StatusR[3])
{
Matrix[i, 3] = Matrix[i, 3] - 1;
}
if (rndParticle > StatusR[3] && rndParticle <= StatusR[4])
{
Matrix[i, 4] = Matrix[i, 4] - 1;
}
if (rndParticle > StatusR[4] && rndParticle <= StatusR[5])
{
Matrix[i, 5] = Matrix[i, 5] - 1;
}
if (rndParticle > StatusR[5] && rndParticle <= StatusR[6])
{
Matrix[i, 6] = Matrix[i, 6] - 1;
}
if (rndParticle > StatusR[6] && rndParticle <= StatusR[7])
{
Matrix[i, 7] = Matrix[i, 7] - 1;
}
if (rndParticle > StatusR[7] && rndParticle <= StatusR[8])
{
Matrix[i, 8] = Matrix[i, 8] - 1;
}
if (rndParticle > StatusR[8] && rndParticle <= StatusR[9])
{
Matrix[i, 9] = Matrix[i, 9] - 1;
}
if (rndParticle > StatusR[9] && rndParticle <= StatusR[10])
{
Matrix[i, 10] = Matrix[i, 10] - 1;
}
}
}
}
static void PrintOutput(int[,] Matrix)
{
StreamWriter writer = new StreamWriter("numbers.txt");
// The writer will bring the output file (txt in this case)
// Ensure the writer will be closed when no longer used
using (writer)
{
// Formatting Output for the Console screen.
Console.WriteLine("");
Console.Write("\t\t\tR0\tR1\tR2\tR3\tR4\tR5\tR6\tR7\tR8\tR9\t\tR10\n\n");
writer.Write("\t\tSoma\tR0\tR1\tR2\tR3\tR4\tR5\tR6\tR7\tR8\t\tR9\t\tR10\n\n");
writer.WriteLine("\n");
// Outer loop for accessing rows
for (int i = 0; i < Cycle; i++)
{
Console.Write("Pac.{0} Cic.{1}\t\t", Patient, i);
writer.Write("Pac.{0} Cic.{1} {2}\t\t", Patient, i, ParticlesInCycle(Matrix, i));
// Inner or nested loop for accessing column of each row
for (int j = 0; j < Class; j++)
{
Console.Write("{0}\t", Matrix[i, j]);
writer.Write("{0}\t", Matrix[i, j]);
}
Console.WriteLine("\nSoma do ciclo {0}: {1}", i, ParticlesInCycle(Matrix, i));
Console.Write("\n");
writer.WriteLine("\n");
}
Console.ReadLine();
}
}
}
}
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Jan 8 23:42:45 2019
@author: Marcos
"""
class Particle():
__slots__ = ('R')
def __init__(self, RClass):
self.R = RClass # R Class from R0 to R10. self.Class is an INT
# self.id = ID
# self.id = Particle.ParticleIdCounter
def RaiseClass(self):
if(self.R < 10):
self.R = self.R + 1
def DemoteClass(self):
if(self.R == 0):
self.__del__()
else:
self.R = self.R - 1
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Feb 3 19:49:55 2019
@author: <NAME>
"""
import matplotlib.pyplot as plt
import random
import ParticleClass
from datetime import datetime
startTime = datetime.now()
print("\n")
ParticleArray = []
for i in range(100):
ParticleArray.append(ParticleClass.Particle(10))
RandomTime = datetime.now()
rndParticles = random.sample(ParticleArray, 90)
#for i in rndParticles:
# print(i.id)
ParticleArray.clear()
ParticleArray = rndParticles
#print("\n")
#print("Particle Array after sorting")
#
#for i in ParticleArray:
# print(i.id)
print("\n")
print("Particle Array size: " + str(len(ParticleArray)))
print("Particle Amount: " + str(ParticleArray[0].ParticleAmount))
print("x[2] id: " + str(ParticleArray[0].id))
print("x[2] Rclass: " + str(ParticleArray[0].R))
ParticleArray[0].RaiseClass()
ParticleArray[0].DemoteClass()
print("x[2] Rclass: " + str(ParticleArray[0].R))
print("x[0] Rclass: " + str(ParticleArray[0].R))
ParticleArray[0].RaiseClass()
print("x[0] Rclass: " + str(ParticleArray[0].R))
ParticleArray[0].DemoteClass()
ParticleArray[0].DemoteClass()
print("Particle Amount: " + str(ParticleArray[0].ParticleAmount))
print("Total run time: " + str(datetime.now() - startTime) + "\n")
print("Random run time: " + str(datetime.now() - RandomTime) + "\n")
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
// TODO opção de definir probabilidade da mutação deletéria em cada infecção, de acordo com o ciclo determinado (trabalhar com intervalos)
// esta probabilidade estará sempre atrelada ao ciclo de infecção
// TODO BUG para poucas partículas, porcentagem de partículas que descem de classe pode dar mais de 100%, pois cálculo é feito
// no final do código, e o valor utilizado para o código é o da mutação
// TODO *** avaliar quando encerrar um paciente e passar para o próximo (média das classes for constante)
// TODO fazer simulação definindo em quais ciclos ocorrem infecções
// TODO interface gráfica (gráficos em tempo real, novas janelas para cada paciente etc)
// TODO: A INTRO explanation about this program, the main use, the aim, how it works, the output and what to do with.
namespace multi_dimensional_array
{
public class ProgramMarcos3D
{
// Number of Cycles
public const int Cycle = 10;
// Number of Classes
public const int Class = 11;
// Number of Patients
public const int Patient = 5;
static int[] InfectionCycle = new int[Patient];
//static int[,,] ParticlesThatInfected = new int[Patient, Cycle, Class];
// The "InitialParticles" is the initial amount of viral particles, that is: the initial virus population of a infection.
public const int InitialParticles = 5;
public const int MaxParticles = 1000000; // Limite máximo de partículas que quero impor para cada ciclo (linha)
//public const double DeleteriousProbability = 0.9;
static double[] DeleteriousProbability = new double[Cycle];
public const double BeneficialProbability = 0.005;
public const bool DeleteriousIncrement = false; // if true, deleterious probability will increase by INCREMENT each cycle
// if false, it will change from a fixed value to another fixed value, at the chosen cycle
// NOT USED YET
//public const int BottleneckParticles = 10;
// Lists to keep the number of particles that go up or down the classes, during mutations
static int[,] ClassUpParticles = new int[Patient, Cycle];
static int[,] ClassDownParticles = new int[Patient, Cycle];
static void Main(string[] args)
{
Random rnd = new Random();
// create and start the Stopwatch Class. From: https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//Thread.Sleep(10000);
FillInfectionCycleArray(5, 0); // FIRST PARAMETER: initial cycle, SECOND PARAMENTER: increment
if (DeleteriousIncrement)
{
FillDeleteriousArrayWithIncrement(0.3, 0.1); // FIRST PARAMETER: initial probability, SECOND PARAMENTER: increment
}
else
{
FillDeleteriousArray(0.3, 0.8, 5); // FIRST PARAMETER: first probability, SECOND PARAMENTER: second probability
// THIRD PARAMETER: cycle to change from first probability to second probability
}
// Declaring the three-dimensional Matrix: it has p Patient, x lines of Cycles and y columns of Classes, defined by the variables above.
int[,,] Matrix = new int[Patient, Cycle, Class];
// The Matrix starts on the Patient 0, 10th position (column) on the line zero.
// The "InitialParticles" is the amount of viral particles that exists in the class 10 on the cycle zero.
// That is: these 5 particles have the potential to create 10 particles each.
Matrix[0, 0, 10] = InitialParticles;
RunPatients(Matrix, rnd);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
PrintOutput(Matrix);
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("Total Run Time: " + elapsedTime);
Console.Write("\n");
Console.ReadKey();
}
static void FillInfectionCycleArray(int InitialCycle, int Increment)
{
for (int i = 0; i < InfectionCycle.GetLength(0); i++)
{
if (i == 0)
{
InfectionCycle[i] = InitialCycle;
}
else
{
if (InfectionCycle[i - 1] + Increment < Cycle)
{
InfectionCycle[i] = InfectionCycle[i - 1] + Increment;
}
else
{
InfectionCycle[i] = InfectionCycle[i - 1];
}
}
}
}
static void FillDeleteriousArray(double FirstProbability, double SecondProbability, int ChangeCycle)
{
for (int i = 0; i < DeleteriousProbability.GetLength(0); i++)
{
if (i <= ChangeCycle)
{
DeleteriousProbability[i] = FirstProbability;
}
else
{
DeleteriousProbability[i] = SecondProbability;
}
}
}
static void FillDeleteriousArrayWithIncrement(double InitialProbability, double Increment)
{
for (int i = 0; i < DeleteriousProbability.GetLength(0); i++)
{
if (i == 0)
{
DeleteriousProbability[i] = InitialProbability;
}
else
{
if (DeleteriousProbability[i - 1] + Increment <= (1 - BeneficialProbability))
{
DeleteriousProbability[i] = DeleteriousProbability[i - 1] + Increment;
}
else
{
DeleteriousProbability[i] = DeleteriousProbability[i - 1];
}
}
}
}
static void RunPatients(int[,,] Matrix, Random rndx)
{
// Main Loop to create more particles on the next Cycles from the Cycle Zero (lines values).
// Each matrix position will bring a value. This value will be mutiplied by its own class number (column value).
for (int p = 0; p < Patient; p++)
{
for (int i = 0; i < Cycle; i++)
{
for (int j = 0; j < Class; j++)
{
if (i > 0)
{
// Multiplies the number os particles from de previous Cycle by the Class number which belongs.
// This is the progeny composition.
Matrix[p, i, j] = Matrix[p, (i - 1), j] * j;
}
}
CutOffMaxParticlesPerCycle(Matrix, p, i, rndx);
ApplyMutationsProbabilities(Matrix, p, i);
if (i == InfectionCycle[p] && p < (Matrix.GetLength(0) - 1))
{
//Console.WriteLine(Matrix.GetLength(0));
PickRandomParticlesForInfection(Matrix, p, i, rndx);
Console.WriteLine("*** INFECTION CYCLE *** {0}", i);
}
// print which Cycle was finished just to give user feedback, because it may take too long to run.
Console.WriteLine("Cycles processed: {0}", i);
}
Console.WriteLine("Patients processed: {0}", p + 1);
}
}
static void ApplyMutationsProbabilities(int[,,] Matrix, int p, int i)
{
// This function will apply three probabilities: Deleterious, Beneficial or Neutral.
// Their roles is to simulate real mutations of virus genome.
// So here, there are mutational probabilities, which will bring an stochastic scenario sorting the progenies by the classes.
int UpParticles = 0;
int DownParticles = 0;
// Here a random number greater than zero and less than one is selected.
Random rnd = new Random();
double RandomNumber;
//RandomNumber = rnd.NextDouble();
//RandomNumber = 0.2;
//RandomNumber = 0.903;
// mutação deletéria = 90,0% de probabilidade (0,9)
// mutação benéfica = 0,5% de probabilidade (0,005)
// mutação neutra = 9,5% de probabilidade (0,095)
// para efeitos de sorteio, qualquer número entre 0 e 0,9 será mutação deletéria
// qualquer número entre 0,9 e 0,905 será mutação benéfica.
// Ou seja, o número sorteado precisa estar em um pequeno intervalo de 0,005 só que colocamos este intervalo acima de 0,9
// Qualquer número acima de 0,905 será mutação neutra
// Não precisamos definir a mutação neutra, pois no código de comparação, o número sorteado deverá ser maior que 0,905 (deletéria + benéfica)
// Here the probabilities numbers for each mutation is defined.
//double DeleteriousProbability = 0.6;
//double BeneficialProbability = 0.005;
int[] ThisCycle = new int[Class];
for (int j = 0; j < Class; j++)
{
ThisCycle[j] = Matrix[p, i, j];
}
for (int j = 0; j < Class; j++)
{
if (ThisCycle[j] > 0 && i > 0)
{
for (int particles = ThisCycle[j]; particles > 0; particles--)
{
// In this loop, for each particle removed from the Matrix [i,j], a random number is selected.
RandomNumber = rnd.NextDouble();
// If the random number is less than the DeleteriousProbability defined, one particle of the previous Cycle will
// decrease one Class number. Remember this function is inside a loop for each i and each j values.
// So this loop will run through the whole Matrix, particle by particle on its own positions.
if (RandomNumber < DeleteriousProbability[i])
// Deleterious Mutation = 90,0% probability (0.9)
{
Matrix[p, i, (j - 1)] = Matrix[p, i, (j - 1)] + 1;
Matrix[p, i, j] = Matrix[p, i, j] - 1;
DownParticles++;
}
else if (RandomNumber < (DeleteriousProbability[i] + BeneficialProbability))
// Beneficial Mutation = 0,5% probability (0.005)
{
if (j < (Class - 1))
{
Matrix[p, i, (j + 1)] = Matrix[p, i, (j + 1)] + 1;
Matrix[p, i, j] = Matrix[p, i, j] - 1;
}
if (j == Class)
{
Matrix[p, i, j] = Matrix[p, i, j] + 1;
}
UpParticles++;
}
}
}
}
ClassUpParticles[p, i] = UpParticles;
ClassDownParticles[p, i] = DownParticles;
// PSEUDOCODIGO (para melhor compreensão no desenvolvimento):
// se a classe R tiver partículas
// Para cada partícula da classe R, Ciclo n
// Pensar numa régua de 0 a 1 (O número sorteado é de 0 a 1):
// |____|____|____|____|____|____|____|____|____|____|
// 0 0.1 0.5 0.8 0.9 1
// MUTAÇÃO DELETÉRIA
// Se o valor sorteado for menor que a probabilidade da mutação deletéria (valor sorteado menor ou igual a 0,8)
// número de partículas da classe R recebe 1 partícula
// número de partículas da classe (R + 1) perde uma partícula
// MUTAÇÂO NEUTRA
// Se o valor sorteado for maior do que a mutação deletéria, mas menor do que a mutação neutra, ou seja,
// se o valor sorteado for maior do que 0.9 e menor do que 0.95
// as partículas não se alteram.
// MUTAÇÃO BENÉFICA
// Se o valor sorteado for maior ou igual à probalidade da mutação neutra (valor sorteado maior ou igual à 0.95)
// número de partículas da classe R perde 1 partícula
// número de partículas da classe (R + 1) recebe uma partícula
}
static int ParticlesInCycle(int[,,] Matrix, int p, int i)
{
// This funtion brings the sum value of particles by Cycle.
int Particles = 0;
for (int j = 0; j < Class; j++)
{
Particles = Particles + Matrix[p, i, j];
}
return Particles;
}
// PSEUDOCODIGO PARA SORTEIO E SELEÇÃO DE PARTÍCULAS PARA REDUÇÃO EM MAXPARTICLES POR CICLO (MÉTODO DIOGO)
// Para cada ciclo: enquanto SOMALINHA > MAXPARTICLES
// Sorteio de número (Sorteado) < SomaLinha
// Sorteado é menor do que a quantidade de partículas em R0?
// Se sim, tira uma partícula de R0; faz novo sorteio e recomeça o loop;
// Se não, faz Sorteado menos a quantidade de partículas em R0, este é Sort1.
// Sort1 é menor do que a quantidade de partículas em R1?
// Se sim, tira uma partícula de R1; faz novo sorteio e recomeça o loop até cumprir com a condição;
// Se não, faz Sort1 menos a quantidade de partículas em R2, este é Sort2.
// Assim até quando necessário.
// PSEUDOCODIGO PARA SORTEIO E SELEÇÃO DE PARTÍCULAS PARA REDUÇÃO EM MAXPARTICLES POR CICLO (MÉTODO MARCOS) = É o que será usado!!!
// Faz um arrray (lista) ordenando as quantidades de partículas da seguinte forma (em um mesmo ciclo):
// Array [0] = classe zero = quantidade de partículas na classe zero, ou seja, R0
// Array [1] = quantidade de partículas em R0 + quantidade de partículas em R1;
// Array [2] = quantidade de partículas em R0 + quantidade de partículas em R1 + quantidade de particulas em R2;
// E assim por diante. Dessa forma, cada posição deste array poderá ter um valor máximo.
// Para cada ciclo: enquanto SOMALINHA > MAXPARTICLES
// Sorteio de número (Sorteado) < SomaLinha
// Se o número sorteado for (0 < Sorteado <= Array[0]),
// Matriz [Ciclo, 0] perderá uma partícula.
// Assim vai até a SomaLinha chegar no MaxParticles determinado.
static void CutOffMaxParticlesPerCycle(int[,,] Matrix, int p, int i, Random rndx)
{
int ParticlesInThisCycle = ParticlesInCycle(Matrix, p, i); // Quantidade de partículas somadas por ciclo (linha)
int[] StatusR = new int[Class]; // Declarando o array que é a lista abaixo
// Se, x = ParticlesInCycle, for maior do que o núm MaxParticles definido, então...
if (ParticlesInThisCycle > MaxParticles)
{
// Para cada valor de x iniciando no valor de soma das partículas por ciclo;
// sendo x, ou seja, esta soma, maior do que o limite MaxParticles definido;
// então, diminua em uma unidade a soma das partículas por ciclo até que atinja o limite MaxParticles definido.
for (int Particles = ParticlesInCycle(Matrix, p, i); Particles > MaxParticles; Particles--)
// PARTICLES is equal to PARTICLESINTHISCYCLE, but we don't want to modifify PARTICLESINTHISCYCLE while the for loop is running
// also, PARTICLESINTHISCYCLE was created outside the for loop, for other purpose
{
StatusR[0] = Matrix[p, i, 0];
StatusR[1] = Matrix[p, i, 0] + Matrix[p, i, 1];
StatusR[2] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2];
StatusR[3] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3];
StatusR[4] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4];
StatusR[5] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5];
StatusR[6] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6];
StatusR[7] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7];
StatusR[8] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8];
StatusR[9] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8] + Matrix[p, i, 9];
StatusR[10] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8] + Matrix[p, i, 9] + Matrix[p, i, 10];
// Gero um número aleatório de 0 ao limite do valor de soma de partículas por ciclo (linha) = ParticlesInCycle
// int RandomMaxParticles;
int rndParticle = rndx.Next(1, ParticlesInCycle(Matrix, p, i));
// Aqui gero as condições para saber de qual classe serão retiradas as partículas para que
// ParticlesInCycle atinja o limite estipulado por MaxParticles
if (rndParticle > 0 && rndParticle <= StatusR[0])
{
Matrix[p, i, 0] = Matrix[p, i, 0] - 1;
}
if (rndParticle > StatusR[0] && rndParticle <= StatusR[1])
{
Matrix[p, i, 1] = Matrix[p, i, 1] - 1;
}
if (rndParticle > StatusR[1] && rndParticle <= StatusR[2])
{
Matrix[p, i, 2] = Matrix[p, i, 2] - 1;
}
if (rndParticle > StatusR[2] && rndParticle <= StatusR[3])
{
Matrix[p, i, 3] = Matrix[p, i, 3] - 1;
}
if (rndParticle > StatusR[3] && rndParticle <= StatusR[4])
{
Matrix[p, i, 4] = Matrix[p, i, 4] - 1;
}
if (rndParticle > StatusR[4] && rndParticle <= StatusR[5])
{
Matrix[p, i, 5] = Matrix[p, i, 5] - 1;
}
if (rndParticle > StatusR[5] && rndParticle <= StatusR[6])
{
Matrix[p, i, 6] = Matrix[p, i, 6] - 1;
}
if (rndParticle > StatusR[6] && rndParticle <= StatusR[7])
{
Matrix[p, i, 7] = Matrix[p, i, 7] - 1;
}
if (rndParticle > StatusR[7] && rndParticle <= StatusR[8])
{
Matrix[p, i, 8] = Matrix[p, i, 8] - 1;
}
if (rndParticle > StatusR[8] && rndParticle <= StatusR[9])
{
Matrix[p, i, 9] = Matrix[p, i, 9] - 1;
}
if (rndParticle > StatusR[9] && rndParticle <= StatusR[10])
{
Matrix[p, i, 10] = Matrix[p, i, 10] - 1;
}
}
}
}
static void PickRandomParticlesForInfection(int[,,] Matrix, int p, int i, Random rndx)
{
int InfectionParticles = 20;
//int ParticlesSelected = 0;
int ParticlesInThisCycle = ParticlesInCycle(Matrix, p, i); // Quantidade de partículas somadas por ciclo (linha)
int[] StatusR = new int[Class]; // TODO melhorar o nome deste array
// TODO o FOR LOOP abaixo não utiliza todas as partículas disponíveis no ciclo
// Em outras palavras, sobram partículas mesmo o ciclo tendo menos partículas do que INFECTIONPARTICLES
//while (ParticlesSelected < InfectionParticles)
//{
// StatusR[0] = Matrix[p, i, 0];
// StatusR[1] = Matrix[p, i, 0] + Matrix[p, i, 1];
// StatusR[2] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2];
// StatusR[3] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3];
// StatusR[4] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4];
// StatusR[5] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5];
// StatusR[6] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6];
// StatusR[7] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7];
// StatusR[8] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8];
// StatusR[9] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8] + Matrix[p, i, 9];
// StatusR[10] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8] + Matrix[p, i, 9] + Matrix[p, i, 10];
// // Gero um número aleatório de 0 ao limite do valor de soma de partículas por ciclo (linha) = ParticlesInCycle
// // int RandomMaxParticles;
// if (ParticlesInThisCycle > 0)
// {
// int rndParticle = rndx.Next(1, ParticlesInThisCycle);
// // Aqui gero as condições para saber de qual classe serão retiradas as partículas para que
// // ParticlesInCycle atinja o limite estipulado por MaxParticles
// if (rndParticle > 0 && rndParticle <= StatusR[0])
// {
// Matrix[(p + 1), 0, 0] += 1;
// Matrix[p, i, 0] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[0] && rndParticle <= StatusR[1])
// {
// Matrix[(p + 1), 0, 1] += 1;
// Matrix[p, i, 1] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[1] && rndParticle <= StatusR[2])
// {
// Matrix[(p + 1), 0, 2] += 1;
// Matrix[p, i, 2] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[2] && rndParticle <= StatusR[3])
// {
// Matrix[(p + 1), 0, 3] += 1;
// Matrix[p, i, 3] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[3] && rndParticle <= StatusR[4])
// {
// Matrix[(p + 1), 0, 4] += 1;
// Matrix[p, i, 4] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[4] && rndParticle <= StatusR[5])
// {
// Matrix[(p + 1), 0, 5] += 1;
// Matrix[p, i, 5] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[5] && rndParticle <= StatusR[6])
// {
// Matrix[(p + 1), 0, 6] += 1;
// Matrix[p, i, 6] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[6] && rndParticle <= StatusR[7])
// {
// Matrix[(p + 1), 0, 7] += 1;
// Matrix[p, i, 7] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[7] && rndParticle <= StatusR[8])
// {
// Matrix[(p + 1), 0, 8] += 1;
// Matrix[p, i, 8] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[8] && rndParticle <= StatusR[9])
// {
// Matrix[(p + 1), 0, 9] += 1;
// Matrix[p, i, 9] -= 1;
// ParticlesSelected++;
// }
// if (rndParticle > StatusR[9] && rndParticle <= StatusR[10])
// {
// Matrix[(p + 1), 0, 10] += 1;
// Matrix[p, i, 10] -= 1;
// ParticlesSelected++;
// }
// }
// else
// {
// Console.WriteLine("Patient {0} Cicle {1} has no particles. FOR LOOP iteration number {2}\t\t", p, i, ParticlesSelected);
// ParticlesSelected++;
// }
//}
for (int ParticlesSelected = 0; ParticlesSelected < InfectionParticles; ParticlesSelected++)
{
StatusR[0] = Matrix[p, i, 0];
StatusR[1] = Matrix[p, i, 0] + Matrix[p, i, 1];
StatusR[2] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2];
StatusR[3] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3];
StatusR[4] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4];
StatusR[5] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5];
StatusR[6] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6];
StatusR[7] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7];
StatusR[8] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8];
StatusR[9] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8] + Matrix[p, i, 9];
StatusR[10] = Matrix[p, i, 0] + Matrix[p, i, 1] + Matrix[p, i, 2] + Matrix[p, i, 3] + Matrix[p, i, 4] + Matrix[p, i, 5] + Matrix[p, i, 6] + Matrix[p, i, 7] + Matrix[p, i, 8] + Matrix[p, i, 9] + Matrix[p, i, 10];
// Gero um número aleatório de 0 ao limite do valor de soma de partículas por ciclo (linha) = ParticlesInCycle
// int RandomMaxParticles;
if (ParticlesInThisCycle > 0)
{
int rndParticle = rndx.Next(1, ParticlesInThisCycle);
// Aqui gero as condições para saber de qual classe serão retiradas as partículas para que
// ParticlesInCycle atinja o limite estipulado por MaxParticles
if (rndParticle > 0 && rndParticle <= StatusR[0])
{
Matrix[(p + 1), 0, 0] += 1;
Matrix[p, i, 0] -= 1;
}
if (rndParticle > StatusR[0] && rndParticle <= StatusR[1])
{
Matrix[(p + 1), 0, 1] += 1;
Matrix[p, i, 1] -= 1;
}
if (rndParticle > StatusR[1] && rndParticle <= StatusR[2])
{
Matrix[(p + 1), 0, 2] += 1;
Matrix[p, i, 2] -= 1;
}
if (rndParticle > StatusR[2] && rndParticle <= StatusR[3])
{
Matrix[(p + 1), 0, 3] += 1;
Matrix[p, i, 3] -= 1;
}
if (rndParticle > StatusR[3] && rndParticle <= StatusR[4])
{
Matrix[(p + 1), 0, 4] += 1;
Matrix[p, i, 4] -= 1;
}
if (rndParticle > StatusR[4] && rndParticle <= StatusR[5])
{
Matrix[(p + 1), 0, 5] += 1;
Matrix[p, i, 5] -= 1;
}
if (rndParticle > StatusR[5] && rndParticle <= StatusR[6])
{
Matrix[(p + 1), 0, 6] += 1;
Matrix[p, i, 6] -= 1;
}
if (rndParticle > StatusR[6] && rndParticle <= StatusR[7])
{
Matrix[(p + 1), 0, 7] += 1;
Matrix[p, i, 7] -= 1;
}
if (rndParticle > StatusR[7] && rndParticle <= StatusR[8])
{
Matrix[(p + 1), 0, 8] += 1;
Matrix[p, i, 8] -= 1;
}
if (rndParticle > StatusR[8] && rndParticle <= StatusR[9])
{
Matrix[(p + 1), 0, 9] += 1;
Matrix[p, i, 9] -= 1;
}
if (rndParticle > StatusR[9] && rndParticle <= StatusR[10])
{
Matrix[(p + 1), 0, 10] += 1;
Matrix[p, i, 10] -= 1;
}
}
else
{
Console.WriteLine("Patient {0} Cicle {1} has no particles. FOR LOOP iteration number {2}\t\t", p, i, ParticlesSelected);
}
}
}
static void PrintOutput(int[,,] Matrix)
{
double PercentageOfParticlesUp = 0.0;
double PercentageOfParticlesDown = 0.0;
StreamWriter writer = new StreamWriter("numbers.txt");
// The writer will bring the output file (txt in this case)
// Ensure the writer will be closed when no longer used
using (writer)
{
// Formatting Output for the Console screen.
Console.WriteLine("");
Console.Write("\t\t\tR0\tR1\tR2\tR3\tR4\tR5\tR6\tR7\tR8\tR9\t\tR10\n\n");
writer.Write("\t\tSoma\tR0\tR1\tR2\tR3\tR4\tR5\tR6\tR7\tR8\t\tR9\t\tR10\n\n");
writer.WriteLine("\n");
for (int p = 0; p < Patient; p++)
{
for (int i = 0; i < Cycle; i++)
{
Console.Write("Pac.{0} Cic.{1}\t\t", p, i);
writer.Write("Pac.{0} Cic.{1} {2}\t\t", p, i, ParticlesInCycle(Matrix, p, i));
for (int j = 0; j < Class; j++)
{
Console.Write("{0}\t", Matrix[p, i, j]);
writer.Write("{0}\t", Matrix[p, i, j]);
}
PercentageOfParticlesUp = (Convert.ToDouble(ClassUpParticles[p, i]) / Convert.ToDouble(ParticlesInCycle(Matrix, p, i))) * 100;
PercentageOfParticlesDown = (Convert.ToDouble(ClassDownParticles[p, i]) / Convert.ToDouble(ParticlesInCycle(Matrix, p, i))) * 100;
Console.WriteLine("\nSoma do ciclo {0}: {1}", i, ParticlesInCycle(Matrix, p, i));
Console.WriteLine("Particles Up: {0}, {1} %", ClassUpParticles[p, i], PercentageOfParticlesUp);
Console.WriteLine("Particles Down: {0}, {1} %", ClassDownParticles[p, i], PercentageOfParticlesDown);
Console.Write("\n");
writer.WriteLine("\n");
}
Console.WriteLine("***************************************************************************************************************");
Console.Write("\n");
Console.Write("\n");
}
}
}
}
}
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 16:31:46 2019
@author: Marcos
"""
import os
import xlsxwriter
import xlrd
def main():
ExcelFileName = "Data.xlsx"
workbook = xlsxwriter.Workbook(ExcelFileName)
worksheet = workbook.add_worksheet()
HorizAlign = workbook.add_format()
HorizAlign.set_align('center')
LastRowAvailable = 0
# directory = r"E:\Taima\Mestrado\Python\Simulacoes\TestesEstatisticos\R5Cycle5\TFounderSim01-03-2019_15-59-55.xlsx"
# print(sh.cell_value(rowx = 20, colx = 7))
#
# print(sh.cell_value(rowx = 20, colx = 14))
# SourceFile = xlrd.open_workbook(directory)
# sh = SourceFile.sheet_by_index(0)
for root, dirs, files in os.walk('E:\Taima\Mestrado\Python\Simulacoes\TestesEstatisticos\R5Cycle5'):
SourceFiles = [ _ for _ in files if _.endswith('.xlsx') ]
for xlsfile in SourceFiles:
SourceFile = xlrd.open_workbook(os.path.join(root,xlsfile))
SourceSheet = SourceFile.sheet_by_index(0)
RParticles = SourceSheet.cell_value(rowx = 23, colx = 6)
CycleTotal = SourceSheet.cell_value(rowx = 23, colx = 14)
worksheet.write(LastRowAvailable, 0, RParticles)
worksheet.write(LastRowAvailable, 1, CycleTotal)
LastRowAvailable += 1
workbook.close()
# for row in range(sh.nrows):
# print(sh.row(row))
# print("Worksheet name(s): {0}".format(book.sheet_names()))
if __name__ == '__main__':
main()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 16:00:00 2019
@author: Marcos
"""
import os
import xlsxwriter
import xlrd
from datetime import datetime
import statistics
import numpy
"""
This script takes data from all the Excel files in a folder, and reads
only two cells from each file: the number of particles of one cell
"""
def main():
ExcelFileName = "TFounderSim_SUMDATA_" + datetime.now().strftime('%d-%m-%Y_%H-%M-%S') + '.xlsx'
workbook = xlsxwriter.Workbook(ExcelFileName)
DataSheet = workbook.add_worksheet('Data')
TransmissionSheet = workbook.add_worksheet('Transmission Cycles')
RawRmaxSheet = workbook.add_worksheet('RawRmax')
RawMiSheet = workbook.add_worksheet('RawMi')
HorizAlign = workbook.add_format()
HorizAlign.set_align('center')
DataLastRowAvailable = 0
TransmissionLastRowAvailable = 0
RawRmaxLastRowAvailable = 0
RawMiLastRowAvailable = 0
# set_column(column1, column2, size)
TransmissionSheet.set_column(0, 0, 9)
TransmissionSheet.merge_range(0, 0, 1, 0, 'Patient') # 1st row, 1st col, last row, last col, content
TransmissionSheet.write(TransmissionLastRowAvailable, 4, "Transmission Cycle")
TransmissionLastRowAvailable += 2
RawRmaxSheet.set_column(0, 0, 9)
RawRmaxSheet.merge_range(0, 0, 1, 0, 'Patient') # 1st row, 1st col, last row, last col, content
RawRmaxSheet.write(TransmissionLastRowAvailable, 4, "Rmax")
RawRmaxLastRowAvailable += 2
RawMiSheet.set_column(0, 0, 9)
RawMiSheet.merge_range(0, 0, 1, 0, 'Patient') # 1st row, 1st col, last row, last col, content
RawMiSheet.write(TransmissionLastRowAvailable, 4, "Mi")
RawMiLastRowAvailable += 2
for root, dirs, files in os.walk('C:\Taima_Furuyama\Mestrado_UNIFESP\Programacao\Python\Simulacoes\TestesEstatisticos\TF_InfCycleAleat_B3.8_D3.8_101Ger_Cadeia_XSim'):
SourceFiles = [ _ for _ in files if _.endswith('.xlsx') ]
# Open a file just to get the generations amount
FirstFile = xlrd.open_workbook(os.path.join(root,SourceFiles[0]))
FirstSheet = FirstFile.sheet_by_index(0)
Generations = int(FirstSheet.cell_value(rowx = 0, colx = 1))
SimulationAmount = len(SourceFiles)
DataSheet.write(DataLastRowAvailable, 0, "Mean Values of " + str(SimulationAmount) + " simulations")
DataLastRowAvailable += 1
#DataSheet.set_column(linha, coluna, tamanho)
#DataSheet.merge_range(linha, coluna, mescla linhas, mescla colunas,"Conteúdo escrito"
DataSheet.merge_range(1, 0, 2, 0, "Generation - Patient")
DataSheet.set_column(0, 0, 17)
DataSheet.merge_range(1, 4, 1, 6, "RMax Cycle 0")
DataSheet.merge_range(1, 10, 1, 12, "Mi Cycle 0")
DataLastRowAvailable += 1
Labels = ["Mean", "Median", "StdDev", "Min", "Max", "Var"]
for i in range(1, 7):
DataSheet.write(DataLastRowAvailable, i + 3, Labels[i - 1])
DataSheet.write(DataLastRowAvailable, i + 9, Labels[i - 1])
DataLastRowAvailable += 1
Simulation = 0
if SimulationAmount > 0:
RawRmaxSheet.write(0, 4, "Rmax")
RawMiSheet.write(0, 4, "Mi")
MiArray = [[None for i in range(SimulationAmount)] for x in range(Generations)]
RMaxArray = [[None for i in range(SimulationAmount)] for x in range(Generations)]
for xlsfile in SourceFiles:
"""Saves transmission cycles for each patient into TransmissionSheet"""
SourceFile = xlrd.open_workbook(os.path.join(root,xlsfile))
for i in range(Generations):
SourceSheet = SourceFile.sheet_by_index(i + 1)
"""Reading data"""
# GenPatient = SourceSheet.cell_value(rowx = 1, colx = 1)
GenerationText = SourceSheet.cell_value(rowx = 1, colx = 1)
GenerationValue = SourceSheet.cell_value(rowx = 1, colx = 2)
PatientText = SourceSheet.cell_value(rowx = 1, colx = 3)
PatientValue = SourceSheet.cell_value(rowx = 1, colx = 4)
if i < (Generations - 1):
TransmissionCycle = SourceSheet.cell_value(rowx = 50, colx = 2)
# LastInfectedPatient = SourceSheet.cell_value(rowx = 50, colx = 3)
RmaxValue = SourceSheet.cell_value(rowx = 49, colx = 1)
MiValue = SourceSheet.cell_value(rowx = 3, colx = 13)
DataSheet.write(DataLastRowAvailable + 1, 0, GenerationText)
DataSheet.write(DataLastRowAvailable + 1, 1, GenerationValue)
DataSheet.write(DataLastRowAvailable + 1, 2, PatientText)
DataSheet.write(DataLastRowAvailable + 1, 3, PatientValue)
else:
# Last patient doesn't have row 55
TransmissionCycle = 0
# DataSheet.write(DataLastRowAvailable + 1, 0, GenerationText)
DataSheet.write(DataLastRowAvailable + 1, 1, GenerationValue)
# DataSheet.write(DataLastRowAvailable + 1, 2, PatientText)
# DataSheet.write(DataLastRowAvailable + 1, 3, PatientValue)
# LastInfectedPatient = SourceSheet.cell_value(rowx = 50, colx = 3)
# RmaxValue = SourceSheet.cell_value(rowx = 49, colx = 1)
# MiValue = SourceSheet.cell_value(rowx = 3, colx = 13)
Mi = SourceSheet.cell_value(rowx = 3, colx = 13)
MiArray[i].pop(0)
MiArray[i].append(Mi)
RMax = SourceSheet.cell_value(rowx = 49, colx = 1)
RMaxArray[i].pop(0)
RMaxArray[i].append(RMax)
"""Writing Transmission data"""
TransmissionSheet.write(1, Simulation + 4, "Simulation " + str(Simulation))
TransmissionSheet.set_column(Simulation + 1, Simulation + 1, 10) # set_column(column1, column2, size)
TransmissionSheet.write(TransmissionLastRowAvailable, 0, GenerationText)
TransmissionSheet.write(TransmissionLastRowAvailable, 1, GenerationValue)
TransmissionSheet.write(TransmissionLastRowAvailable, 2, PatientText)
TransmissionSheet.write(TransmissionLastRowAvailable, 3, PatientValue)
TransmissionSheet.write(TransmissionLastRowAvailable, Simulation + 4, TransmissionCycle)
TransmissionLastRowAvailable += 1
RawRmaxSheet.write(1, Simulation + 4, "Simulation " + str(Simulation))
RawRmaxSheet.set_column(Simulation + 1, Simulation + 1, 10) # set_column(column1, column2, size)
RawRmaxSheet.write(RawRmaxLastRowAvailable, 0, GenerationText)
RawRmaxSheet.write(RawRmaxLastRowAvailable, 1, GenerationValue)
RawRmaxSheet.write(RawRmaxLastRowAvailable, 2, PatientText)
RawRmaxSheet.write(RawRmaxLastRowAvailable, 3, PatientValue)
RawRmaxSheet.write(RawRmaxLastRowAvailable, Simulation + 4, RmaxValue)
RawRmaxLastRowAvailable += 1
RawMiSheet.write(1, Simulation + 4, "Simulation " + str(Simulation))
RawMiSheet.set_column(Simulation + 1, Simulation + 1, 10) # set_column(column1, column2, size)
RawMiSheet.write(RawMiLastRowAvailable, 0, GenerationText)
RawMiSheet.write(RawMiLastRowAvailable, 1, GenerationValue)
RawMiSheet.write(RawMiLastRowAvailable, 2, PatientText)
RawMiSheet.write(RawMiLastRowAvailable, 3, PatientValue)
RawMiSheet.write(RawMiLastRowAvailable, Simulation + 4, MiValue)
RawMiLastRowAvailable += 1
"""Writing only patient number on DataSheet
Mi and RMax are going to be written later"""
DataLastRowAvailable += 1
Simulation +=1
DataLastRowAvailable = 2
TransmissionLastRowAvailable = 2
RawRmaxLastRowAvailable = 2
RawMiLastRowAvailable = 2
DataLastRowAvailable = 3
MiMeanArray = [None for x in range(Generations)]
MiMedianArray = [None for x in range(Generations)]
MiStdDevArray = [None for x in range(Generations)]
MiMinArray = [None for x in range(Generations)]
MiMaxArray = [None for x in range(Generations)]
MiVarArray = [None for x in range(Generations)]
RMaxMeanArray = [None for x in range(Generations)]
RMaxMedianArray = [None for x in range(Generations)]
RMaxStdDevArray = [None for x in range(Generations)]
RMaxMinArray = [None for x in range(Generations)]
RMaxMaxArray = [None for x in range(Generations)]
RMaxVarArray = [None for x in range(Generations)]
# print(MiMeanArray.pop(0))
for Gen in range(Generations):
"""calculate the statistical parameters"""
MiMeanArray.pop(0)
Mean = statistics.mean(MiArray[Gen])
MiMeanArray.append(Mean)
MiMedianArray.pop(0)
Median = statistics.median(MiArray[Gen])
MiMedianArray.append(Median)
MiStdDevArray.pop(0)
StdDev = statistics.pstdev(MiArray[Gen])
MiStdDevArray.append(StdDev)
MiMinArray.pop(0)
Min = min(MiArray[Gen])
MiMinArray.append(Min)
MiMaxArray.pop(0)
Max = max(MiArray[Gen])
MiMaxArray.append(Max)
MiVarArray.pop(0)
Var = statistics.pvariance(MiArray[Gen])
MiVarArray.append(Var)
RMaxMeanArray.pop(0)
Mean = statistics.mean(RMaxArray[Gen])
RMaxMeanArray.append(Mean)
RMaxMedianArray.pop(0)
Median = statistics.median(RMaxArray[Gen])
RMaxMedianArray.append(Median)
RMaxStdDevArray.pop(0)
StdDev = statistics.pstdev(RMaxArray[Gen])
RMaxStdDevArray.append(StdDev)
RMaxMinArray.pop(0)
Min = min(RMaxArray[Gen])
RMaxMinArray.append(Min)
RMaxMaxArray.pop(0)
Max = max(RMaxArray[Gen])
RMaxMaxArray.append(Max)
RMaxVarArray.pop(0)
Var = statistics.pvariance(RMaxArray[Gen])
RMaxVarArray.append(Var)
# print(MiMedianArray)
for Gen in range(Generations):
"""writes the statistical parameters"""
DataSheet.write(DataLastRowAvailable, 4, RMaxMeanArray[Gen])
DataSheet.write(DataLastRowAvailable, 5, RMaxMedianArray[Gen])
DataSheet.write(DataLastRowAvailable, 6, RMaxStdDevArray[Gen])
DataSheet.write(DataLastRowAvailable, 7, RMaxMinArray[Gen])
DataSheet.write(DataLastRowAvailable, 8, RMaxMaxArray[Gen])
DataSheet.write(DataLastRowAvailable, 9, RMaxVarArray[Gen])
DataSheet.write(DataLastRowAvailable, 10, MiMeanArray[Gen])
DataSheet.write(DataLastRowAvailable, 11, MiMedianArray[Gen])
DataSheet.write(DataLastRowAvailable, 12, MiStdDevArray[Gen])
DataSheet.write(DataLastRowAvailable, 13, MiMinArray[Gen])
DataSheet.write(DataLastRowAvailable, 14, MiMaxArray[Gen])
DataSheet.write(DataLastRowAvailable, 15, MiVarArray[Gen])
DataLastRowAvailable += 1
workbook.close()
if __name__ == '__main__':
main()
| d620717ec0bd35cb12a8c75c17c59708a56aafef | [
"Markdown",
"C#",
"Python"
] | 11 | Markdown | taimafuruyama/Projetos_UNIFESP | e7e4f41f3030c2d684a33c9ad43f17ceffa7a2d7 | 1b555867c673cd3abe411fa399730a9e7f6beeb1 |
refs/heads/master | <repo_name>fidelina/helm-postgres<file_sep>/Dockerfile
FROM centos:centos7.6.1810
COPY files/repo/postgrespro-ent-10.repo /etc/yum.repos.d/
RUN sed -i 's/override/#override/g' /etc/yum.conf \
&& yum clean all; yum install -y -q glibc-common \
&& yum install -y postgrespro-ent-11-client postgrespro-ent-11-server postgrespro-ent-11-contrib \
pg-probackup-ent-11 pg-filedump-ent-11 ;\
yum clean all \
&& mkdir /data/ /data/postgres; chown -R postgres. /data/ \
&& localedef -i ru_RU -c -f UTF-8 -A /usr/share/locale/locale.alias ru_RU.UTF-8;
COPY files/config.sh /opt
COPY files/entrypoint.sh /tmp
RUN chmod +x /tmp/entrypoint.sh; chown postgres. /tmp/entrypoint.sh; touch /tmp/pg_log; chown postgres. /tmp/pg_log
USER postgres
ENV LANG ru_RU.utf8
ENTRYPOINT ["bash", "+x", "/tmp/entrypoint.sh"]
<file_sep>/files/config.sh
#!/bin/bash
#chmod g+x /var/lib/pgpro/ /var/lib/pgpro/ent-11/;
chown postgres. /var/lib/pgpro/ent-11/;
runuser -l postgres -c '/opt/pgpro/ent-11/bin/pg_ctl -D /data/postgres initdb -o "-E=UTF8"';
runuser -l postgres -c '/opt/pgpro/ent-11/bin/pg_ctl -D /data/postgres start';
runuser -l postgres -c "cat << EOF | /opt/pgpro/ent-11/bin/psql --dbname=postgres --username=postgres
ALTER SYSTEM SET listen_addresses = localhost;
ALTER SYSTEM SET default_transaction_isolation = 'read committed';
ALTER SYSTEM SET wal_level = logical;
ALTER SYSTEM SET max_connections = 1500;
ALTER SYSTEM SET max_prepared_transactions = 300;
ALTER SYSTEM SET max_wal_senders = 10;
ALTER SYSTEM SET max_replication_slots = 10;
ALTER SYSTEM SET max_worker_processes = 250;
CREATE USER gasu;
CREATE DATABASE gods OWNER gasu ENCODING 'UTF8' LC_COLLATE = 'ru_RU.utf8' LC_CTYPE = 'ru_RU.utf8' TEMPLATE template0;
GRANT ALL PRIVILEGES ON DATABASE gods TO gasu;
EOF"
<file_sep>/files/entrypoint.sh
#!/usr/bin/env bash
#/opt/pgpro/ent-11/bin/pg_ctl -D /data/postgres -l /tmp/pg_log start;
touch /tmp/pg_log;
while [ -f /tmp/pg_log ]; do
sleep 1;
done;
#system_exit
exit $EXIT_CODE | 3ed7a4f61407a5a637cca630afe7c146b05d3bd3 | [
"Dockerfile",
"Shell"
] | 3 | Dockerfile | fidelina/helm-postgres | 7be34bd6494a6398cafda981f6b88f99e6c80886 | a3e41840932b32f1b035a5f578d930597af939cd |
refs/heads/master | <repo_name>martypowell/RailsDemo<file_sep>/app/views/releases/show.json.jbuilder
json.extract! @release, :id, :version, :desc, :date, :app_id, :created_at, :updated_at
<file_sep>/app/views/servers/show.json.jbuilder
json.extract! @server, :id, :name, :environment_type, :os, :created_at, :updated_at
<file_sep>/app/views/platforms/show.json.jbuilder
json.extract! @platform, :id, :name, :desc, :active, :created_at, :updated_at
<file_sep>/app/views/apps/index.json.jbuilder
json.array!(@apps) do |app|
json.extract! app, :id, :name, :desc, :in_house, :platform
json.url app_url(app, format: :json)
end
<file_sep>/app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
@apps = App.order(:updated_at)
end
end
<file_sep>/app/models/app.rb
class App < ActiveRecord::Base
has_many :releases, dependent: :destroy
validates_presence_of :name
end
<file_sep>/app/views/releases/index.json.jbuilder
json.array!(@releases) do |release|
json.extract! release, :id, :version, :desc, :date, :app_id
json.url release_url(release, format: :json)
end
<file_sep>/app/views/apps/show.json.jbuilder
json.extract! @app, :id, :name, :desc, :in_house, :created_at, :updated_at, :platform
| 3bf3e765c925621899cb60bda191f6cb956de195 | [
"Ruby"
] | 8 | Ruby | martypowell/RailsDemo | 253bd65dc9367bb02b5e42973a234ca999063b2a | 5d836eb1c30d6896ee184e3b574573a0d37c28a3 |
refs/heads/master | <file_sep>require "pry"
def oxford_comma(array)
if array.size ==1
array.join
elsif array.size ==2
array.join(" and ")
else array.size >=3
array.last.insert(0,"and ")
array.join(", ")
end
end
| ffe3a54386887ee401894ae88e5568afb5b330b8 | [
"Ruby"
] | 1 | Ruby | stanimirvasilev/oxford-comma-online-web-sp-000 | c17923692be5c4fa31f32542eba57359f1cfd6c1 | bf44d41995e88647d37315cb44e05e48a6202adc |
refs/heads/master | <repo_name>itstylerrr/Simplicity<file_sep>/README.md
---
description: >-
Welcome to the Documentation for all of the bots and windows applications
developed by Tyler for the Simplicity organization.
---
# Tyler's Development Docs

<file_sep>/SUMMARY.md
# Table of contents
* [Tyler's Development Docs](README.md)
## Important Links
* [Main Website](https://tylersdev.ml)
* [Our Discord](https://discord.gg/KGXrYdY8BN)
## Discord Bots
* [Simplicity](discord-bots/simplicity.md)
## Windows Apps
* [Carbon X](windows-apps/carbon-x.md)
<file_sep>/discord-bots/simplicity.md
---
description: >-
Simplicity is a Discord Bot coded in DJS v13 by @!ts tyler#7922 || Learn how
to set it up here!
---
# Simplicity
## Inviting the bot.
Obviously, if you don't have a server that you have admin powers in, create one. Nextly in your browser copy and paste this link.
```
https://discordapp.com/invite something here
```
{% hint style="info" %}
It may ask for the bot to have admin powers in your server, please allow that so Simplicity is able to run every command in your server without error.
{% endhint %}
Once you have invited the bot, it should be pretty straightforward to set up, just type in the command for the help menu, and everything should be explained there.
The default prefix for Simplicity is: `$`
{% code title="Discord Channel" %}
```bash
$help
```
{% endcode %}
<file_sep>/index.js
console.clear();
const DiscordJS = require("discord.js");
const WOKCommands = require("wokcommands");
const path = require("path");
const config = require("./config.json");
var colors = require("colors");
colors.setTheme({
bot: "cyan",
mongo: "green",
warn: "yellow",
error: "red",
});
const { Intents } = DiscordJS;
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],
});
client.on("ready", () => {
console.log("-BOT-".bot, "Simplicity is updated to the latest version ✅");
console.log("-BOT-".bot, "Simplicity is loading commands 🔃");
console.log("-MONGO-".mongo, "Simplicity is commecting to mongo 🔃");
new WOKCommands(client, {
commandsDir: path.join(__dirname, "commands"),
messagesPath: "",
showWarns: true,
delErrMsgCooldown: 10,
defaultLangauge: "english",
ignoreBots: false,
dbOptions: {
keepAlive: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
},
testServers: ["866487944898281502"],
disabledDefaultCommands: [],
mongoUri: config.mongoUri,
})
.setDefaultPrefix("$")
.setColor("WHITE")
.setCategorySettings([
{
name: "Fun & Games",
emoji: "🎮",
},
{
name: "Economy",
emoji: "💸",
},
{
name: "Testing",
emoji: "⚠",
},
{
name: "Information",
emoji: "ℹ",
},
]);
console.log("-MONGO-".mongo, "Simplicity has connected to mongo ✅");
console.log("-BOT-".bot, "Simplicity has loaded all commands ✅");
console.log();
console.log("-BOT-".bot, "Simplicity is ready ✅");
});
client.on('guildDelete', guild => {
let servericon = guild.iconURL();
const guildDel = new DiscordJS.MessageEmbed()
.setAuthor(`@Simplicity has left ${guild.name} 🚫`, servericon)
.setColor("RED")
.setTimestamp();
let mainguild = client.guilds.cache.get('866487944898281502');
if (mainguild) {
channel = mainguild.channels.cache.get('886741127951171644');
if (channel) {
channel.send({embeds: [guildDel]})
}
}
});
client.on('guildCreate', guild => {
let servericon = guild.iconURL();
const guildAdd = new DiscordJS.MessageEmbed()
.setAuthor(`@Simplicity has joined ${guild.name} ✅`, servericon)
.addField(`Total Members`, `**${client.guilds.cache.reduce((x, guild) => x + guild.memberCount, 0)}** members!`)
.setColor("#65db7b")
.setTimestamp();
let mainguild = client.guilds.cache.get('866487944898281502');
if (mainguild) {
channel = mainguild.channels.cache.get('886741127951171644');
if (channel) {
channel.send({embeds: [guildAdd]})
}
}
});
client.login(config.TOKEN);
<file_sep>/commands/Fun & Games/8ball.js
const { MessageEmbed } = require('discord.js')
module.exports = {
category: 'Fun & Games',
description: 'The 8Ball command gives you anwsers to your most difficult questions.',
aliases: ['anwser', '🎱'],
cooldown: '5s',
callback: async ({ message, interaction, args }) => {
const anwsers = [
'It is certain.',
'It is decidedly so.',
'Without a doubt.',
'Yes - definitely.',
'You may rely on it.',
'As I see it, yes.',
'Most likely.',
'Outlook good.',
'Yes.',
'Signs point to yes.',
'Reply hazy, try again.',
'Ask again later.',
'Better not tell you now.',
'Cannot predict now.',
'Concentrate and ask again.',
'Don\'t count on it.',
'My reply is no.',
'My sources say no.',
'Outlook not so good.',
'Very doubtful.'
];
const question = args.join(' ');
if (!question) {
message.reply('Please provide a question.')
return;
}
const embed = new MessageEmbed()
.setTitle('🎱 The Magic 8-Ball 🎱')
.addField('Your Question', question)
.addField('Your Answer', `${anwsers[Math.floor(Math.random() * anwsers.length)]}`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send( {embeds: [embed]} );
}
}<file_sep>/windows-apps/carbon-x.md
---
description: >-
Carbon X is Simplicity's best ROBLOX executor available for free, with an API
allowing you to execute about any script! NO ADS!
---
# Carbon X
## Installing Carbon X
The first thing that you need to do before downloading any executor is disable your anti-virus. Now go to the website for Carbon X, using the link below. Once you are there, there should be a button that says "Download Now" click that.
```
https://carbonx.iitstyler.repl.co/
```
{% hint style="info" %}
You will be prompted to join our Discord server. You must join that, or you will not be able to download the application, as the bootstrapper is on our Discord.
{% endhint %}
One you have downloaded the bootstrapper, drag it onto your desktop, run it, then all the files should be downloaded and extracted onto your desktop. Now find the folder named "Carbon X v\(version \#\)" open it and run the EXE file.
Then you should be all set up with Carbon X.
<file_sep>/commands/Fun & Games/meme.js
const { MessageEmbed } = require('discord.js')
const fetch = require('node-fetch')
module.exports = {
category: 'Fun & Games',
description: 'Shows a random meme from the memes, dankmemes, or me_irl subreddits.',
cooldown: '5s',
callback: async ({ message, interaction }) => {
let res = await fetch('https://meme-api.herokuapp.com/gimme');
res = await res.json();
const embed = new MessageEmbed()
.setAuthor(`Subreddit: ${res.title}`)
.setTitle(`🤣 Meme 🤣`)
.setImage(res.url)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send({embeds: [embed]});
},
} | bd07d2266b4a84d67f4058178da9ab514721717e | [
"Markdown",
"JavaScript"
] | 7 | Markdown | itstylerrr/Simplicity | 1ed35e5dcfd897fde2304d32ed9643b6616b0b23 | 11794a111ad55a2ec3fecd7c7c9c4bd9c07fd339 |
refs/heads/main | <file_sep># With this concept of default parameters in mind, the goal of this assignment is to write a single function, randInt() that takes up to 2 arguments.
# If no arguments are provided, the function should return a random integer between 0 and 100.
# If only a max number is provided, the function should return a random integer between 0 and the max number.
# If only a min number is provided, the function should return a random integer between the min number and 100
# If both a min and max number are provided, the function should return a random integer between those 2 value
import random
def randInt(min= 0, max= 100 ):
if(max < min or max < 0):
print("invalid entries. Random number will be in default range")
min = 0
max = 100
num = random.randint(min, max)
return num
print(randInt()) # should print a random integer between 0 to 100
print(randInt(max=50)) # should print a random integer between 0 to 50
print(randInt(min=50)) # should print a random integer between 50 to 100
print(randInt(min=50, max=500)) # should print a random integer between 50 and 500
print("\n---max>min---")
print(randInt(300, 50))
print("\nmax < 0")
print(randInt(max = -1))
| b6a6281ad97f92ec35a98f6939f37c100b9910be | [
"Python"
] | 1 | Python | SDBranka/Functions_intermediate1 | 1d8403be672ba71d7e03360159bfc0b716f38c04 | ed38379550ef1a2ca395c35862123faa4e4340ff |
refs/heads/master | <repo_name>phamhongviet/serf-template<file_sep>/template.go
package main
import (
"os"
"text/template"
)
func RenderTemplate(src string, dest string, env interface{}) {
// parse template
tpl, err := template.ParseFiles(src)
if err != nil {
panic(err)
}
// render template
result_file, err := os.Create(dest)
defer result_file.Close()
if err != nil {
panic(err)
}
err = tpl.Execute(result_file, env)
if err != nil {
panic(err)
}
}
<file_sep>/README.md
# Serf Template
Template rendering with Serf.
## Installation
$ git clone https://github.com/phamhongviet/serf-template.git
$ cd serf-template
$ go build
## Usage
$ serf-template config-file
Instead of reading anything from stdin or environment variables, Serf Template get members' information from the RPC interface. Serf Temlate subscribe to member related events from RPC stream (member-join, member-failed, member-update, member-leave and member-reap).
## Configuration
Example:
{
"serf": "path/to/serf"
"name": "regexp",
"role": "regexp",
"status": "regexp",
"tags": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
"rpc-addr": "127.0.0.1:7373",
"rpc-auth": "<PASSWORD>",
"rpc-timeout": 1000,
"templates": [
{
"src": "/path/to/template.tpl",
"dest": "/path/to/result.file",
"cmd": "service dummy restart"
},
{
"src": "/path/to/src.file",
"dest": "/path/to/dest.file",
"cmd": "service dummier restart",
}
]
}
## Template File
Serf Template consumes template files in [Go Template][] format. Template files are rendered with a list of members with `Name`, `Addr`, `Port`, `Tags` and `Status`.
Member structure example:
{
"name": "web-1",
"addr": "172.16.0.21",
"port": 7946,
"tags": {
"webport": "8080",
"app": "nginx",
"role": "web"
},
"status": "failed",
}
Template file example:
{{ range . }}{{ if eq .Status "alive" }}
server {{.Name}} at {{.Addr}} with serf at {{.Port}} and {{.Tags.app}} at {{.Tags.webport}}
{{ end }}{{ end }}
The above template file would produce a file like this:
server web-1 at 172.16.0.21 with serf at 7946 and nginx at 8080
server web-2 at 172.16.0.22 with serf at 7946 and nginx at 8080
server web-3 at 172.16.0.23 with serf at 7946 and httpd at 80
[Go Template]: http://golang.org/pkg/text/template/ "Go Template"
<file_sep>/main.go
package main
import (
//"encoding/json"
"errors"
//"fmt"
"os"
"os/exec"
//"strconv"
rpc "github.com/hashicorp/serf/client"
"log"
"strings"
//"text/template"
)
// exit codes
/*
const (
OK = iota
SYNTAX_ERROR = iota
CMD_FAILED = iota
TEMPLATE_PARSE_FAILED = iota
)
*/
const (
DEBUG = false
DEBUG_FILE = "/tmp/serf_template.log"
)
const (
BUFFER_SIZE = 16
)
func main() {
if DEBUG {
log_file, _ := os.Create(DEBUG_FILE)
defer log_file.Close()
log.SetOutput(log_file)
log.Println("Serf Template starting")
}
if len(os.Args) != 2 {
err := errors.New("No config file")
panic(err)
}
// parse directive from config file
directives, err := ParseDirectives(os.Args[1])
if err != nil {
panic(err)
}
if DEBUG {
log.Printf("directives: %s", directives)
}
// create RPC config
rpc_config := rpc.Config{
Addr: directives.Rpc_addr,
AuthKey: directives.Rpc_auth,
Timeout: directives.Rpc_timeout,
}
// create connection to the RPC interface
rpc_client, err := rpc.ClientFromConfig(&rpc_config)
if err != nil {
panic(err)
}
defer rpc_client.Close()
// create input channel
ch := make(chan map[string]interface{}, BUFFER_SIZE)
_, err = rpc_client.Stream("member-join,member-failed,member-update,member-leave,member-reap", ch)
if err != nil {
panic(err)
}
for {
// wait for signal from serf
<-ch
// get members' information
members, err := rpc_client.MembersFiltered(directives.Tags, directives.Status, directives.Name)
if err != nil {
panic(err)
}
// for each templates:
// - render template
// - execute command if any
for i := 0; i < len(directives.Templates); i++ {
RenderTemplate(directives.Templates[i].Src, directives.Templates[i].Dest, members)
if directives.Templates[i].Cmd != "" {
cmd_args := strings.Split(directives.Templates[i].Cmd, " ")
cmd := exec.Command(cmd_args[0], cmd_args[1:]...)
err := cmd.Run()
if err != nil {
panic(err)
}
}
}
}
}
<file_sep>/template_test.go
package main
import (
"fmt"
rpc "github.com/hashicorp/serf/client"
"io/ioutil"
)
func ExampleRenderTemplate() {
members := []rpc.Member{
{
Name: "web-1",
Addr: []byte{172, 16, 0, 21},
Port: 7946,
Status: "alive",
Tags: map[string]string{
"app": "nginx",
"webport": "8080",
},
},
{
Name: "web-2",
Addr: []byte{172, 16, 0, 22},
Port: 7946,
Status: "alive",
Tags: map[string]string{
"app": "nginx",
"webport": "8080",
},
},
{
Name: "web-3",
Addr: []byte{172, 16, 0, 23},
Port: 7946,
Status: "alive",
Tags: map[string]string{
"app": "httpd",
"webport": "80",
},
},
}
RenderTemplate("test/template_1.tpl", "test/result_1.txt", members)
out, err := ioutil.ReadFile("test/result_1.txt")
if err != nil {
panic(err)
}
fmt.Println(string(out))
// Output:
// BEGIN
// server web-1 at 172.16.0.21 with serf at 7946 and nginx at 8080
// server web-2 at 172.16.0.22 with serf at 7946 and nginx at 8080
// server web-3 at 172.16.0.23 with serf at 7946 and httpd at 80
//
// END
}
<file_sep>/directive.go
package main
import (
"encoding/json"
"io/ioutil"
"time"
)
type Template struct {
Src string
Dest string
Cmd string
}
type Directive struct {
Serf string
Name string
Role string
Status string
Tags map[string]string
Rpc_addr string `json:"rpc-addr"`
Rpc_auth string `json:"rpc-auth"`
Rpc_timeout time.Duration `json:"rpc-timeout"`
Templates []Template
}
func ParseDirectives(config_file string) (Directive, error) {
config_json, err := ioutil.ReadFile(config_file)
if err != nil {
panic(err)
}
var directive Directive
err = json.Unmarshal(config_json, &directive)
if err != nil {
panic(err)
}
// default RPC address
if directive.Rpc_addr == "" {
directive.Rpc_addr = "127.0.0.1:7373"
}
// timeout in millisecond. time.Duration use nanosecond by default
directive.Rpc_timeout = directive.Rpc_timeout * 1000000
return directive, nil
}
<file_sep>/directive_test.go
package main
import (
//"testing"
"fmt"
)
func ExampleParseDirectives() {
var d Directive
var e error
// example 1: no config
d, e = ParseDirectives("test/config_1.json")
if e != nil {
panic(e)
}
fmt.Println(d)
// example 2: full config
d, e = ParseDirectives("test/config_2.json")
if e != nil {
panic(e)
}
fmt.Println(d.Serf)
fmt.Println(d.Name)
fmt.Println(d.Role)
fmt.Println(d.Status)
fmt.Println(len(d.Tags))
fmt.Println(d.Tags["app"])
fmt.Println(d.Tags["port"])
fmt.Println(d.Rpc_addr)
fmt.Println(d.Rpc_auth)
fmt.Println(d.Rpc_timeout)
fmt.Println(d.Templates[0].Src)
fmt.Println(d.Templates[0].Dest)
fmt.Println(d.Templates[0].Cmd)
// Output:
// { map[] 127.0.0.1:7373 0 []}
// serf
// svr
// web
// alive
// 2
// a1
// 80
// 127.0.0.1:7373
// rpcauthtoken
// 500ms
// /path/to/template.tpl
// /path/to/result.file
// service dummy restart
}
| cfd06ad2ed992d3791f9bc7d0935c19bde161028 | [
"Markdown",
"Go"
] | 6 | Go | phamhongviet/serf-template | ca22b5f4a7a35001e31abf47346a3516973ef562 | 93ff96a843682990e1545f162bc94d6ccbe067d5 |
refs/heads/master | <repo_name>sakky16/fragment-tutorial<file_sep>/EPC_task_android/app/src/main/java/com/trisysit/epc_task_android/database/Task.java
package com.trisysit.epc_task_android.database;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
/**
* Created by trisys on 7/2/18.
*/
@Entity
public class Task {
String taskId;
String comment;
String priority;
String subject;
@Id
String mobileId;
long taskCreatedDate;
String taskFor;
String taskStatus;
long taskUpdatedDate;
String assignedTo;
String assignedToName;
String taskCreatedBy;
String taskUpdatedBy;
long taskStartDate;
long taskEndDate;
String status;
String taskEffort;
long taskActualStartDate;
long taskActualEndDate;
String taskActualEffort;
String parentTaskId;
String projectId;
String categoryId;
@Generated(hash = 1082595286)
public Task(String taskId, String comment, String priority, String subject,
String mobileId, long taskCreatedDate, String taskFor,
String taskStatus, long taskUpdatedDate, String assignedTo,
String assignedToName, String taskCreatedBy, String taskUpdatedBy,
long taskStartDate, long taskEndDate, String status, String taskEffort,
long taskActualStartDate, long taskActualEndDate,
String taskActualEffort, String parentTaskId, String projectId,
String categoryId) {
this.taskId = taskId;
this.comment = comment;
this.priority = priority;
this.subject = subject;
this.mobileId = mobileId;
this.taskCreatedDate = taskCreatedDate;
this.taskFor = taskFor;
this.taskStatus = taskStatus;
this.taskUpdatedDate = taskUpdatedDate;
this.assignedTo = assignedTo;
this.assignedToName = assignedToName;
this.taskCreatedBy = taskCreatedBy;
this.taskUpdatedBy = taskUpdatedBy;
this.taskStartDate = taskStartDate;
this.taskEndDate = taskEndDate;
this.status = status;
this.taskEffort = taskEffort;
this.taskActualStartDate = taskActualStartDate;
this.taskActualEndDate = taskActualEndDate;
this.taskActualEffort = taskActualEffort;
this.parentTaskId = parentTaskId;
this.projectId = projectId;
this.categoryId = categoryId;
}
@Generated(hash = 733837707)
public Task() {
}
public String getTaskId() {
return this.taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getPriority() {
return this.priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getSubject() {
return this.subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMobileId() {
return this.mobileId;
}
public void setMobileId(String mobileId) {
this.mobileId = mobileId;
}
public long getTaskCreatedDate() {
return this.taskCreatedDate;
}
public void setTaskCreatedDate(long taskCreatedDate) {
this.taskCreatedDate = taskCreatedDate;
}
public String getTaskFor() {
return this.taskFor;
}
public void setTaskFor(String taskFor) {
this.taskFor = taskFor;
}
public String getTaskStatus() {
return this.taskStatus;
}
public void setTaskStatus(String taskStatus) {
this.taskStatus = taskStatus;
}
public long getTaskUpdatedDate() {
return this.taskUpdatedDate;
}
public void setTaskUpdatedDate(long taskUpdatedDate) {
this.taskUpdatedDate = taskUpdatedDate;
}
public String getAssignedTo() {
return this.assignedTo;
}
public void setAssignedTo(String assignedTo) {
this.assignedTo = assignedTo;
}
public String getAssignedToName() {
return this.assignedToName;
}
public void setAssignedToName(String assignedToName) {
this.assignedToName = assignedToName;
}
public String getTaskCreatedBy() {
return this.taskCreatedBy;
}
public void setTaskCreatedBy(String taskCreatedBy) {
this.taskCreatedBy = taskCreatedBy;
}
public String getTaskUpdatedBy() {
return this.taskUpdatedBy;
}
public void setTaskUpdatedBy(String taskUpdatedBy) {
this.taskUpdatedBy = taskUpdatedBy;
}
public long getTaskStartDate() {
return this.taskStartDate;
}
public void setTaskStartDate(long taskStartDate) {
this.taskStartDate = taskStartDate;
}
public long getTaskEndDate() {
return this.taskEndDate;
}
public void setTaskEndDate(long taskEndDate) {
this.taskEndDate = taskEndDate;
}
public String getTaskEffort() {
return this.taskEffort;
}
public void setTaskEffort(String taskEffort) {
this.taskEffort = taskEffort;
}
public long getTaskActualStartDate() {
return this.taskActualStartDate;
}
public void setTaskActualStartDate(long taskActualStartDate) {
this.taskActualStartDate = taskActualStartDate;
}
public long getTaskActualEndDate() {
return this.taskActualEndDate;
}
public void setTaskActualEndDate(long taskActualEndDate) {
this.taskActualEndDate = taskActualEndDate;
}
public String getTaskActualEffort() {
return this.taskActualEffort;
}
public void setTaskActualEffort(String taskActualEffort) {
this.taskActualEffort = taskActualEffort;
}
public String getParentTaskId() {
return this.parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
public String getProjectId() {
return this.projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getCategoryId() {
return this.categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
}
<file_sep>/EPC_task_android/app/src/main/java/com/trisysit/epc_task_android/activity/SplashScreenActivity.java
package com.trisysit.epc_task_android.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.trisysit.epc_task_android.EPCTaskUpdateAppication;
import com.trisysit.epc_task_android.R;
import com.trisysit.epc_task_android.utils.SharedPrefHelper;
import java.util.Timer;
import java.util.TimerTask;
public class SplashScreenActivity extends AppCompatActivity {
private SharedPrefHelper sharedPrefHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
sharedPrefHelper = SharedPrefHelper.getInstance(EPCTaskUpdateAppication.getContext());
String token = sharedPrefHelper.getFromSharedPrefs(SharedPrefHelper.TOKEN);
if (token != null && (!token.equalsIgnoreCase(""))) {
Intent intent = new Intent(SplashScreenActivity.this, TaskUpdateActivity.class);
startActivity(intent);
finish();
} else {
showScreen();
}
}
private void showScreen() {
TimerTask task = new TimerTask() {
@Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
};
Timer t = new Timer();
t.schedule(task, 5000);
}
}
<file_sep>/app/src/main/java/com/example/saikat/fragmentdemo/Communicator.java
package com.example.saikat.fragmentdemo;
/**
* Created by trisys on 25/11/17.
*/
public interface Communicator {
public void respond(String data);
}
<file_sep>/app/src/main/java/com/example/saikat/fragmentdemo/MainActivity.java
package com.example.saikat.fragmentdemo;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.saikat.fragmentdemo.fragment.FragmentA;
import com.example.saikat.fragmentdemo.fragment.FragmentB;
public class MainActivity extends AppCompatActivity implements Communicator {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void respond(String data) {
FragmentManager manager=getFragmentManager();
FragmentB fragmentB=(FragmentB)manager.findFragmentById(R.id.fragment2);
fragmentB.onChange(data);
}
}
<file_sep>/EPC_task_android/app/src/main/java/com/trisysit/epc_task_android/serverModel/LoginRequestModel.java
package com.trisysit.epc_task_android.serverModel;
/**
* Created by trisys on 6/2/18.
*/
public class LoginRequestModel {
String username;
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<file_sep>/EPC_task_android/app/src/main/java/com/trisysit/epc_task_android/utils/NetworkUpdateReceiver.java
package com.trisysit.epc_task_android.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by trisys on 7/2/18.
*/
public class NetworkUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager=(ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
NetworkInfo mobileNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(activeNetworkInfo!=null){
}
else if(mobileNetInfo!=null){
}
else {
AfterNetworkSyncManager manager=new AfterNetworkSyncManager(context);
manager.syncAllData();
}
}
}
<file_sep>/EPC_task_android/app/src/main/java/com/trisysit/epc_task_android/activity/LoginActivity.java
package com.trisysit.epc_task_android.activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;
import com.trisysit.epc_task_android.BuildConfig;
import com.trisysit.epc_task_android.EPCTaskUpdateAppication;
import com.trisysit.epc_task_android.R;
import com.trisysit.epc_task_android.serverModel.LoginDataModel;
import com.trisysit.epc_task_android.serverModel.LoginRequestModel;
import com.trisysit.epc_task_android.serverModel.LoginResponseModel;
import com.trisysit.epc_task_android.utils.AppUtils;
import com.trisysit.epc_task_android.utils.NetworkUtils;
import com.trisysit.epc_task_android.utils.SharedPrefHelper;
import com.trisysit.epc_task_android.utils.SyncApiClass;
import java.util.concurrent.TimeUnit;
import dmax.dialog.SpotsDialog;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class LoginActivity extends AppCompatActivity {
private EditText usernameET, passwordET;
private Button loginBT;
private SharedPrefHelper sharedPrefHelper;
private ProgressDialog progressDialog;
private AlertDialog dialog;
private ScrollView scrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPrefHelper = SharedPrefHelper.getInstance(EPCTaskUpdateAppication.getContext());
getWIdgets();
setListener();
}
private void getWIdgets() {
usernameET = (EditText) findViewById(R.id.username_et);
passwordET = (EditText) findViewById(R.id.password_et);
loginBT = (Button) findViewById(R.id.login_bt);
scrollView = (ScrollView) findViewById(R.id.scrollView);
}
private boolean applyValidations() {
String userName = usernameET.getText().toString();
String password = passwordET.getText().toString();
if (userName.equals("")) {
Toast.makeText(LoginActivity.this, "Username should not be empty", Toast.LENGTH_LONG).show();
return false;
} else if (password.equals("")) {
Toast.makeText(LoginActivity.this, "Password should not be empty", Toast.LENGTH_LONG).show();
return false;
} else {
return true;
}
}
private void setListener() {
loginBT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (applyValidations()) {
if (AppUtils.isOnline(LoginActivity.this)) {
String encodedPassword = "";
String password = <PASSWORD>ET.getText().toString();
try {
byte[] encoded = password.getBytes("UTF-8");
encodedPassword = Base64.encodeToString(encoded, Base64.DEFAULT);
String password1 = encodedPassword.replace("\n", "");
callLoginApi(usernameET.getText().toString(), password1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(LoginActivity.this, getString(R.string.no_internet_msg), Toast.LENGTH_SHORT).show();
}
}
}
});
passwordET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
scrolUpScrollView();
}
});
}
private void scrolUpScrollView() {
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
View lastChild = scrollView.getChildAt(scrollView.getChildCount() - 1);
int bottom = lastChild.getBottom() + scrollView.getPaddingBottom();
int sy = scrollView.getScrollY();
int sh = scrollView.getHeight();
int delta = bottom - (sy + sh);
scrollView.smoothScrollBy(0, delta);
}
}, 200);
}
private void callLoginApi(String userName, String encodedPassword) {
LoginRequestModel model = new LoginRequestModel();
model.setUsername(userName);
model.setPassword(<PASSWORD>);
HttpLoggingInterceptor interceptor = null;
OkHttpClient.Builder client = new OkHttpClient.Builder()
.connectTimeout(45, TimeUnit.SECONDS)
.readTimeout(45, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.addInterceptor(interceptor);
}
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(NetworkUtils.SERVER_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
SyncApiClass apiClass = retrofit.create(SyncApiClass.class);
Call<LoginResponseModel> responseCall = apiClass.loginApi(model);
showProgress();
responseCall.enqueue(new Callback<LoginResponseModel>() {
@Override
public void onResponse(Call<LoginResponseModel> call, Response<LoginResponseModel> response) {
if (response.code() == 200) {
if (response.body().getStatus().equalsIgnoreCase("200")) {
Log.d("Userlogin", "loginSuccess");
LoginDataModel dataModel = response.body().getData();
sharedPrefHelper.saveInSharedPrefs(SharedPrefHelper.TOKEN, dataModel.getToken());
sharedPrefHelper.saveInSharedPrefs(SharedPrefHelper.NAME, dataModel.getFirstName() + " " + dataModel.getLastName());
AppUtils.hideSoftKeyboard(LoginActivity.this);
Intent intent = new Intent(LoginActivity.this, TaskUpdateActivity.class);
startActivity(intent);
finish();
}
Toast.makeText(LoginActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, getString(R.string.server_connection_error_msg), Toast.LENGTH_SHORT).show();
}
dismissProgress();
}
@Override
public void onFailure(Call<LoginResponseModel> call, Throwable t) {
String error = "";
if (call != null) {
error = call.toString();
}
dismissProgress();
Log.i("Error in image upload", error);
}
});
}
private void showProgress() {
dialog = new SpotsDialog(LoginActivity.this, getString(R.string.please_wait_msg), R.style.Custom);
dialog.setCancelable(false);
dialog.show();
}
public void dismissProgress() {
if (dialog != null) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
<file_sep>/EPC_task_android/app/src/main/java/com/trisysit/epc_task_android/EPCTaskUpdateAppication.java
package com.trisysit.epc_task_android;
import android.content.Context;
import android.support.multidex.MultiDexApplication;
/**
* Created by trisys on 6/2/18.
*/
public class EPCTaskUpdateAppication extends MultiDexApplication {
private static Context applicationContext;
public static Context getContext() {
return applicationContext;
}
@Override
public void onCreate() {
super.onCreate();
//Fabric.with(this, new Crashlytics());
//String userName= SharedPrefHelper.getInstance(this).getFromSharedPrefs(SharedPrefHelper.USERNAME);
//Crashlytics.setUserIdentifier(userName);
if (applicationContext == null) {
applicationContext = this;
}
}
}
<file_sep>/EPC_task_android/app/src/main/java/com/trisysit/epc_task_android/utils/AfterNetworkSyncManager.java
package com.trisysit.epc_task_android.utils;
import android.content.Context;
/**
* Created by trisys on 7/2/18.
*/
public class AfterNetworkSyncManager {
Context context;
SharedPrefHelper sharedPrefHelper;
public AfterNetworkSyncManager(Context context){
this.context=context;
sharedPrefHelper=SharedPrefHelper.getInstance(context);
}
public void syncAllData(){
}
}
<file_sep>/EPC_task_android/settings.gradle
include ':app', ':drawerLib'
| 9d12ea7406d2d75996e424d37566aa9421eaa352 | [
"Java",
"Gradle"
] | 10 | Java | sakky16/fragment-tutorial | 50b12d6aca3d21476ece4a3a06fd34df60563a52 | d8d744b0ac34ecd34ddfdf8a19c97f97ac4bfc1d |
refs/heads/main | <repo_name>ThabetSabha/firebase-login<file_sep>/src/components/create-user-form/create-user-form.component.jsx
import React, { useState } from "react";
import "./create-user-form.styles.scss";
//Components
import FormInput from "../form-input/form-input.component";
import CustomButton from "../custom-button/custom-button.component";
const CreateUserForm = () => {
const [userCredentials, setUserCredentials] = useState({
email: "",
password: "",
username: "",
mobileNumber: "",
companyName: "",
companyType: "",
});
const [isError, setIsError] = useState(null);
const {
email,
password,
mobileNumber,
companyName,
companyType,
username,
} = userCredentials;
const handleSubmit = (event) => {
event.preventDefault();
};
const handleChange = (event) => {
const { value, name } = event.target;
setUserCredentials({ ...userCredentials, [name]: value });
};
return (
<div className="create-user-container">
<div className="create-user">
<h2>Create a new user here</h2>
<form onSubmit={handleSubmit}>
<FormInput
name="username"
type="username"
value={username}
handleChange={handleChange}
label="Username"
required
/>
<FormInput
name="email"
type="email"
handleChange={handleChange}
value={email}
label="Email"
required
/>
<FormInput
name="password"
type="password"
value={password}
handleChange={handleChange}
label="Password"
required
/>
<FormInput
name="mobileNumber"
type="mobileNumber"
value={mobileNumber}
handleChange={handleChange}
label="Mobile Number"
required
/>
<FormInput
name="companyName"
type="companyName"
value={companyName}
handleChange={handleChange}
label="Company Name"
required
/>
<FormInput
name="companyType"
type="companyType"
value={companyType}
handleChange={handleChange}
label="Company Type"
required
/>
{isError !== null ? (
<span className="error-span">{isError.message}</span>
) : (
<span className="error-span" />
)}
<div className="buttons">
<CustomButton type="submit"> Create User </CustomButton>
</div>
</form>
</div>
</div>
);
};
export default CreateUserForm;
<file_sep>/src/App.js
/* eslint-disable react-hooks/exhaustive-deps */
import { useState, useEffect } from "react";
import { Route, Switch, Redirect } from "react-router";
import "./App.scss";
import SignIn from "./components/sign-in/sign-in.component";
import CreateUserForm from "./components/create-user-form/create-user-form.component";
import Spinner from "./components/spinner/spinner.component";
import Header from "./components/header/header.component";
import {
auth,
getCurrentUser,
createUserProfileDocument,
} from "./firebase/firebase.utils";
function App() {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(null);
// Checks if a user is already logged in to firebase, then changes the loading state to false
const checkUserSession = async () => {
try {
const userAuth = await getCurrentUser();
if (!userAuth) {
setIsLoading(false);
return;
}
await getUserSnapshotFromUserAuthAndSignIn(userAuth);
} catch (error) {
console.log(error);
setIsLoading(false);
}
};
const signInWithEmail = async (email, password) => {
try {
const { user } = await auth.signInWithEmailAndPassword(email, password);
setIsLoading(true);
await getUserSnapshotFromUserAuthAndSignIn(user);
setIsError(null);
} catch (error) {
console.log(error);
setIsError(error);
}
};
// Checks if the provided info is valid, if so signs the user in, and loads it into state.
const getUserSnapshotFromUserAuthAndSignIn = async (userAuth) => {
try {
const userRef = await createUserProfileDocument(userAuth);
const userSnapshot = await userRef.get();
setUser({
id: userSnapshot.id,
...userSnapshot.data(),
});
setIsLoading(false);
setIsError(null);
} catch (error) {
console.log(error);
setIsError(error);
setIsLoading(false);
}
};
// Sign user out of firebase.
const signOut = async () => {
try {
await auth.signOut();
setUser(null);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
setIsLoading(true);
checkUserSession();
}, []);
return (
<>
{isLoading ? (
<Spinner />
) : (
<>
<Header signOut={signOut} user={user} />
<Switch>
<Route
exact
path="/signin"
render={() =>
user ? (
<Redirect to="/" />
) : (
<SignIn signInWithEmail={signInWithEmail} isError={isError} />
)
}
/>
<Route
path="/"
render={() =>
user === null ? <Redirect to="/signin" /> : <CreateUserForm />
}
/>
</Switch>
</>
)}
</>
);
}
export default App;
| b6ba92dd5a333e552f0396948c51d95e8f6b945f | [
"JavaScript"
] | 2 | JavaScript | ThabetSabha/firebase-login | 22d0435868d1ece81db8cb384d94c79a9b19e333 | 4abe1dcab405996011b0c64437e3749a1274ccd1 |
refs/heads/master | <file_sep>package pl.sda.db;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.AssertionsForClassTypes.*;
import static org.junit.jupiter.api.Assertions.assertAll;
public class DatabaseTest {
@Test
public void testAddUser() {
// given
User user = new User("login", "<PASSWORD>");
User user1 = new User("login1", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
users.add(user1);
Database database = new Database();
// when
database.addUser(user);
database.addUser(user1);
// then
assertThat(database.findAll().size())
.as("Should be 2")
.isEqualTo(2);
}
@Test(expected = UserExistsException.class)
public void testAddUserAlreadyThere() {
// given
User user = new User("login", "<PASSWORD>");
User user1 = new User("login1", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
users.add(user1);
Database database = new Database(users);
// when
database.addUser(user);
}
@Test
public void testFindAll() {
// given
User user = new User("login", "<PASSWORD>");
User user1 = new User("login1", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
users.add(user1);
int sizeBefore = users.size();
Database database = new Database(users);
// when
List<User> userList = database.findAll();
// then
assertAll(
() -> assertThat(userList.size())
.isEqualTo(2),
() -> assertThat(userList.contains(user))
.isEqualTo(true),
() -> assertThat(userList.contains(user1))
.isEqualTo(true),
() -> assertThat(userList.get(0).getLogin())
.isEqualTo("login"),
() -> assertThat(userList.get(0).getPassword())
.isEqualTo("<PASSWORD>"),
() -> assertThat(userList.get(1).getLogin())
.isEqualTo("login1"),
() -> assertThat(userList.get(1).getPassword())
.isEqualTo("<PASSWORD>")
);
}
@Test
public void testRemoveUser() {
// given
User user = new User("login", "<PASSWORD>");
User user1 = new User("login1", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
users.add(user1);
int sizeBefore = users.size();
Database database = new Database(users);
// when
User removedUser = user;
database.removeUser(removedUser.getLogin());
int size = database.findAll().size();
// then
assertThat(removedUser.getLogin())
.isEqualTo("login");
assertThat(removedUser.getPassword())
.isEqualTo("<PASSWORD>");
assertThat(size)
.isEqualTo(sizeBefore - 1);
}
@Test(expected = UserNotFoundException.class)
public void testRemoveUserNoUserFound() {
// given
User user = new User("login", "<PASSWORD>");
User user1 = new User("login1", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
users.add(user1);
int sizeBefore = users.size();
Database database = new Database(users);
// when
database.removeUser("login2");
}
@Test
public void testFindUser() {
// given
User user = new User("login", "password");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
User foundUser = database.findUser(user.getLogin());
int size = users.size();
// then
assertThat(foundUser.getLogin())
.as("should be login")
.isEqualTo(user.getLogin());
assertThat(foundUser.getPassword())
.as("should be password")
.isEqualTo(user.getPassword());
assertThat(size)
.as("should be 1")
.isEqualTo(1);
}
@Test(expected = UserNotFoundException.class)
public void testFindUserNoUserFound() {
// given
User user = new User("login", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
database.findUser("login1");
}
@Test
public void testFindByPartOfLoginE() {
// given
User user = new User("login", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
User foundUser = database.findByPartOfLogin("in");
// then
assertThat(foundUser)
.isEqualToComparingFieldByField(user);
}
@Test(expected = UserNotFoundException.class)
public void testFindByPartOfLoginENoUser() {
// given
User user = new User("login", "password");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
database.findByPartOfLogin("ing");
}
@Test
public void testFindByPartOfLoginB() {
// given
User user = new User("login", "password");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
User foundUser = database.findByPartOfLogin("lo");
// then
assertThat(foundUser)
.isEqualToComparingFieldByField(user);
}
@Test(expected = UserNotFoundException.class)
public void testFindByPartOfLoginBNoUser() {
// given
User user = new User("login", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
database.findByPartOfLogin("ad");
}
@Test
public void testFindByPartOfLoginM() {
// given
User user = new User("login", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
User foundUser = database.findByPartOfLogin("gi");
// then
assertThat(foundUser)
.isEqualToComparingFieldByField(user);
}
@Test(expected = UserNotFoundException.class)
public void testFindByPartOfLoginMNoUser() {
// given
User user = new User("login", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
database.findByPartOfLogin("dmi");
}
@Test
public void testModifyUser() {
// given
User user = new User("login", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
database.modifyUser(user.getLogin(), "newLogin");
// then
assertThat(user.getLogin())
.isEqualTo("newLogin");
}
@Test(expected = UserNotFoundException.class)
public void testModifyUserNoUser() {
// given
User user = new User("login", "<PASSWORD>");
List<User> users = new ArrayList<>();
users.add(user);
Database database = new Database(users);
// when
database.modifyUser("login1", "newLogin");
}
}<file_sep>package pl.sda.db;
class UserExistsException extends RuntimeException {
public UserExistsException(String message) {
super(message);
}
}
<file_sep>package pl.sda.air;
public class Airplane {
final static int LIMIT = 1000000;
private final String name;
private int height;
public Airplane(String name, int height) {
if (height >= 0 && height <= LIMIT) {
this.height = height;
} else if (height < 0) {
this.height = 0;
} else {
this.height = LIMIT;
}
this.name = name;
}
public void ascent(int value) {
if (value + this.height < 0) {
this.height = 0;
} else {
this.height = Math.min(value + this.height, LIMIT);
}
}
public void descent(int value) {
// alt + enter on ? to replace with a normal if
if (this.height - value > LIMIT) {
this.height = LIMIT;
} else {
this.height = value <= this.height ? this.height - value : 0;
}
}
public String getName() {
return name;
}
public int getHeight() {
return height;
}
}
<file_sep>package pl.sda.calc;
import java.util.Arrays;
public class Calculator { // ctrl + shift + t - creates a test
public double add(double a, double b) {
return a + b;
}
public double subtract(double a, double b) {
return a - b;
}
public double multiple(double a, double b) {
return a * b;
}
public double divide(double a, double b) {
if (b == 0) {
throw new IllegalArgumentException("One cannot divide by zero!");
}
return a / b;
}
public double power(double a, double b) {
return Math.pow(a, b);
}
public double root(double a) {
if (a < 0) {
throw new IllegalArgumentException("No complex numbers allowed, ur number must be > 0");
}
return Math.sqrt(a);
}
public boolean isDividable(double a, double b) {
if (a % b == 0) {
return true;
} else {
return false;
}
}
public double sumArrayOfNumbers(double... numbers) {
double sum = Arrays.stream(numbers)
.sum();
return sum;
}
}
| 942bf047efc79a6f508a5786003e57d658b4b9f4 | [
"Java"
] | 4 | Java | 19Pawel97/Testing.java | 47f2233555b258a5f1c40f51b57b1922c9c082d8 | 48bea2a25ebddbad72c86d871f2914d586e01eda |
refs/heads/master | <repo_name>ianschmutte/cbp_imputations<file_sep>/cbputils.py
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 14:03:25 2020
@author: manav
"""
import numpy as np, pandas as pd
import re, sys
#Clean data and prepare bounds
def cbp_clean(data_input, geo):
data_input.columns = map(str.lower, data_input.columns)
data_input['empflag'] = data_input['empflag'].astype(str)
data_input.loc[data_input.empflag == ".", 'empflag'] = ""
if 'lfo' in data_input.columns:
data_input = data_input[data_input.lfo == '-']
if 'naics' in data_input.columns:
data_input = data_input.rename(columns={"naics": "ind"})
elif 'sic' in data_input.columns:
data_input = data_input.rename(columns={"sic": "ind"})
data_input['lb'] = data_input['empflag']
data_input['ub'] = data_input['empflag']
data_input['lb'] = data_input['lb'].replace({'A':0,'B':20,'C':100,'E':250,'F':500,'G':1000,'H':2500,'I':5000,'J':10000,'K':25000,'L':50000,'M':100000})
data_input['ub'] = data_input['ub'].replace({'A':19,'B':99,'C':249,'E':499,'F':999,'G':2499,'H':4999,'I':9999,'J':24999,'K':49999,'L':99999,'M':100000000})
data_input[['lb','ub']] = data_input[['lb','ub']].apply(pd.to_numeric, errors='coerce')
data_input.loc[np.isnan(data_input.lb), {'ub','lb'}] = data_input.loc[np.isnan(data_input.lb), 'emp']
if geo == "us":
data_input = data_input[['ind','lb','ub']]
elif geo == "st":
data_input = data_input[['fipstate','ind','lb','ub']]
elif geo == "co":
data_input = data_input[['fipstate','fipscty','ind','lb','ub']]
return data_input
def cbp_change_code(data_input, code_old, code_new):
data_helper = data_input.copy()
data_helper = data_helper[data_helper.ind == code_old]
data_helper.loc[data_helper.ind == code_old, 'ind'] = code_new
data_helper.loc[:, 'lb'] = 0
data_input = data_input.append(data_helper, ignore_index=True)
return data_input
#Clean data and prepare bounds
def cbp_drop(data_input, year, geo,codechanger):
ind_drop_set = []
geo_drop_set = [98,99]
if geo == "co" and year in range(1970, 1990):
if year == 1977:
ind_drop_set = ["0785", "2031", "2433", "2442", "3611", "3716", "3791", "3803","3821", "5122", "5129", "6798", "7012", "7013", "8310", "8361"]
if year == 1978:
ind_drop_set = ["0785", "2015", "2433", "2442", "2661", "3611", "3716", "3791", "3803", "3821", "4582", "5129", "6070", "6798", "7012", "7013", "8062", "8084", "8310", "8361", "8411", "8800", "8810"]
if year == 1979:
ind_drop_set = ["0785", "0759", "0785", "079/", "1625", "2036", "2940", "2942", "3073", "3239", "3481", "5212", "5513", "5780", "5781", "5820", "5821", "5991", "6122", "6406", "7012", "7060", "7065", "7328", "7380", "7388", "7626", "7638", "7835", "7912", "7994", "8120", "8126", "8500", "8560", "8562", "8680", "8800", "8810","8811", "3716", "5129", "5192", "6590", "6599", "6798", "7013", "8310", "8361"]
data_helper = data_input.copy()
data_helper = data_helper[data_helper.fipstate == 11]
data_helper = data_helper[data_helper.fipscty == 99]
data_helper.loc[:, 'lb'] = 0
data_helper.loc[:, 'fipscty'] = 1
data_input.append(data_helper, ignore_index=True)
if year == 1980:
ind_drop_set = [ "1629", "64--", "6798", "8310", "8361", "8631"]
if year == 1981:
ind_drop_set = ["1540", "1542", "6798", "8051", "8310", "8361"]
if year == 1982:
ind_drop_set = ["1321", "2771", "8800", "8810", "8811", "3716", "6590", "6599", "6798", "8310", "8361"]
if year == 1983:
ind_drop_set = ["1711", "3716", "4229", "6590", "6599", "6793", "6798", "8310", "8361"]
if year == 1984:
ind_drop_set = ["3716", "4229", "5380", "5580", "6590", "6599", "6798", "8310", "8361"]
if year == 1985:
ind_drop_set = ["3716", "5380", "5580", "6798", "8310", "8361"]
if year == 1986:
ind_drop_set = ["1111", "1481", "1531", "1611", "4131", "4151", "4231", "4411", "4431", "4441", "4712", "4811", "4821", "4899", "4911", "4941", "4961", "4971", "5380", "5580", "5970", "6410", "6610", "7840", "8110", "8361"]
if year == 1987:
ind_drop_set = ["1540", "4214", "5399", "6410", "8320", "8321", "8330", "8331", "8350", "8351", "8390", "8399"]
if year == 1988:
ind_drop_set = ["5399"]
elif geo == "st" and year in range(70, 91):
if year == 1977:
ind_drop_set = ["0785", "2031", "2433", "2442", "3611", "3716", "3791", "3803", "3821", "5129", "6798", "7012", "7013", "8310", "8361"]
if year == 1978:
ind_drop_set = ["3716", "5129", "6070", "6798", "7012", "7013", "8310", "8361", "0785", "2015", "2433", "2442", "3611", "3791", "3803", "3821"]
if year == 1979:
ind_drop_set = ["0759", "0785", "079/", "1625", "2036", "2940", "2942", "3073", "3239", "3481", "3716", "5129", "5192", "5212", "5513", "5780", "5781", "5820", "5821", "5991", "6406", "6590", "6599", "6798", "7012", "7013", "7060", "7065", "7328", "7380", "7388", "7626", "7638", "7835", "7912", "7994", "8120", "8126", "8310", "8361", "8500", "8560", "8562", "8680", "8800", "8810", "8811"]
if year == 1980:
ind_drop_set = ["3716", "6798", "8310", "8361"]
if year == 1981:
ind_drop_set = ["1540", "1542", "6798", "8310", "8361"]
if year == 1982:
ind_drop_set = ["2771", "3716", "6590", "6599", "6798", "8310", "8361", "8800", "8810", "8811"]
if year == 1983:
ind_drop_set = ["3716", "4229", "6590", "6599", "6793", "6798", "8310", "8361"]
if year == 1984:
ind_drop_set = ["3716", "4229", "5380", "5580", "6590", "6599", "6798", "8310", "8361"]
if year == 1985:
ind_drop_set = ["3716", "5380", "5580", "6798", "8310", "8361"]
if year == 1986:
ind_drop_set = ["1111", "1481", "1531", "1611", "4131", "4151", "4231", "4411", "4431", "4441", "4712", "4811", "4821", "4899", "4911", "4941", "4961", "4971", "5380", "5580", "5970", "6410", "6610", "7840", "8110", "8361"]
if year == 1987:
ind_drop_set = ["1540", "4214", "6410", "8320", "8330", "8350", "8390"]
if year == 1988:
ind_drop_set = ["5399"]
if year == 1990:
ind_drop_set = ["8990"]
elif geo == "us" and year in range(1970, 1990):
if year == 1977:
ind_drop_set = ["3716", "5129", "6798", "7012", "7013", "8310", "8361"]
data_input = codechanger(data_input, "40--", "4300")
data_input = codechanger(data_input, "40--", "4310")
data_input = codechanger(data_input, "40--", "4311")
if year == 1978:
ind_drop_set = ["3716", "5129", "6070", "6798", "7012", "7013", "8310", "8361"]
if year == 1979:
ind_drop_set = ["5129", "6590", "6599", "6798", "7013", "8310", "8361"]
data_input = codechanger(data_input, "1090", "1092")
data_input = codechanger(data_input, "6110", "6113")
if year == 1980:
ind_drop_set = ["3761", "6798", "8310", "8361"]
data_input = codechanger(data_input, "1090", "1092")
data_input = codechanger(data_input, "6110", "6113")
if year == 1981:
ind_drop_set = ["6798", "8310", "8361"]
data_input = codechanger(data_input, "6110", "6113")
if year == 1982:
ind_drop_set = ["3716", "6590", "6599", "6798", "8310", "8361"]
data_input = codechanger(data_input, "1090", "1092")
data_input = codechanger(data_input, "6110", "6113")
if year == 1983:
ind_drop_set = ["3716", "4229", "6590", "6599", "6798", "8310", "8361"]
data_input = codechanger(data_input, "3570", "3572")
data_input = codechanger(data_input, "6110", "6113")
if year == 1984:
ind_drop_set = ["3716", "4229", "6590", "6599", "6798", "8310", "8361"]
data_input = codechanger(data_input, "3570", "3572")
data_input = codechanger(data_input, "3670", "3673")
if year == 1985:
ind_drop_set = ["3716", "6798", "8310", "8361"]
data_input = codechanger(data_input, "3570", "3572")
if year == 1986:
ind_drop_set = ["1111", "1481", "1531", "1611", "4131", "4151", "4231", "4411", "4431", "4441", "4712", "4811", "4821", "4899", "4911", "4941", "4961", "4971", "5380", "5580", "5970", "6410", "6610", "7840", "8110", "8361"]
data_input = codechanger(data_input, "3570", "3572")
if year == 1987:
ind_drop_set = ["1110", "1210", "1540", "5399", "6410", "8320", "8321", "8330", "8331", "8350", "8351", "8390", "8399"]
data_input = codechanger(data_input, "1112", "1110")
data_input = codechanger(data_input, "1211", "1210")
data_input = codechanger(data_input, "5800", "5810")
data_input = data_input[~data_input.ind.isin(ind_drop_set)]
if geo == 'co' or geo == 'st':
data_input = data_input[~data_input.fipstate.isin(geo_drop_set)]
data_input.loc[data_input.ind == "19--", 'ind'] = "20--"
data_input.loc[data_input.ind == "--", "ind"] = "07--"
if year == 1997:
data_input = codechanger(data_input, "5800", "5810")
data_input = codechanger(data_input, "2070", "2067")
if year in range(1991, 1997):
data_input = codechanger(data_input, "5800", "5810")
if year in range(1970, 1998):
data_input.ind = data_input.ind.str.replace('/','\\')
return data_input
##Industry Code Files
def indreforder_ind(data_input):
data_input = data_input[['NAICS']]
data_input = data_input.sort_values(by = 'NAICS')
return data_input
##Geography Code Files
def indreforder_geo(data_input):
data_input = data_input[['fipstate','fipscty']]
data_input = data_input.sort_values(by = ['fipstate','fipscty'])
return data_input
<file_sep>/cbp_raw_clean.py
#<NAME> (2019)
#Corresponding Author: <EMAIL>
##Load Packages
import numpy as np, pandas as pd
import re, sys
import fnmatch
import os
##Import Own Packages
import cbp_utils
##Code to prepare CBP data
geolist = ['co','st','us']
# Using for loop
for year in range(1977, 2017):
for geo in geolist:
yl = 'cbp'+str(year)+geo
data = pd.read_csv(root+"/Data Input"+'/'+str(year)+'/'+geo+'/'+yl+'.txt')
data = cbp_utils.cbp_clean(data,geo)
data = cbp_utils.cbp_drop(data, year, geo, cbp_utils.cbp_change_code)
data.to_csv(root+"/Data Process"+'/'+str(year)+'/'+geo+'/'+yl+'_edit.csv',index=False)
print(str(year)+':'+geo+'--done!')
##Code to prepare industry and geo reference files
for year in range(1977, 2017):
os.chdir(root+'/Data Input/'+str(year)+'/ref')
data = []
data1 = []
data2 = []
for file in os.listdir('.'):
if fnmatch.fnmatchcase(file, '*sic*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
data.append(str(myline[0:4]))
df = pd.DataFrame(data, columns=['ind'])
#df = df.drop(df.index[0])
df = df.replace('"','')
df = df.replace(" ","")
df.to_csv(root+"/Data Process"+'/'+str(year)+'/ref/ind_ref_'+str(year)+'.csv', sep='\t',index=False)
elif fnmatch.fnmatchcase(file, '*naics*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
data.append(str(myline[0:6]))
df = pd.DataFrame(data, columns=['ind'])
df = df.replace('"','', regex=True)
df = df.replace(' ','', regex=True)
df = df[df.ind != 'NAICS']
df.to_csv(root+"/Data Process"+'/'+str(year)+'/ref/ind_ref_'+str(year)+'.csv', sep='\t',index=False)
elif fnmatch.fnmatchcase(file, '*geo*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
data1.append(str(myline[1:3]))
data2.append(str(myline[6:9]))
df1 = pd.DataFrame(data1, columns=['fipstate'])
df2 = pd.DataFrame(data2, columns=['fipstate'])
df = pd.concat([df1, df2], axis=1)
df = df.replace('"','', regex=True)
df = df.replace(' ','', regex=True)
df = df.replace(',','', regex=True)
df = df.drop(df.index[0])
df.to_csv(root+"/Data Process"+'/'+str(year)+'/ref/geo_ref_'+str(year)+'.csv', sep='\t',index=False)
<file_sep>/CBPpython.py
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#<NAME> (2019)
#Corresponding Author: <EMAIL>
import pandas as pd
from ast import literal_eval
import sys
import os
'''
This method takes in a preorder traversal of the tree of codes (which could be
NAICS or geographic) and returns a list of dictionaries whose entries
identify the type of code in the node (naics or geo), its code, and its children.
The method takes in three inputs:
1. The tree of codes (which could be NAICS or geographic). The tree should
be given as a preorder traversal
2. A name for the codes: Either 'naics' or 'geo'
3. A level function that, given a code, determines the level of the code
in the directed tree (The level of a node in a directed tree is defined
as 1 + number of edge between the root and the node.).
Outputs dicts -- a list whose entries have the following structure:
tree[index in the preorder traversal] =
{
'name': 'naics' OR 'geo'
'code': code,
'children': a list of indices of its children in the tree
}
'''
def preorderTraversalToTree(preorder_traversal, name, level_function):
dicts=[]
# lineage = [0, index-first-parent, index-second-parent, ....]
lineage = []
for index in range(len(preorder_traversal)):
code = preorder_traversal[index]
# create this code's dictionary
code_dict = {}
code_dict['name'] = name
code_dict[name] = code
code_dict['children'] = []
# find its parent and update the lineage
level = level_function(code)
while(len(lineage) >= level and len(lineage) > 0):
lineage.pop()
if len(lineage) > 0:
parents_dictionary = dicts[lineage[-1]]
parents_dictionary['children'].append(index)
lineage.append(index)
dicts.append(code_dict)
return dicts
# Assumes SIC
def findCorrectionsToTypos(big_df, typos, year, ref_file_name):
industry_codes = newNaicsCodes(ref_file_name, year)
industry_tree = preorderTraversalToTree(industry_codes, 'sic', sic_level)
for typo in typos:
possible_codes = generatePossibleCodes(typo, year, ref_file_name)
# numbers = numberTimesCodeOccurs(typo, year, 0, 0)
# print('\nTypo %s appears %s times in the dataset [national, state, county].' % (typo, numbers))
# for all occurrences of the typo, find codes that will fit the industrial
# tree of that occurence
for index, row in big_df[big_df.sic == typo].iterrows():
st_id = row.fipstate
co_id = row.fipscty
neighborhood = big_df[(big_df.fipstate == st_id) & (big_df.fipscty == co_id)]
for code in possible_codes:
index_possible_code = industry_codes.index(code)
for index_parent, row_parent in neighborhood.iterrows():
if row_parent.sic in industry_codes:
index_in_codes = industry_codes.index(row_parent.sic)
if index_possible_code in industry_tree[index_in_codes]['children']:
print('Found correct code for fipstate %d, fipscty %d, code %s. (possible) right code %s and parent %s' % (st_id, co_id, typo, code, row_parent.sic))
# print(row_parent.naics)
year_before = str(int(year) - 1); year_after = str(int(year) + 1)
print('At the same location, the code %s appears %s times in previous year datasets and %s times in next year datasets\n' % (code, numberTimesCodeOccurs(code, year_before, st_id, co_id), numberTimesCodeOccurs(code, year_after, st_id, co_id)) )
print('')
def generatePossibleCodes(code, year, ref_file_name):
industry_codes = newNaicsCodes(ref_file_name, year)
possible_codes = []
chars = list(range(10))
for index in range(4):
for c in chars:
new_code = code[:index] + str(c) + code[index+1:]
if (new_code in industry_codes) and (new_code not in possible_codes):
possible_codes.append(new_code)
new_code = code[:3] + '\\'
if new_code in industry_codes:
possible_codes.append(new_code)
return possible_codes
def checkNoTimesCodeOccurs(code, year, us, st, co):
numbers = [us[us.sic == code].sic.size, st[st.sic == code].sic.size, co[co.sic == code].sic.size]
if numbers[0] > 0 and numbers[1] > 0 and numbers[2] > 0:
return False
return ((st[st.sic==code].sic.size <= 5) and (co[co.sic==code].sic.size <= 5))
def numberTimesCodeOccurs(code, year, st_id, co_id):
us = pd.read_csv('cbp' + year + 'us_edit.csv')
st = pd.read_csv('cbp' + year + 'st_edit.csv')
co = pd.read_csv('cbp' + year + 'co_edit.csv')
big_df = merge_dataframes(us, st, co)
return big_df[(big_df.fipstate == st_id) & (big_df.fipscty == co_id) & (big_df.sic == code)].index.size
# if int(year) <= 1997:
# return ((st[st.sic==code].sic.size <= 5) and (co[co.sic==code].sic.size <= 5))
# else:
# return ((st[st.naics==code].naics.size <= 5) and (co[co.naics==code].naics.size <= 5))
def typos(year, national_file, state_file, county_file, ref_file_name):
industry_codes = newNaicsCodes(ref_file_name, year)
industry_codes_in_dataset = []
if int(year) <= 1997:
industry_codes_in_dataset = list(national_file.sic.drop_duplicates()) + list(state_file.sic.drop_duplicates()) + list(county_file.sic.drop_duplicates())
else:
industry_codes_in_dataset = list(national_file.sic.drop_duplicates()) + list(state_file.naics.drop_duplicates()) + list(county_file.naics.drop_duplicates())
# find the codes that are in the datasets but not in the ref files
typos = list(filter(lambda x: x not in industry_codes, industry_codes_in_dataset))
# remove codes that appear in every dataset (national, state and county)
typos = list(filter(lambda x: checkNoTimesCodeOccurs(x, year, national_file, state_file, county_file), typos))
# drop duplicates
typos = list(set(typos))
return typos
def sic_level(code):
if code == '----':
return 1
if '-' in code:
return 2
if code[3] == '\\':
return 3
if code[3] == '/':
return 3
if code[2:4] == '00':
return 3
if code[3] == '0':
return 4
return 5
# The level function for naics
def naics_level(code):
# all industries
if code == '------':
return 1
return sum(a.isdigit() for a in code)
# level function for geo
def geo_level(code):
# national
if code[0] == 0:
return 1
# state
if code[1] == 0:
return 2
# county
return 3
def refFileName(year):
return "ind_ref_"+str(year)+".csv"
# return "cbp" + year + "_ind_ref.csv"
# names = {
# 1980: 'sic80.txt',
# 1981: 'sic81.txt',
# 1982: 'sic82.txt',
# 1983: 'sic83.txt',
# 1984: 'sic84.txt',
# 1985: 'sic85.txt',
# 1986: 'sic86_87.txt',
# 1987: 'sic86_87.txt',
# 1988: 'sic88_97.txt',
# 1989: 'sic88_97.txt',
# 1990: 'sic88_97.txt',
# 1991: 'sic88_97.txt',
# 1992: 'sic88_97.txt',
# 1993: 'sic88_97.txt',
# 1994: 'sic88_97.txt',
# 1995: 'sic88_97.txt',
# 1996: 'sic88_97.txt',
# 1997: 'sic88_97.txt',
# 1998: 'naics03.txt',
# 1999: 'naics03.txt',
# 2000: 'naics03.txt',
# 2001: 'naics03.txt',
# 2002: 'naics03.txt',
# 2003: 'naics2002.txt',
# 2004: 'naics2002.txt',
# 2005: 'naics2002.txt',
# 2006: 'naics2002.txt',
# 2007: 'naics2002.txt',
# 2008: 'naics2008.txt',
# 2009: 'naics2009.txt',
# 2010: 'naics2010.txt',
# 2011: 'naics2011.txt',
# 2012: 'naics2012.txt',
# 2013: 'naics2012.txt',
# 2014: 'naics2012.txt',
# 2015: 'naics2012.txt',
# 2016: 'naics2012.txt'
# }
# return names[int(year)]
def newNaicsCodes(ref_file, year):
refs = pd.read_csv(ref_file)
if year <=1997:
return list(refs.ind)
else:
return list(refs.ind)
# produces a list of naics/sic codes that are ordered like a
# preorder tree traversal. takes in the reference file
# industry reference file's NAICS or SIC column are preordered
def naicsCodes(ref_file_name, year, use=''):
naics_codes = []
if year <= 1997:
if year >= 1988:
with open(ref_file_name, 'r') as f:
naics_codes = [line.split(None, 1)[0] for line in f]
elif year >= 1986:
with open(ref_file_name, 'r') as f:
naics_codes = [line.split(None, 1)[0] for line in f]
naics_codes = naics_codes[1:] # the first one is 'SIC', so remove that one
elif year >= 1980:
with open(ref_file_name, 'r') as f:
naics_codes = [line[0:4] for line in f] # first 4 chars are the code
else:
if year <= 2011:
with open(ref_file_name, 'r') as f:
naics_codes = [line.split(None, 1)[0] for line in f]
# remove the first element, which is 'NAICS'
naics_codes = naics_codes[1:]
else:
naics_codes = list(pd.read_csv(ref_file_name).NAICS)
if use != 'typos':
# some codes are unused. if you add them to the naics codes, then you
# have KeyError problems later. so compare them with the national_df
national_df = pd.read_csv('cbp' + str(year) + 'us_edit.csv')
real_naics_codes = []
if year <= 1997:
real_naics_codes = list(national_df['sic'])
else:
real_naics_codes = list(national_df['naics'])
# have to check these codes are actually used in the dataset
naics_codes = list(filter(lambda x: x in real_naics_codes, naics_codes))
# drop duplicated codes but keep order
return sorted(set(naics_codes))
def geoCodes(state_df, county_df):
# Create a preorder traversal of the geo tree
# in list geo_codes
states = state_df.drop_duplicates(['fipstate'])[['fipstate']].values.tolist()
counties = county_df.drop_duplicates(['fipstate', 'fipscty'])[['fipstate','fipscty']]
geo_codes = [(0,0)]
for state in states:
state = state[0]
geo_codes.append((state, 0))
for county in list(counties[counties.fipstate == state].fipscty):
geo_codes.append((state, county))
return geo_codes
def merge_dataframes(national_df, state_df, county_df):
state_df['fipscty'] = 0
national_df['fipscty'] = 0
national_df['fipstate'] = 0
df = pd.concat([national_df,state_df,county_df], sort=True)
df['geo'] = list(zip(df.fipstate, df.fipscty))
return df
# This function submits a query to the data frame and returns a pandas series
# entry is a dictionary with 'geo' representing the geo code (fipstate or 0, fipscty or 0)
# and 'naics' representing the naics code
# It chooses the data frame to search (national, state or county)
# based on the length of the geography argument
def read_df(entry, ub, lb):
geo = entry['geo']
naics = entry['naics']
return (ub[geo][naics], lb[geo][naics])
# write updates the database. it takes in
# 1. the element to be updated (which is a python
# dictionary that includes geo and naics codes for the element)
# 2. bound to be updated
# 3. the new value for the bound
def write_df(entry, bound, new_value, ub, lb):
geo = entry['geo']
naics = entry['naics']
if bound == 'ub':
ub[geo][naics] = new_value
elif bound == 'lb':
lb[geo][naics] = new_value
return (ub, lb)
# merges two python dictionaries
def merge_dict(x,y): return {**x, **y}
# checks if two lists of pandas dataframes contain equivalent data frames
def equalListDataFrames(list1, list2):
for index in range(len(list1)):
if list1[index].equals(list2[index]) == False:
return False
return True
# take str of tuple and return the tuple
def strToTuple(tuple_str):
tuple_list = tuple_str.replace('(',')').replace(')',',').split(',')
tuple_list = list(filter(lambda x: x!='', tuple_list))
return (int(tuple_list[0]), int(tuple_list[1]))
def splitBigDataFrame(big_df, year):
# from 'geo' create 'fipstate' and 'fipscty'
big_df[['fipstate', 'fipscty']] = pd.DataFrame(big_df['geo'].tolist(), index = big_df.index)
big_df = big_df.drop(['geo'], axis = 1)
big_df = big_df[['naics', 'fipstate', 'fipscty', 'ub', 'lb']]
# pull national df from big df
us = big_df.loc[(big_df['fipstate'] == 0)]
# drop unnecessary columns
us = us[['naics', 'lb', 'ub']]
# pull state df from big df and merge missing values
st = big_df.loc[(big_df['fipstate'] != 0) & (big_df['fipscty'] == 0)]
original_st = pd.read_csv('cbp' + year + 'st_edit.csv')
original_st = original_st.rename(index=str, columns={'sic': 'naics'})
original_st['fipscty'] = 0
st = pd.merge(st, original_st, on=['naics', 'fipstate', 'fipscty'], how='outer').fillna(0)
# rename columns
st = st.rename(index=str, columns={"ub_x": "ub", "lb_x": "lb"})
# change dtype from float to int
st.ub = st.ub.astype(int)
st.lb = st.lb.astype(int)
# drop unnecessary columns like fipscty
st = st[['fipstate', 'naics', 'lb', 'ub']]
st = st.sort_values(by=['fipstate'])
# oull county df from big df and merge missing values
co = big_df.loc[(big_df['fipstate'] != 0) & (big_df['fipscty'] != 0)]
original_co = pd.read_csv('cbp' + year + 'co_edit.csv')
original_co = original_co.rename(index=str, columns={'sic': 'naics'})
co = pd.merge(co, original_co, on=['naics', 'fipstate', 'fipscty'], how='outer').fillna(0)
# rename columns
co = co.rename(index=str, columns={"ub_x": "ub", "lb_x": "lb"})
# change datatype from float to int
co.ub = co.ub.astype(int)
co.lb = co.lb.astype(int)
# drop unnecessary columns
co = co[['fipstate', 'fipscty', 'naics', 'lb', 'ub']]
co = co.sort_values(by=['fipstate', 'fipscty'])
return (us, st, co)
def matrixToBigDataFrame(ub, lb):
ub['naics'] = ub.index
lb['naics'] = lb.index
ub_df = pd.melt(ub, id_vars=['naics'], var_name='geo', value_name='ub')
lb_df = pd.melt(lb, id_vars=['naics'], var_name='geo', value_name='lb')
df = pd.merge(ub_df, lb_df, on=['naics', 'geo'])
# some rows were added to make a matrix
# but they did not exist in the original database
df = df[df['ub'] != 0]
return df
def findNonzeroSlack(ub_slack, lb_slack):
ub_df = pd.melt(ub_slack, id_vars=['naics'], var_name='geo', value_name='ub')
lb_df = pd.melt(lb_slack, id_vars=['naics'], var_name='geo', value_name='lb')
df = pd.merge(ub_df, lb_df, on=['naics', 'geo'])
# delete nonzero entries
df = df[(df['ub'] != 0) | (df['lb'] != 0)]
return df
def save(ub, lb, year="2016", optional_name=""):
big_df = matrixToBigDataFrame(ub, lb)
(us, st, co) = splitBigDataFrame(big_df, year)
if int(year) <= 1997:
us = us.rename(index=str, columns={'naics': 'sic'})
co = co.rename(index=str, columns={'naics': 'sic'})
st = st.rename(index=str, columns={'naics': 'sic'})
us.to_csv("cbp" + year + "us" + optional_name + ".csv", index=False)
st.to_csv("cbp" + year + "st" + optional_name + ".csv", index=False)
co.to_csv("cbp" + year + "co" + optional_name + ".csv", index=False)
'''
optimize is a method that takes in a 'fixed location' (which could be a geographical
location like a county or a NAICS code) and a 'variable' tree.
It goes over the tree and optimizes the corresponding entries based on the child-parent
relations in the tree.
'''
def optimize(ub_matrix, lb_matrix, geo_tree, naics_tree,
location, tree, direction='up', method='children', suppress_output=True):
if suppress_output == False:
print('Optimizing. Method: ' + method)
# direction of the optimization
r = range(len(tree))
if direction == 'down': r = reversed(r)
for index in r:
node = tree[index]
# if there is theoretically no children,
# there is no optimization to be done
if len(node['children']) == 0:
continue
code_upper, code_lower = read_df(merge_dict(node, location), ub_matrix, lb_matrix)
sum_children_upper, sum_children_lower = (0, 0)
for c in node['children']:
(ub,lb) = read_df(merge_dict(tree[c], location), ub_matrix, lb_matrix)
sum_children_upper += ub
sum_children_lower += lb
# if there is no children in the database (even though theoretically
# there could be), then you can't optimize
if (sum_children_upper, sum_children_lower) == (0,0):
continue
if method == 'children':
# if none of the children is suppressed, don't update them
if sum_children_lower == sum_children_upper:
continue
for c in node['children']:
c_upper, c_lower = read_df(merge_dict(tree[c], location), ub_matrix, lb_matrix)
new_value_upper = min(c_upper, code_upper-(sum_children_lower-c_lower))
new_value_lower = max(c_lower, code_lower-(sum_children_upper-c_upper))
# sum of children should be updated
sum_children_lower += new_value_lower - c_lower
sum_children_upper += new_value_upper - c_upper
if (not suppress_output) and ((c_upper, c_lower) != (new_value_upper, new_value_lower)):
print(index, c, c_upper, c_lower, new_value_upper, new_value_lower)
(ub_matrix, lb_matrix) = write_df(merge_dict(tree[c], location), 'ub', new_value_upper, ub_matrix, lb_matrix)
(ub_matrix, lb_matrix) = write_df(merge_dict(tree[c], location), 'lb', new_value_lower, ub_matrix, lb_matrix)
elif method == 'parent':
# if the parent is not suppressed, don't update it
if code_upper == code_lower:
continue
if (not suppress_output) and (sum_children_lower > code_lower or sum_children_upper < code_upper):
print(index, code_upper, code_lower, sum_children_upper, sum_children_lower)
new_value_upper = min(sum_children_upper, code_upper)
new_value_lower = max(sum_children_lower, code_lower)
# a discrepancy in the data means that there is no overlap between
# the entry's interval and the interval obtained using its children's
# sum. The if statement below checks if there is a discrepancy at this entry.
# if there is a discrepancy in data, print out and exit.
if max(sum_children_lower, code_lower)>min(sum_children_upper, code_upper):
print('discrepancy')
print('index: ' + str(index))
print('location: ' + str(location))
print('children sum (lower, upper): ' + str((sum_children_lower, sum_children_upper)))
print('code (lower, upper): ' + str((code_lower, code_upper)))
save(ub, lb, optional_name='_problem')
exit()
(ub_matrix, lb_matrix) = write_df(merge_dict(node, location),'lb', new_value_lower, ub_matrix, lb_matrix)
(ub_matrix, lb_matrix) = write_df(merge_dict(node, location),'ub', new_value_upper, ub_matrix, lb_matrix)
return (ub_matrix, lb_matrix)
# establishment bounds
def fix(ub_matrix, lb_matrix, ub_est, lb_est, geo_tree, naics_tree, suppress_output):
for geo_index, geo in enumerate(geo_tree):
for naics_index, naics in enumerate(naics_tree):
current_entry = merge_dict(naics, geo)
current_upper, current_lower = read_df(current_entry, ub_matrix, lb_matrix)
current_upper_est, current_lower_est = read_df(current_entry, ub_est, lb_est)
est_violates_adding_up_constraints = False
# NAICS
# check theoretical children
if len(naics_tree[naics_index]['children']) != 0:
sum_children_upper, sum_children_lower = (0,0)
for child in naics_tree[naics_index]['children']:
child_upper, child_lower = read_df(merge_dict(naics_tree[child], geo_tree[geo_index]), ub_matrix, lb_matrix)
sum_children_upper += child_upper
sum_children_lower += child_lower
# are there actual children in the dataset
if (sum_children_upper, sum_children_lower) != (0,0):
# is the establishment dataset: (1) better (2) violating adding up constraints?
# the establishment dataset is better
if current_upper_est < current_upper or current_lower < current_lower_est:
# the establishment estimate does not violate adding up constraints
if max(current_lower_est, sum_children_lower) <= min(current_upper_est, sum_children_upper):
ub_matrix, lb_matrix = write_df(current_entry, 'ub', current_upper_est, ub_matrix, lb_matrix)
ub_matrix, lb_matrix = write_df(current_entry, 'lb', current_lower_est, ub_matrix, lb_matrix)
else:
est_violates_adding_up_constraints = True
# GEO
# check theoretical children
if len(geo_tree[geo_index]['children']) != 0:
sum_children_upper, sum_children_lower = (0,0)
for child in geo_tree[geo_index]['children']:
child_upper, child_lower = read_df(merge_dict(naics_tree[naics_index], geo_tree[child]), ub_matrix, lb_matrix)
sum_children_upper += child_upper
sum_children_lower += child_lower
# are there actual children in the dataset
if (sum_children_upper, sum_children_lower) != (0,0):
# is the establishment dataset: (1) better (2) violating adding up constraints?
# the establishment dataset is better
if current_upper_est < current_upper or current_lower < current_lower_est:
# the establishment estimate does not violate adding up constraints
if max(current_lower_est, sum_children_lower) <= min(current_upper_est, sum_children_upper) and (not est_violates_adding_up_constraints):
ub_matrix, lb_matrix = write_df(current_entry, 'ub', current_upper_est, ub_matrix, lb_matrix)
ub_matrix, lb_matrix = write_df(current_entry, 'lb', current_lower_est, ub_matrix, lb_matrix)
print('Fixed the dataset.')
ub_matrix.to_csv('ub_fixed.csv')
lb_matrix.to_csv('lb_fixed.csv')
return (ub_matrix, lb_matrix)
# BOUND-TIGHTENING BEGINS HERE
def tighten_bounds(ub_matrix, lb_matrix, geo_tree, naics_tree, year = '16', suppress_output=True):
print('tightening started')
while True:
old_dfs = list(map(lambda x: x.copy(), [ub_matrix, lb_matrix]))
# STEP 1
for geo in geo_tree:
(ub_matrix, lb_matrix) = optimize(ub_matrix, lb_matrix, geo_tree, naics_tree, geo, naics_tree, 'down', 'children', suppress_output)
# STEP 2
for naics in naics_tree:
(ub_matrix, lb_matrix) = optimize(ub_matrix, lb_matrix, geo_tree, naics_tree, naics, geo_tree, 'down', 'children', suppress_output)
# STEP 3
for geo in geo_tree:
(ub_matrix, lb_matrix) = optimize(ub_matrix, lb_matrix, geo_tree, naics_tree, geo, naics_tree, 'up', 'parent', suppress_output)
# STEP 4
for naics in naics_tree:
(ub_matrix, lb_matrix) = optimize(ub_matrix, lb_matrix, geo_tree, naics_tree, naics, geo_tree, 'up', 'parent', suppress_output)
# check if we're converged
new_dfs = [ub_matrix, lb_matrix]
if equalListDataFrames(new_dfs, old_dfs):
# write data
ub_matrix.to_csv('ub_converged.csv')
lb_matrix.to_csv('lb_converged.csv')
save(ub_matrix, lb_matrix, year, '_tightened_bounds')
print('converged')
break
else:
ub_matrix.to_csv('ub.csv')
lb_matrix.to_csv('lb.csv')
print('no convergence')
#<NAME>, Yang (2019)
#Corresponding Author: <EMAIL>
import numpy as np, pandas as pd
import re, sys
#Clean data and prepare bounds
def cbp_clean(data_input, geo):
data_input.columns = map(str.lower, data_input.columns)
data_input['empflag'] = data_input['empflag'].astype(str)
data_input.loc[data_input.empflag == ".", 'empflag'] = ""
if 'lfo' in data_input.columns:
data_input = data_input[data_input.lfo == '-']
if 'naics' in data_input.columns:
data_input = data_input.rename(columns={"naics": "ind"})
elif 'sic' in data_input.columns:
data_input = data_input.rename(columns={"sic": "ind"})
data_input['lb'] = data_input['empflag']
data_input['ub'] = data_input['empflag']
data_input['lb'] = data_input['lb'].replace({'A':0,'B':20,'C':100,'E':250,'F':500,'G':1000,'H':2500,'I':5000,'J':10000,'K':25000,'L':50000,'M':100000})
data_input['ub'] = data_input['ub'].replace({'A':19,'B':99,'C':249,'E':499,'F':999,'G':2499,'H':4999,'I':9999,'J':24999,'K':49999,'L':99999,'M':100000000})
data_input[['lb','ub']] = data_input[['lb','ub']].apply(pd.to_numeric, errors='coerce')
data_input.loc[np.isnan(data_input.lb), {'ub','lb'}] = data_input.loc[np.isnan(data_input.lb), 'emp']
if geo == "us":
data_input = data_input[['ind','lb','ub']]
elif geo == "st":
data_input = data_input[['fipstate','ind','lb','ub']]
elif geo == "co":
data_input = data_input[['fipstate','fipscty','ind','lb','ub']]
return data_input
def cbp_change_code(data_input, code_old, code_new):
data_helper = data_input.copy()
data_helper = data_helper[data_helper.ind == code_old]
data_helper.loc[data_helper.ind == code_old, 'ind'] = code_new
data_helper.loc[:, 'lb'] = 0
data_input = data_input.append(data_helper, ignore_index=True)
return data_input
#Clean data and prepare bounds
def cbp_drop(data_input, year, geo,codechanger):
ind_drop_set = []
geo_drop_set = [98,99]
if geo == "co" and year in range(1970, 1990):
if year == 1977:
ind_drop_set = ["0785", "2031", "2433", "2442", "3611", "3716", "3791", "3803","3821", "5122", "5129", "6798", "7012", "7013", "8310", "8361"]
if year == 1978:
ind_drop_set = ["0785", "2015", "2433", "2442", "2661", "3611", "3716", "3791", "3803", "3821", "4582", "5129", "6070", "6798", "7012", "7013", "8062", "8084", "8310", "8361", "8411", "8800", "8810"]
if year == 1979:
ind_drop_set = ["0785", "0759", "0785", "079/", "1625", "2036", "2940", "2942", "3073", "3239", "3481", "5212", "5513", "5780", "5781", "5820", "5821", "5991", "6122", "6406", "7012", "7060", "7065", "7328", "7380", "7388", "7626", "7638", "7835", "7912", "7994", "8120", "8126", "8500", "8560", "8562", "8680", "8800", "8810","8811", "3716", "5129", "5192", "6590", "6599", "6798", "7013", "8310", "8361"]
data_helper = data_input.copy()
data_helper = data_helper[data_helper.fipstate == 11]
data_helper = data_helper[data_helper.fipscty == 99]
data_helper.loc[:, 'lb'] = 0
data_helper.loc[:, 'fipscty'] = 1
data_input.append(data_helper, ignore_index=True)
if year == 1980:
ind_drop_set = [ "1629", "64--", "6798", "8310", "8361", "8631"]
if year == 1981:
ind_drop_set = ["1540", "1542", "6798", "8051", "8310", "8361"]
if year == 1982:
ind_drop_set = ["1321", "2771", "8800", "8810", "8811", "3716", "6590", "6599", "6798", "8310", "8361"]
if year == 1983:
ind_drop_set = ["1711", "3716", "4229", "6590", "6599", "6793", "6798", "8310", "8361"]
if year == 1984:
ind_drop_set = ["3716", "4229", "5380", "5580", "6590", "6599", "6798", "8310", "8361"]
if year == 1985:
ind_drop_set = ["3716", "5380", "5580", "6798", "8310", "8361"]
if year == 1986:
ind_drop_set = ["1111", "1481", "1531", "1611", "4131", "4151", "4231", "4411", "4431", "4441", "4712", "4811", "4821", "4899", "4911", "4941", "4961", "4971", "5380", "5580", "5970", "6410", "6610", "7840", "8110", "8361"]
if year == 1987:
ind_drop_set = ["1540", "4214", "5399", "6410", "8320", "8321", "8330", "8331", "8350", "8351", "8390", "8399"]
if year == 1988:
ind_drop_set = ["5399"]
elif geo == "st" and year in range(70, 91):
if year == 1977:
ind_drop_set = ["0785", "2031", "2433", "2442", "3611", "3716", "3791", "3803", "3821", "5129", "6798", "7012", "7013", "8310", "8361"]
if year == 1978:
ind_drop_set = ["3716", "5129", "6070", "6798", "7012", "7013", "8310", "8361", "0785", "2015", "2433", "2442", "3611", "3791", "3803", "3821"]
if year == 1979:
ind_drop_set = ["0759", "0785", "079/", "1625", "2036", "2940", "2942", "3073", "3239", "3481", "3716", "5129", "5192", "5212", "5513", "5780", "5781", "5820", "5821", "5991", "6406", "6590", "6599", "6798", "7012", "7013", "7060", "7065", "7328", "7380", "7388", "7626", "7638", "7835", "7912", "7994", "8120", "8126", "8310", "8361", "8500", "8560", "8562", "8680", "8800", "8810", "8811"]
if year == 1980:
ind_drop_set = ["3716", "6798", "8310", "8361"]
if year == 1981:
ind_drop_set = ["1540", "1542", "6798", "8310", "8361"]
if year == 1982:
ind_drop_set = ["2771", "3716", "6590", "6599", "6798", "8310", "8361", "8800", "8810", "8811"]
if year == 1983:
ind_drop_set = ["3716", "4229", "6590", "6599", "6793", "6798", "8310", "8361"]
if year == 1984:
ind_drop_set = ["3716", "4229", "5380", "5580", "6590", "6599", "6798", "8310", "8361"]
if year == 1985:
ind_drop_set = ["3716", "5380", "5580", "6798", "8310", "8361"]
if year == 1986:
ind_drop_set = ["1111", "1481", "1531", "1611", "4131", "4151", "4231", "4411", "4431", "4441", "4712", "4811", "4821", "4899", "4911", "4941", "4961", "4971", "5380", "5580", "5970", "6410", "6610", "7840", "8110", "8361"]
if year == 1987:
ind_drop_set = ["1540", "4214", "6410", "8320", "8330", "8350", "8390"]
if year == 1988:
ind_drop_set = ["5399"]
if year == 1990:
ind_drop_set = ["8990"]
elif geo == "us" and year in range(1970, 1990):
if year == 1977:
ind_drop_set = ["3716", "5129", "6798", "7012", "7013", "8310", "8361"]
data_input = codechanger(data_input, "40--", "4300")
data_input = codechanger(data_input, "40--", "4310")
data_input = codechanger(data_input, "40--", "4311")
if year == 1978:
ind_drop_set = ["3716", "5129", "6070", "6798", "7012", "7013", "8310", "8361"]
if year == 1979:
ind_drop_set = ["5129", "6590", "6599", "6798", "7013", "8310", "8361"]
data_input = codechanger(data_input, "1090", "1092")
data_input = codechanger(data_input, "6110", "6113")
if year == 1980:
ind_drop_set = ["3761", "6798", "8310", "8361"]
data_input = codechanger(data_input, "1090", "1092")
data_input = codechanger(data_input, "6110", "6113")
if year == 1981:
ind_drop_set = ["6798", "8310", "8361"]
data_input = codechanger(data_input, "6110", "6113")
if year == 1982:
ind_drop_set = ["3716", "6590", "6599", "6798", "8310", "8361"]
data_input = codechanger(data_input, "1090", "1092")
data_input = codechanger(data_input, "6110", "6113")
if year == 1983:
ind_drop_set = ["3716", "4229", "6590", "6599", "6798", "8310", "8361"]
data_input = codechanger(data_input, "3570", "3572")
data_input = codechanger(data_input, "6110", "6113")
if year == 1984:
ind_drop_set = ["3716", "4229", "6590", "6599", "6798", "8310", "8361"]
data_input = codechanger(data_input, "3570", "3572")
data_input = codechanger(data_input, "3670", "3673")
if year == 1985:
ind_drop_set = ["3716", "6798", "8310", "8361"]
data_input = codechanger(data_input, "3570", "3572")
if year == 1986:
ind_drop_set = ["1111", "1481", "1531", "1611", "4131", "4151", "4231", "4411", "4431", "4441", "4712", "4811", "4821", "4899", "4911", "4941", "4961", "4971", "5380", "5580", "5970", "6410", "6610", "7840", "8110", "8361"]
data_input = codechanger(data_input, "3570", "3572")
if year == 1987:
ind_drop_set = ["1110", "1210", "1540", "5399", "6410", "8320", "8321", "8330", "8331", "8350", "8351", "8390", "8399"]
data_input = codechanger(data_input, "1112", "1110")
data_input = codechanger(data_input, "1211", "1210")
data_input = codechanger(data_input, "5800", "5810")
data_input = data_input[~data_input.ind.isin(ind_drop_set)]
if geo == 'co' or geo == 'st':
data_input = data_input[~data_input.fipstate.isin(geo_drop_set)]
data_input.loc[data_input.ind == "19--", 'ind'] = "20--"
data_input.loc[data_input.ind == "--", "ind"] = "07--"
if year == 1997:
data_input = codechanger(data_input, "5800", "5810")
data_input = codechanger(data_input, "2070", "2067")
if year in range(1991, 1997):
data_input = codechanger(data_input, "5800", "5810")
if year in range(1970, 1998):
data_input.ind = data_input.ind.str.replace('/','\\')
return data_input
##Industry Code Files
def indreforder_ind(data_input):
data_input = data_input[['NAICS']]
data_input = data_input.sort_values(by = 'NAICS')
return data_input
##Geography Code Files
def indreforder_geo(data_input):
data_input = data_input[['fipstate','fipscty']]
data_input = data_input.sort_values(by = ['fipstate','fipscty'])
return data_input
import numpy as np, pandas as pd
import re, sys
import fnmatch
import os
os.chdir("C:/Users/manav")
##Code to prepare CBP data
geolist = ['co','st','us']
# Using for loop
for year in range(1990,1992):
for geo in geolist:
yl = 'cbp'+str(year)+geo
data = pd.read_csv("Downloads/"+'efsy_cbp_raw_'+str(year)+'/'+geo+'/'+yl+'.txt')
data = cbp_clean(data,geo)
data = cbp_drop(data, year, geo, cbp_change_code)
data.to_csv("Downloads/"+'efsy_cbp_raw_'+str(year)+'/'+geo+'/'+yl+'_edit.csv',index=False)
print(str(year)+':'+geo+'--done!')
##Code to prepare industry and geo reference files
for year in range(1990, 1992):
os.chdir("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref')
dat = []
dat1 = []
dat2 = []
for file in os.listdir('.'):
if fnmatch.fnmatchcase(file, '*sic*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
dat.append(str(myline[0:4]))
df = pd.DataFrame(dat, columns=['ind'])
#df = df.drop(df.index[0])
df = df.replace('"','')
df = df.replace(" ","")
df.to_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref/ind_ref_'+str(year)+'.csv', sep='\t',index=False)
print(df)
elif fnmatch.fnmatchcase(file, '*naics*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
dat.append(str(myline[0:6]))
df = pd.DataFrame(dat, columns=['ind'])
df = df.replace('"','', regex=True)
df = df.replace(' ','', regex=True)
df = df[df.ind != 'NAICS']
df.to_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref/ind_ref_'+str(year)+'.csv', sep='\t',index=False)
print(df)
elif fnmatch.fnmatchcase(file, '*geo*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
dat1.append(str(myline[1:3]))
dat2.append(str(myline[6:9]))
df1 = pd.DataFrame(dat1, columns=['fipstate'])
df2 = pd.DataFrame(dat2, columns=['fipstate'])
df = pd.concat([df1, df2], axis=1)
df = df.replace('"','', regex=True)
df = df.replace(' ','', regex=True)
df = df.replace(',','', regex=True)
df = df.drop(df.index[0])
print(df)
df.to_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref/geo_ref_'+str(year)+'.csv', sep='\t',index=False)
#<NAME> (2019)
#Corresponding Author: <EMAIL>
##Load Packages
#from gurobipy import *
from gurobipy import *
import cbp
import numpy as np, pandas as pd
import re, sys
model = Model('cbp')
# extract year from the arguments
year = 2016
is_estab = False
if len(sys.argv) > 1:
year = sys.argv[1]
if len(sys.argv) > 2:
is_estab = sys.argv[2] == 'estab'
is_sic = False
if year <= 1997:
is_sic = True
#Reading in a year's data
national_df = pd.read_csv(root+'/Data Process/'+str(year)+'/us/'+'cbp'+str(year)+'us_edit.csv')
state_df = pd.read_csv(root+'/Data Process/'+str(year)+'/st/'+'cbp'+str(year)+'st_edit.csv')
county_df = pd.read_csv(root+'/Data Process/'+str(year)+'/co/'+'cbp'+str(year)+'co_edit.csv')
#rename industry column from sic to naics in sic years.
if is_sic:
national_df = national_df.rename(index=str, columns={'sic': 'naics'})
state_df = state_df.rename(index=str, columns={'sic': 'naics'})
county_df = county_df.rename(index=str, columns={'sic': 'naics'})
# find the ref files
industry_ref_file = cbp.refFileName(year)
refpath = root+'/Data Process/'+str(year)+'/ref/'
os.chdir(refpath)
naics_codes = cbp.newNaicsCodes(industry_ref_file, year)
geo_codes = cbp.geoCodes(state_df, county_df)
# ##
# Construct tree for NAICS codes
# ##
# determine level function based on which industry code is used
industry_level_function = cbp.naics_level
if is_sic:
industry_level_function = cbp.sic_level
naics_tree = cbp.preorderTraversalToTree(naics_codes, 'naics', industry_level_function)
# ##
# Construct tree for Geography
# ##
geo_tree = cbp.preorderTraversalToTree(geo_codes, 'geo', cbp.geo_level)
df = cbp.merge_dataframes(national_df, state_df, county_df)
# matrices
ub_matrix = df.pivot(index='ind', columns='geo', values='ub').fillna(0).astype(int)
lb_matrix = df.pivot(index='ind', columns='geo', values='lb').fillna(0).astype(int)
ub_matrix_estab = ub_matrix.copy()
lb_matrix_estab = lb_matrix.copy()
# geo_codes's entries are tuples, which mess up the indexing
# solution: convert the entries to string and remove the space
# because gurobi doesn't like spaces in variable names
geo_codes_str = list(map(lambda x: x.replace(' ', ''), map(str, geo_codes)))
entries = model.addVars(naics_codes, geo_codes_str, name = "Entries")
# add gurobi variables for differences and absolute differences
diffs = model.addVars(naics_codes, geo_codes_str, lb = (-1) * GRB.INFINITY, name = "Diffs")
abs_diffs = model.addVars(naics_codes, geo_codes_str, name = "Abs_Diffs")
if is_estab:
ub_matrix_estab = df.pivot(index='naics', columns='geo', values='ub_estab').fillna(0).astype(int)
lb_matrix_estab = df.pivot(index='naics', columns='geo', values='lb_estab').fillna(0).astype(int)
# Upper bound
model.addConstrs((entries[naics, geo] <= ub_matrix_estab[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "ub")
# Lower bound
model.addConstrs((entries[naics, geo] >= lb_matrix_estab[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "lb")
else:
# Upper bound
model.addConstrs((entries[naics, geo] <= ub_matrix[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "ub")
# Lower bound
model.addConstrs((entries[naics, geo] >= lb_matrix[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "lb")
# define diffs and absolute differences
model.addConstrs((diffs[naics, geo] == (entries[naics, geo] - (ub_matrix[geo_codes[geo_index]][naics] + lb_matrix[geo_codes[geo_index]][naics]) / 2.0) for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "difference")
model.addConstrs((abs_diffs[naics, geo] == abs_(diffs[naics, geo]) for naics in naics_codes for geo in geo_codes_str), "absolute_difference")
for geo_index, geo in enumerate(geo_codes_str):
# print(geo_index)
for naics_index, naics in enumerate(naics_codes):
# bounds = (ub_matrix[geo_codes[geo_index]][naics], lb_matrix[geo_codes[geo_index]][naics])
# # Upper bound
# model.addConstr((entries[naics, geo] <= bounds[0]), "ub" + naics + geo)
# model.addConstr((entries[naics, geo] >= bounds[1]), "lb" + naics + geo)
# model.addConstr((diffs[naics, geo] == (entries[naics, geo] - sum(bounds) / 2.0)), "difference" + naics + geo)
# model.addConstr((abs_diffs[naics, geo] == abs_(diffs[naics, geo])), "absolute_difference" + naics + geo)
# Geographical constraints
# if no children, there is no constraint
if len(geo_tree[geo_index]['children']) > 0:
# check whether in reality this cell has children
children_geo_sum_upper = sum(ub_matrix[geo_codes[child]][naics] for child in geo_tree[geo_index]['children'])
if children_geo_sum_upper > 0:
model.addConstr(entries[naics, geo] == sum(entries[naics, geo_codes_str[child]] for child in geo_tree[geo_index]['children']), "Geographical_Constraint" + naics + geo)
# Industry constraints
# if no children, there is no constraint
if len(naics_tree[naics_index]['children']) > 0:
# check whether this cell has children in reality (in the dataset)
# if children's upper bound sum is nonzero then there is children in the data
children_naics_sum_upper = sum(ub_matrix[geo_codes[geo_index]][naics_codes[child]] for child in naics_tree[naics_index]['children'])
if children_naics_sum_upper > 0:
# SIC does not have exact hierarchy after level 2. NAICS always has exact hierarchy
if is_sic and (cbp.sic_level(naics) >= 2):
model.addConstr(entries[naics, geo] >= sum(entries[naics_codes[child], geo] for child in naics_tree[naics_index]['children']), "Industry_Constraint" + naics + geo)
else:
model.addConstr(entries[naics, geo] == sum(entries[naics_codes[child], geo] for child in naics_tree[naics_index]['children']), "Industry_Constraint" + naics + geo)
# Objective
# obj = entries.sum()
obj = abs_diffs.sum()
# model.setObjective(obj, GRB.MAXIMIZE) # maximize
model.setObjective(obj, GRB.MINIMIZE) # minimize
print('Model created.')
# make the model less sensitive
model.Params.NumericFocus = 1
# model.write("model.lp")
m = model.optimize()
# Write solution to the python variables
for v in model.getVars():
if v.Varname.split('[')[0] == 'Entries':
# get naics and geo codes from the variable name
s = v.Varname.replace(']', '[').split('[')[1]
naics = s.split(',', 1)[0]
s = s.split(',', 1)[1]
geo = tuple(map(int, re.findall('\d+', s)))
if is_estab:
# update the matrix
ub_matrix_estab[geo][naics] = v.X
lb_matrix_estab[geo][naics] = v.X
else:
# update the matrix
ub_matrix[geo][naics] = v.X
lb_matrix[geo][naics] = v.X
# print("%s %f" % (v.Varname, v.X))
# print solution quality statistics
model.printQuality()
# cbp's save function to save the matrices
if is_estab:
cbp.save(ub_matrix_estab, lb_matrix_estab, year, "_gurobi_midpoint_estab")
else:
cbp.save(ub_matrix, lb_matrix, year, "_gurobi_midpoint")
<file_sep>/cbpclean.py
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 16:34:33 2020
@author: manav
"""
os.chdir("C:/Users/manav/Downloads")
import numpy as np, pandas as pd
import re, sys
import fnmatch
import os
import cbputils
os.chdir("C:/Users/manav")
##Code to prepare CBP data
geolist = ['co','st','us']
# Using for loop
for year in range(1990,1992):
for geo in geolist:
yl = 'cbp'+str(year)+geo
data = pd.read_csv("Downloads/"+'efsy_cbp_raw_'+str(year)+'/'+geo+'/'+yl+'.txt')
data = cbputils.cbp_clean(data,geo)
data = cbputils.cbp_drop(data, year, geo, cbputils.cbp_change_code)
data.to_csv("Downloads/"+'efsy_cbp_raw_'+str(year)+'/'+geo+'/'+yl+'_edit.csv',index=False)
print(str(year)+':'+geo+'--done!')
##Code to prepare industry and geo reference files
for year in range(1990, 1992):
os.chdir("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref')
dat = []
dat1 = []
dat2 = []
for file in os.listdir('.'):
if fnmatch.fnmatchcase(file, '*sic*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
dat.append(str(myline[0:4]))
df = pd.DataFrame(dat, columns=['ind'])
#df = df.drop(df.index[0])
df = df.replace('"','')
df = df.replace(" ","")
df.to_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref/ind_ref_'+str(year)+'.csv', sep='\t',index=False)
print(df)
elif fnmatch.fnmatchcase(file, '*naics*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
dat.append(str(myline[0:6]))
df = pd.DataFrame(dat, columns=['ind'])
df = df.replace('"','', regex=True)
df = df.replace(' ','', regex=True)
df = df[df.ind != 'NAICS']
df.to_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref/ind_ref_'+str(year)+'.csv', sep='\t',index=False)
print(df)
elif fnmatch.fnmatchcase(file, '*geo*'):
with open (file, 'rt') as myfile: # Open file lorem.txt for reading text
for myline in myfile: # For each line, read it to a string
dat1.append(str(myline[1:3]))
dat2.append(str(myline[6:9]))
df1 = pd.DataFrame(dat1, columns=['fipstate'])
df2 = pd.DataFrame(dat2, columns=['fipstate'])
df = pd.concat([df1, df2], axis=1)
df = df.replace('"','', regex=True)
df = df.replace(' ','', regex=True)
df = df.replace(',','', regex=True)
df = df.drop(df.index[0])
print(df)
df.to_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref/geo_ref_'+str(year)+'.csv', sep='\t',index=False)
<file_sep>/cbpgurobi.py
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 16:35:04 2020
@author: manav
"""
#<NAME> (2019)
#Corresponding Author: <EMAIL>
##Load Packages
#from gurobipy import *
import os
os.chdir("C:/Users/manav/Downloads")
from gurobipy import *
import cbpfunc as cbp
import numpy as np, pandas as pd
import re, sys
import time
model = Model('cbp')
# extract year from the arguments
year = 2002
tic=time.perf_counter()
is_estab = False
if len(sys.argv) > 1:
year = sys.argv[1]
if len(sys.argv) > 2:
is_estab = sys.argv[2] == 'estab'
is_sic = False
if year <= 1997:
is_sic = True
#Reading in a year's data
national_df = pd.read_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/us/'+'cbp'+str(year)+'us_edit.csv')
state_df = pd.read_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/st/'+'cbp'+str(year)+'st_edit.csv')
county_df = pd.read_csv("C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/co/'+'cbp'+str(year)+'co_edit.csv')
#rename industry column from sic to naics in sic years.
if is_sic:
national_df = national_df.rename(index=str, columns={'sic': 'naics'})
state_df = state_df.rename(index=str, columns={'sic': 'naics'})
county_df = county_df.rename(index=str, columns={'sic': 'naics'})
# find the ref files
industry_ref_file = cbp.refFileName(year)
refpath = "C:/Users/manav/Downloads/"+'efsy_cbp_raw_'+str(year)+'/ref/'
os.chdir(refpath)
naics_codes = cbp.newNaicsCodes(industry_ref_file, year)
geo_codes = cbp.geoCodes(state_df, county_df)
# ##
# Construct tree for NAICS codes
# ##
# determine level function based on which industry code is used
industry_level_function = cbp.naics_level
if is_sic:
industry_level_function = cbp.sic_level
naics_tree = cbp.preorderTraversalToTree(naics_codes, 'naics', industry_level_function)
# ##
# Construct tree for Geography
# ##
geo_tree = cbp.preorderTraversalToTree(geo_codes, 'geo', cbp.geo_level)
df = cbp.merge_dataframes(national_df, state_df, county_df)
# matrices
ub_matrix = df.pivot(index='ind', columns='geo', values='ub').fillna(0).astype(int)
lb_matrix = df.pivot(index='ind', columns='geo', values='lb').fillna(0).astype(int)
ub_matrix_estab = ub_matrix.copy()
lb_matrix_estab = lb_matrix.copy()
# geo_codes's entries are tuples, which mess up the indexing
# solution: convert the entries to string and remove the space
# because gurobi doesn't like spaces in variable names
geo_codes_str = list(map(lambda x: x.replace(' ', ''), map(str, geo_codes)))
entries = model.addVars(naics_codes, geo_codes_str, name = "Entries")
# add gurobi variables for differences and absolute differences
diffs = model.addVars(naics_codes, geo_codes_str, lb = (-1) * GRB.INFINITY, name = "Diffs")
abs_diffs = model.addVars(naics_codes, geo_codes_str, name = "Abs_Diffs")
if is_estab:
ub_matrix_estab = df.pivot(index='naics', columns='geo', values='ub_estab').fillna(0).astype(int)
lb_matrix_estab = df.pivot(index='naics', columns='geo', values='lb_estab').fillna(0).astype(int)
# Upper bound
model.addConstrs((entries[naics, geo] <= ub_matrix_estab[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "ub")
# Lower bound
model.addConstrs((entries[naics, geo] >= lb_matrix_estab[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "lb")
else:
# Upper bound
model.addConstrs((entries[naics, geo] <= ub_matrix[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "ub")
# Lower bound
model.addConstrs((entries[naics, geo] >= lb_matrix[geo_codes[geo_index]][naics] for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "lb")
# define diffs and absolute differences
model.addConstrs((diffs[naics, geo] == (entries[naics, geo] - (ub_matrix[geo_codes[geo_index]][naics] + lb_matrix[geo_codes[geo_index]][naics]) / 2.0) for naics in naics_codes for geo_index, geo in enumerate(geo_codes_str)), "difference")
model.addConstrs((abs_diffs[naics, geo] == abs_(diffs[naics, geo]) for naics in naics_codes for geo in geo_codes_str), "absolute_difference")
for geo_index, geo in enumerate(geo_codes_str):
# print(geo_index)
for naics_index, naics in enumerate(naics_codes):
# bounds = (ub_matrix[geo_codes[geo_index]][naics], lb_matrix[geo_codes[geo_index]][naics])
# # Upper bound
# model.addConstr((entries[naics, geo] <= bounds[0]), "ub" + naics + geo)
# model.addConstr((entries[naics, geo] >= bounds[1]), "lb" + naics + geo)
# model.addConstr((diffs[naics, geo] == (entries[naics, geo] - sum(bounds) / 2.0)), "difference" + naics + geo)
# model.addConstr((abs_diffs[naics, geo] == abs_(diffs[naics, geo])), "absolute_difference" + naics + geo)
# Geographical constraints
# if no children, there is no constraint
if len(geo_tree[geo_index]['children']) > 0:
# check whether in reality this cell has children
children_geo_sum_upper = sum(ub_matrix[geo_codes[child]][naics] for child in geo_tree[geo_index]['children'])
if children_geo_sum_upper > 0:
model.addConstr(entries[naics, geo] == sum(entries[naics, geo_codes_str[child]] for child in geo_tree[geo_index]['children']), "Geographical_Constraint" + naics + geo)
# Industry constraints
# if no children, there is no constraint
if len(naics_tree[naics_index]['children']) > 0:
# check whether this cell has children in reality (in the dataset)
# if children's upper bound sum is nonzero then there is children in the data
children_naics_sum_upper = sum(ub_matrix[geo_codes[geo_index]][naics_codes[child]] for child in naics_tree[naics_index]['children'])
if children_naics_sum_upper > 0:
# SIC does not have exact hierarchy after level 2. NAICS always has exact hierarchy
if is_sic and (cbp.sic_level(naics) >= 2):
model.addConstr(entries[naics, geo] >= sum(entries[naics_codes[child], geo] for child in naics_tree[naics_index]['children']), "Industry_Constraint" + naics + geo)
else:
model.addConstr(entries[naics, geo] == sum(entries[naics_codes[child], geo] for child in naics_tree[naics_index]['children']), "Industry_Constraint" + naics + geo)
# Objective
# obj = entries.sum()
obj = abs_diffs.sum()
# model.setObjective(obj, GRB.MAXIMIZE) # maximize
model.setObjective(obj, GRB.MINIMIZE) # minimize
print('Model created.')
# make the model less sensitive
model.Params.NumericFocus = 1
# model.write("model.lp")
m = model.optimize()
# Write solution to the python variables
for v in model.getVars():
if v.Varname.split('[')[0] == 'Entries':
# get naics and geo codes from the variable name
s = v.Varname.replace(']', '[').split('[')[1]
naics = s.split(',', 1)[0]
s = s.split(',', 1)[1]
geo = tuple(map(int, re.findall('\d+', s)))
if is_estab:
# update the matrix
ub_matrix_estab[geo][naics] = v.X
lb_matrix_estab[geo][naics] = v.X
else:
# update the matrix
ub_matrix[geo][naics] = v.X
lb_matrix[geo][naics] = v.X
# print("%s %f" % (v.Varname, v.X))
# print solution quality statistics
model.printQuality()
# cbp's save function to save the matrices
if is_estab:
cbp.save(ub_matrix_estab, lb_matrix_estab, year, "_gurobi_midpoint_estab")
else:
cbp.save(ub_matrix, lb_matrix, year, "_gurobi_midpoint")
toc=time.perf_counter()
print(f"Ran code in {toc - tic:0.4f} seconds")
<file_sep>/README.md
# cbp_database_public
This repo contains the codes for Eckert, Fort, Schott, and Yang (2019).
| 0be232d04aa23a095070e45888d7180ceb5e89a1 | [
"Markdown",
"Python"
] | 6 | Python | ianschmutte/cbp_imputations | 94e254bc7f89bfa90431d3028982e0171be85891 | 941324ea382702ddba901045580f574765b6ba12 |
refs/heads/master | <file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
// Main page - Danish
Route::get('/', function () {
App::setLocale('da');
return view('pages.home');
//
});
// Main page, danish
/*Route::get('da', function () {
App::setLocale('da');
return view('pages.home');
//
});*/
// Main page, english
Route::get('/en', function () {
App::setLocale('en');
return view('pages.home');
//
});
// Service pages, danish
Route::get('hjemmeside-virksomhed', function () {
App::setLocale('da');
return view('components.servicepages.main');
});
Route::get('app-udvikling', function () {
App::setLocale('da');
return view('components.servicepages.app');
//
});
Route::get('support', function () {
App::setLocale('da');
return view('components.servicepages.support');
//
});
// Service pages, english
Route::get('premium-website', function () {
App::setLocale('en');
return view('components.servicepages.main');
});
Route::get('app-development', function () {
App::setLocale('en');
return view('components.servicepages.app');
//
});
Route::get('premium-support', function () {
App::setLocale('en');
return view('components.servicepages.support');
//
});
<file_sep><?php
namespace App\Exceptions;
use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
HttpException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/PHP
*/
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
return parent::render($request, $e);
}
}
}
<file_sep><?php
// Navbar - en
$lang['en']['nav']['home'] = 'Home';
$lang['en']['nav']['services'] = 'Services';
$lang['en']['nav']['portfolio'] = 'Portfolio';
$lang['en']['nav']['about'] = 'About us';
$lang['en']['nav']['contact'] = 'Contact us';
$lang['en']['nav']['lang'] = 'Dansk';
// Navbar - da
$lang['da']['nav']['home'] = 'Forside';
$lang['da']['nav']['services'] = 'Produkter';
$lang['da']['nav']['portfolio'] = 'Portfolio';
$lang['da']['nav']['about'] = 'Om os';
$lang['da']['nav']['contact'] = 'Kontakt os';
$lang['da']['nav']['lang'] = 'English';
// P1_header/intro - en
$lang['en']['p1']['slogan'] = 'We create business websites that makes your business a web success';
$lang['en']['p1']['introtitle'] = 'Who we are';
$lang['en']['p1']['introtext'] = 'We are a web agency located in Aarhus, Denmark. We create web- and app based solutions, tailor-made for our clients to make them stand out, and allow for flexibility.';
$lang['en']['p1']['introcall'] = 'You’re one step from getting it right';
$lang['en']['p1']['introbutton'] = 'Let\'s talk';
// P1_header/intro - da
$lang['da']['p1']['slogan'] = 'Websites, apps og mere..';
$lang['da']['p1']['introtitle'] = 'Hvem vi er';
$lang['da']['p1']['introtext'] = 'Vi er et web bureau i Aarhus. Vi udvikler web- og app-baserede løsninger, skræddersyet til vores klienter, for at de kan skille sig ud med vores simple, flexible produkter.';
$lang['da']['p1']['introcall'] = 'You’re one step from getting it right';
$lang['da']['p1']['introbutton'] = 'Let\'s talk';
// P2_services - en
$lang['en']['p2']['servicestitle'] = 'What we do';
$lang['en']['p2']['premiumtitle'] = 'Premium websites';
$lang['en']['p2']['premiumtext'] = 'Stand out from your competitors with our tailor-made solutions, uniquely designed for flexible ease of use.';
$lang['en']['p2']['apptitle'] = 'App development';
$lang['en']['p2']['apptext'] = 'If your company needs an app, we will make it. We make apps for Android and iPhones.';
$lang['en']['p2']['seotitle'] = 'Get discovered';
$lang['en']['p2']['seotext'] = 'Using search engine optimization, we ensure that your site gets to the top of the search results.';
$lang['en']['p2']['redesigntitle'] = 'Re-design';
$lang['en']['p2']['redesigntext'] = 'We will improve what already works on your existing site, and add features to improve it even further.';
$lang['en']['p2']['printtitle'] = 'Print';
$lang['en']['p2']['printtext'] = 'With well-designed flyers and business cards, you will be sure that your clients will come back to you.';
$lang['en']['p2']['shoptitle'] = 'Online shop';
$lang['en']['p2']['shoptext'] = 'Our tailor-made e-commerce solutions fits any convievable kind of use. Boost your sales and your overview.';
$lang['en']['p2']['biztitle'] = 'Business solutions';
$lang['en']['p2']['biztext'] = 'We can make applications for employee management, account handling or whatever you need to make your business run smooth.';
$lang['en']['p2']['supporttitle'] = 'Support';
$lang['en']['p2']['supporttext'] = "When we've delivered our product, we will keep in touch to ensure that everything works, and make imporovements based on usage statistics.";
// P2_services - en
$lang['da']['p2']['servicestitle'] = 'Hvad vi tilbyder';
$lang['da']['p2']['premiumtitle'] = 'Premium websites';
$lang['da']['p2']['premiumtext'] = 'Skil dig ud fra dine konkurrenter med vores skræddersyede løsninger, som er fleksible og designet til at dække dine behov.';
$lang['da']['p2']['apptitle'] = 'App-udvikling';
$lang['da']['p2']['apptext'] = 'Hvis din virksomhed har brug for en app, laver vi den. Vi udvikler apps til Android of iPhone.';
$lang['da']['p2']['seotitle'] = 'Bliv opdaget';
$lang['da']['p2']['seotext'] = 'Med <i>search engine optimization</i>, sikrer vi at din website kommer øverst blandt søgeresultaterne.';
$lang['da']['p2']['redesigntitle'] = 'Re-design';
$lang['da']['p2']['redesigntext'] = 'Hvis du mangler en ny website, laver vi den baseret på hvad der allerede er godt på din nuværende site, og forbedrer hvor der er behov.';
$lang['da']['p2']['printtitle'] = 'Tryk';
$lang['da']['p2']['printtext'] = 'Med pæne brochurer og visitkort, vil dine kunder vender tilbage til dig.';
$lang['da']['p2']['shoptitle'] = 'Web shop';
$lang['da']['p2']['shoptext'] = 'Vores skræddersyede e-commerce løsninger passer til alle tænkelige anveldelsesformer. Forøg dit salg og dit overblik.';
$lang['da']['p2']['biztitle'] = 'Virksomhedsløsninger';
$lang['da']['p2']['biztext'] = 'Vi kan lave applikationer til personale management, regnskabshåndtering eller hvad end din virksomhed har brug for, for at køre flydende.';
$lang['da']['p2']['supporttitle'] = 'Support';
$lang['da']['p2']['supporttext'] = "Når vi har leveret vores produkt, holder vi kontakten for at sikre os at alt virker optimalt, og for at lave forbedringer baseret på brugsstatistikker.";
// P4_ABOUT US - en
$lang['en']['p4']['title'] = 'What makes us different?';
$lang['en']['p4']['firsttitle'] = 'Your website or an app will be a pleasure to use';
$lang['en']['p4']['firsttext'] = '<strong>enbit.dk</strong> believes that a <strong>well designed website</strong> or an <strong>interface</strong> makes both the <strong>user\'s</strong> and <strong>client\'s</strong> experience more pleasant, resulting in them coming back to <strong>your business website</strong> and <strong>using your service</strong> again.';
$lang['en']['p4']['secondtitle'] = 'Everything we build for you is 100% custom made';
$lang['en']['p4']['secondtext'] = 'We <strong>focus on</strong> providing <strong>clear</strong> and <strong>usable design</strong>, by using the <strong>latest technologies</strong> we guarantee the <strong>best user experience</strong>. Unlike most other agencies we create <strong>unique design</strong> - you will never see the same website built for someone else.';
$lang['en']['p4']['thirdtitle'] = 'We care about your business';
$lang['en']['p4']['thirdtext'] = 'We are glad to see our <strong>happy clients</strong>. We make sure that everything is <strong>updated</strong> and <strong>working perfectly</strong> by following and <strong>analyzing</strong> your traffic <strong>statistics</strong>. Our <strong>support</strong> is <strong>flaweless</strong>, you will never have to wait for us to <strong>answer your questions</strong>';
$lang['en']['p4']['precall'] = 'Still not convinced? There are more';
$lang['en']['p4']['aboutcall'] = 'Make an inquiry and get <strong>FREE</strong> price estimates';
// P4_ABOUT US - da
$lang['da']['p4']['title'] = 'What makes us different?';
$lang['da']['p4']['firsttitle'] = 'Your website or an app will be a pleasure to use';
$lang['da']['p4']['firsttext'] = '<strong>enbit.dk</strong> believes that a <strong>well designed website</strong> or an <strong>interface</strong> makesboth the <strong>user\'s</strong> and <strong>client\'s</strong> experience more pleasant, resulting in them coming back to <strong>your business website</strong> and <strong>using your service</strong> again.';
$lang['da']['p4']['secondtitle'] = 'Everything we build for you is 100% custom made';
$lang['da']['p4']['secondtext'] = 'We <strong>focus on</strong> providing <strong>clear</strong> and <strong>usable design</strong>, by using the <strong>latest technologies</strong> we guarantee the <strong>best user experience</strong>. Unlike most other agencies we create <strong>unique design</strong> - you will never see the same website built for someone else.';
$lang['da']['p4']['thirdtitle'] = 'We care about your business';
$lang['da']['p4']['thirdtext'] = 'We are glad to see our <strong>happy clients</strong>. We make sure that everything is <strong>updated</strong> and <strong>working perfectly</strong> by following and <strong>analyzing</strong> your traffic <strong>statistics</strong>. Our <strong>support</strong> is <strong>flaweless</strong>, you will never have to wait for us to <strong>answer your questions</strong>';
$lang['da']['p4']['precall'] = 'Still not convinced? There are more';
$lang['da']['p4']['aboutcall'] = 'Make an inquiry and get <strong>FREE</strong> price estimates';
//P5_CONTACT - en
$lang['en']['p5']['thanktitle'] = 'Thank you for your message';
$lang['en']['p5']['thanktext'] = 'We will get back to you as soon as possible.';
$lang['en']['p5']['thanktitleFail'] = 'There was an error';
$lang['en']['p5']['thanktextFail'] = 'Something went wrong. We apologize for this inconvenience. To send us a mail, use <a href="mailto:<EMAIL>"><EMAIL></a>.';
$lang['en']['p5']['formemail'] = 'Email';
$lang['en']['p5']['formemailplaceholder'] = 'Please enter your email address...';
$lang['en']['p5']['formname'] = 'Name';
$lang['en']['p5']['formnameplaceholder'] = 'Please enter your name...';
$lang['en']['p5']['formphone'] = 'Phone';
$lang['en']['p5']['formphoneplaceholder'] = 'Please enter your phone number... (optional)';
$lang['en']['p5']['formmessage'] = 'Message';
$lang['en']['p5']['formmessageplaceholder'] = 'Your Message...';
$lang['en']['p5']['formcheckbox'] = ' I would like to receive a phone call from you';
$lang['en']['p5']['formsubmit'] = 'Send';
//P5_CONTACT - da
$lang['da']['p5']['thanktitle'] = 'Tak for din besked';
$lang['da']['p5']['thanktext'] = 'Vi kontakter dig snarest muligt.';
$lang['da']['p5']['thanktitleFail'] = 'Der opstod en fejl';
$lang['da']['p5']['thanktextFail'] = 'Noget gik galt. Vi beklager ulejligheden. Du kan sende os en mail på <a href="mailto:<EMAIL>"><EMAIL></a>.';
$lang['da']['p5']['formemail'] = 'Email';
$lang['da']['p5']['formemailplaceholder'] = 'Skriv venligst din email adresse...';
$lang['da']['p5']['formname'] = 'Navn';
$lang['da']['p5']['formnameplaceholder'] = 'Skriv venligst dit navn...';
$lang['da']['p5']['formphone'] = 'Telefon';
$lang['da']['p5']['formphoneplaceholder'] = 'Skriv venligst dit telefonnummer... (valgfrit)';
$lang['da']['p5']['formmessage'] = 'Besked';
$lang['da']['p5']['formmessageplaceholder'] = 'Din besked...';
$lang['da']['p5']['formcheckbox'] = ' Jeg ønsker at blive ringet op';
$lang['da']['p5']['formsubmit'] = 'Send';
?><file_sep><?php
return [
'page.lang' => 'en',
'page.langinv' => 'da',
'page.langpost' => '',
'page.langswitch' => 'en',
'nav.home' => 'Forside',
'nav.services' => 'Produkter',
'nav.portfolio' => 'Portfolio',
'nav.about' => 'Om os',
'nav.contact' => 'Kontakt os',
'nav.lang' => 'English',
'header.slogan' => 'Skræddersyede websites og apps til din virksomhed',
'intro.title' => 'Hvem er vi?',
'intro.text' => 'enbit.dk er et <em>webdesign bureau i Aarhus</em>, som udvikler <em>websites og apps</em>, skræddersyet til små og mellemstore virksomheder, så de kan skille sig ud fra konkurrenterne.',
'intro.call' => 'Kom i gang med det samme, få et professionelt website, og få flere kunder',
'intro.button' => 'Se hvad vi tilbyder',
'servicepage.premiumwebtitle' => 'Billigt, Skræddersyet Website til Din Virksomhed',
'servicepage.premiumwebdescription' => 'Skil dig ud fra konkurrenterne med et skræddersyet website, unikt designet til at dække dine behov. Ny hjemmeside, redesign, SEO og support til en lav pris.',
'servicepage.apptitle' => 'Skræddersyede Apps til din Virksomhed',
'servicepage.appdescription' => 'Gør dine kunder til brugere med en app til mobil og tablets. Vi laver native og hybrid apps til Android, iPhone og iPad og udgiver dem til app-butikkerne.',
'servicepage.supporttitle' => 'Support - Første Måned er Gratis',
'servicepage.supportdescription' => 'enbit.dk holder kontakten ved lige, for at sikre at din app eller website virker optimalt. Første måned er gratis, efterfølgende måneder til en lav pris.',
'mainpagetitle' => 'Websites, Apps og SEO - Skræddersyet, til en Lav Pris',
'mainpagedescription' => 'enbit.dk er et webdesignfirma i Aarhus som tilbyder websites, apps og SEO, skræddersyet til vores kunder. Forøg din synlighed på nettet, til en lav pris.',
'servicelist.premiumlink' => 'hjemmeside-virksomhed',
'servicelist.applink' => 'app-udvikling',
'servicelist.supportlink' => 'support',
'servicelist.title' => 'Vi tilbyder',
'servicelist.premiumtitle' => 'Skræddersyet website',
'servicelist.premiumtext' => 'Skil dig ud fra konkurrenterne med vores skræddersyede hjemmesider, designet specifikt til dine behov.',
'servicelist.apptitle' => 'Apps',
'servicelist.apptext' => 'Gør jeres kunder til engagerede brugere med en app til mobil og tablet. Vi udvikler apps til Android, iPhone og iPad.',
// OUTDATED:
'servicelist.seotitle' => 'Søgemaskineoptimering',
'servicelist.seotext' => 'Med <i>søgemaskineoptimering (SEO)</i>, sikrer vi at dit website kommer øverst blandt søgeresultaterne.',
'servicelist.redesigntitle' => 'Re-design',
'servicelist.redesigntext' => 'Hvis du mangler et nyt website, designer vi det, baseret på hvad der allerede er godt på dit nuværende site, og forbedrer hvor der er behov.',
'servicelist.printtitle' => 'Tryk',
'servicelist.printtext' => 'Med pæne brochurer og visitkort, vil dine kunder vender tilbage til dig.',
'servicelist.shoptitle' => 'Web shop',
'servicelist.shoptext' => 'Vores skræddersyede e-commerce løsninger passer til alle tænkelige anveldelsesformer. Forøg dit salg og dit overblik.',
'servicelist.biztitle' => 'Virksomhedsløsninger',
'servicelist.biztext' => 'Vi kan lave applikationer til personale management, regnskabshåndtering eller hvad end din virksomhed har brug for, for at køre flydende.',
// NOT OUTDATED:
'servicelist.supporttitle' => 'Support',
'servicelist.supporttext' => "Vi holder kontakten ved lige for at besvare spørgsmål, sikre at alt fungerer og udfører løbende forbedringer.",
'servicelist.calltoaction' => 'Kom i kontakt',
'servicelist.pricing.from' => 'Fra',
'servicelist.pricing.freemonth' => 'Første måned er altid gratis',
'servicelist.pricing.month' => 'måned',
'servicelist.view' => 'LÆS MERE',
'about.title' => 'Hvordan skiller vi os ud?',
'about.firsttitle' => 'Dit website eller app bliver en fornøjelse at bruge',
'about.firsttext' =>
'<em>enbit.dk</em> tror på at <strong>veldesignede hjemmesider</strong> og <strong>brugerflader</strong>
gør <strong>brugerens oplevelse</strong> mere behagelig, så de får lyst til at besøge <strong>din virksomheds website</strong> igen, og <strong>anvende jeres service</strong>.',
'about.secondtitle' => 'Alt hvad vi laver er 100% skræddersyet',
'about.secondtext' => '<em>Vores fokus</em> er at levere <strong>tydeligt</strong>, <strong>simpelt</strong> og <strong>brugervenligt design</strong>. Ved at anvende de <strong>nyeste teknologier</strong>, garanterer vi den <strong>bedste brugeroplevelse</strong> med vores websites og apps. I modsætning til andre, leverer vi et <strong>unikt design</strong> - du vil aldrig se dit website blive brugt af andre.',
'about.thirdtitle' => 'Vi interesserer os for din virksomhed',
'about.thirdtext' => '<em>Vi holder</em> af <em>glade kunder</em>, og sørger for at alt på dit website (eller din app) er <strong>opdateret</strong> og <strong>virker perfekt</strong>, ved at følge og <strong>analysere</strong> din hjemmesides <strong>brugerstatistikker</strong>. Vores <strong>support</strong> er <strong>i top</strong> - du skal aldrig vente på at få <strong>besvaret dine spørgsmål</strong>.',
'about.precall' => 'Stadig ikke overbevist?',
'about.aboutcall' => 'Kom med en forespørgsel og få et <em>gratis</em> og <em>uforpligtende</em> prisoverslag',
'about.aboutcallBtn' => 'Kom i kontakt',
'contact.thanktitle' => 'Tak for din besked',
'contact.thanktext' => 'Vi kontakter dig snarest muligt og ser frem til at arbejde sammen med dig.',
'contact.thanktitleFail' => 'Der opstod en fejl',
'contact.thanktextFail' => 'Noget gik galt. Vi beklager ulejligheden. Du kan sende os en mail på <a href="mailto:<EMAIL>">info<img src="img/at.png" alt="at" />enbit.dk</a>',
'contact.formemail' => 'Email',
'contact.formemailplaceholder' => 'Skriv venligst din email adresse',
'contact.formname' => 'Navn',
'contact.formnameplaceholder' => 'Skriv venligst dit navn',
'contact.formphone' => 'Telefon',
'contact.formphoneplaceholder' => 'Skriv venligst dit telefonnummer (valgfrit)',
'contact.formmessage' => 'Besked',
'contact.formmessageplaceholder' => 'Din besked',
'contact.formcheckbox' => ' Jeg ønsker at blive ringet op',
'contact.formsubmit' => 'Send',
'premiumweb.01title' => 'Skræddersyet website til din virksomhed',
'premiumweb.01text' => 'Webdesign har udviklet sig til et punkt, hvor frameworks og kodebiblioteker er tilgængelige, til at forenkle konstruktionen af websites, uden at der kræves megen erfaring indenfor kodning. Det betyder, at folk uden tilstrækkelig viden om kodning, kan oprette hjemmesider. Selvom det er hurtigt og nemt at bruge disse frameworks, begrænser de hvor meget hjemmesiden kan tilpasses til dine specifikke behov. Hos enbit.dk, betragter vi webdesign som en kunstform og, vigtigst af alt, et afgørende bindeled mellem dig og dine kunder! Til trods for at vi selv kan anvende de førnævnte frameworks, er vi ikke bange for at kode vores egne scripts, og bryde normerne for disse frameworks. Vi stræber efter kun at lave hjemmesider, som vi selv ville være stolte af at bruge. Hos enbit.dk vil du altid få værdi for dine penge, og du vil skille sig ud fra dine konkurrenter.',
'premiumweb.01list' => '<li>Priser fra 4.000 kr.</li><li>En måneds gratis support</li><li>Den bedste brugeroplevelse</li><li>Skil dig ud fra konkurrenterne</li><li>Betal når produktet er færdigt<sup>*</sup></li><li>Moderne, responsivt webdesign</li>',
'premiumweb.01small' => '<sup>*</sup>Vi opkræver dog et mindre depositum for påbegyndelse af arbejde',
'premiumweb.02title' => 'Tid til et nyt design?',
'premiumweb.02text' => 'Hvis din nuværende hjemmeside kunne bruge en ansigtsløftning, for at holde trit med de konstant skiftende trends i webdesign, vil vi være glade for at hjælpe. Vi vil analysere din nuværende hjemmeside for at finde ud af, hvad der fungerer godt, og arbejde de aspekter ind i din nye hjemmeside, og samtidig forbedre de aspekter af din gamle hjemmeside, der fungerede knap så godt. Mens et helt nyt design er nyt og spændende, indser vi også, at dine nuværende brugere ikke føler sig hjemme i et uvant, nyt design. Vi lægger derfor stor vægt i at immødekomme dine nuværende brugeres vaner, således at den nye hjemmeside vil føles tilstrækkeligt bekendt for dem.',
'premiumweb.02list' => '<li>Analyse af nuværende website</li><li>Nyt design, tro mod det gamle</li><li>Professionelt, brugervenligt webdesign</li><li>En måneds gratis support</li>',
'premiumweb.03title' => 'Søgemaskineoptimering',
'premiumweb.03text' => 'En hjemmeside er kun værdifuld, hvis folk kan finde den. Det er derfor, vi i enbit.dk lægger stor vægt på søgemaskineoptimering (SEO). Ved at anvende den seneste almene praksis indenfor SEO, får vi dit website til at stige og ligge blandt toppen af søgeresultaterne på de mest populære søgemaskiner, såsom Google, Yahoo og Bing. Vi vil formatere indholdet, for at gøre det let læselig for søgemaskinerne, inkludere sociale medier og holde koden semantisk korrekt, så du kan være sikker på, at dine kunder ikke vil have problemer med at finde dit website.',
'premiumweb.03list' => '<li>Semantisk korrekt HTML5</li><li>Optimering af indhold og nøgleord</li><li>Hjælp til AdWords og lignende</li>',
'premiumweb.04title' => 'Du er også en bruger',
'premiumweb.04text' => 'Hos enbit.dk skelner vi mellem to slags brugere på din hjemmeside: din hjemmesides besøgende, og dig selv - du er jo den, der skal tilføje indhold til dit websted. Derfor stræber vi efter at lave et content management system (CMS), som er en fornøjelse at bruge, så du kan gøre, hvad du skal gøre, så hurtigt og effektivt som muligt, hvilket giver dig mere tid til at drive din virksomhed. Du vil få nem kontrol over ethvert ønskeligt aspekt af dit websted.',
'premiumweb.04list' => '<li>Unikt, skræddersyet CMS</li><li>Nemt at tilpasse din hjemmeside</li><li>Du vælger, hvad du vil styre</li>',
'premiumweb.button' => 'Se Andre',
'app.01title' => 'Gør dine kunder til brugere',
'app.01text' => 'Populariteten af mobile enheder er eksploderet, og mange virksomheder har apps til forskellige formål. Hos enbit.dk udvikler vi apps til mobil og tablets, til Android og iOS-enheder. Som med vores premium website løsning, er vores apps skræddersyet til dine behov, og vi vil lave det design, der fungerer bedst for din app, uanset om det er et platform-venligt design, eller et nyt og banebrydende design. Kontakt os, og vi vil gratis hjælpe dig med at finde ud, om du har brug for en app.',
'app.01list' => '<li>Skræddersyede apps til Android og iOS</li><li>Appudvikling til mobil og tablet</li><li>En måneds gratis support</li>',
'app.02title' => 'Udgiv',
'app.02text' => 'Hos enbit.dk vil vi hellere end gerne hjælpe dig med at få din app ud på app-markeder for de forskellige platforme. Vi vil guide dig gennem processen med at rekvirere de nødvendige tilladelser og opfylde kriterierne for at frigive appen. I processen vil vi sørge for at præsentere den på en måde, der vil få din app til stige så tæt på toppen af søgeresultaterne, som muligt.',
'app.02list' => '<li>Play Store og App Store</li><li>SEO - kom blandt de øverste resultater</li><li>Hjælp med opsætning af udviklerlicens</li>',
'app.03title' => 'Native, hybrid og trejdeparts-tjenester',
'app.03text' => "Vil hjælper dig gratis med at beslutte, hvilken slags app, du har brug for - native eller hybrid. Hybrid apps er billigere, men med mindre funktionalitet, mens native apps er fuldt funktionelle, men mindre billige. Om vi laver en hybrid- eller en native app til dig, inkluderer vi hellere end gerne trejdepartsservices, som Facebook, Google API'er, Instagram, osv.",
'app.03list' => '<li>Vi finder den bedste app-type til dig</li><li>Google- og Facebook-tjenester, og andre</li>',
'support.01title' => 'Første måned er gratis',
'support.01text' => 'Når du modtager et produkt fra enbit.dk, vil det altid inkludere en måneds gratis og uforpligtende support. I løbet af denne måned, vil vi sørge for, at alle i virksomheden ved, hvordan man bruger produktet, og vi vil analysere og forbedre dit produkt for at sikre, at du får den kvalitet, du forventer. Efter den første gratis måned, kan du at vælge, om du ønsker at betale for en måned mere, eller ej. Alle enbit.dk kunder kan, til enhver tid, købe en måneds support.',
'support.01list' => '<li>Intro og instruktion til produktet</li><li>Vi sikrer os at produktet virker</li><li>Få svar på spørgsmål via tlf eller mail</li>',
'support.02title' => 'Analyse',
'support.02text' => 'Vi inkluderer analyseværktøjer i alle produkter, vi laver. Som enbit.dk kunde, vil du altid have fri adgang til disse analyseresultater. I løbet af din supportperiode, vil vi bruge disse analyseresultater til at forbedre produktet, baseret på brugernes adfærd.',
'support.02list' => '<li>Forbedringer baseret på brugerstatistikker</li><li>Gratis, nem adgang til analyser og statistikker</li>',
'support.03title' => 'Fejlsikring',
'support.03text' => 'En af de største dele af udviklingsfasen, er lanceringen - efter at produktet er blevet lanceret, bliver det sat på prøve for alvor, for allerførste gang. Før lanceringen, lærer vi en masse om produktet; platform-specifikke bugs, klient-side problemer, etc. Efter lanceringen lærer vi endnu mere, blandt andet om server problemer og trafikrelaterede bugs. Lanceringensfasen er tiden, hvor vi polerer de flossede kanter, og får produktet til at skinne. Dette er grunden til, at den første måneds support altid er gratis.',
'support.03list' => '<li>Vi bliver ved til produktet er fejlfrit</li><li>Diagnosticering af evt. problemer</li>',
];<file_sep><?php
return [
'page.lang' => 'da',
'page.langinv' => 'en',
'page.langpost' => 'en',
'page.langswitch' => '',
'nav.home' => 'Home',
'nav.services' => 'Services',
'nav.portfolio' => 'Portfolio',
'nav.about' => 'About us',
'nav.contact' => 'Contact us',
'nav.lang' => 'Dansk',
'servicelist.premiumlink' => 'premium-website',
'servicelist.applink' => 'app-development',
'servicelist.supportlink' => 'premium-support',
'header.slogan' => 'Tailor-made web solutions for your company',
'intro.title' => 'Who we are',
'intro.text' => 'We are a web agency located in Aarhus, Denmark and we create web and app based solutions, custom-made for our clients to make them stand out.',
'intro.call' => 'Get started now, and gain customers',
'intro.button' => 'See our services',
'servicepage.premiumwebtitle' => 'Custom Made Websites for Your Business',
'servicepage.premiumwe description' => 'Stand out from your competitors with our tailor-made websites, designed uniquely to meet your needs.',
'servicepage.apptitle' => 'Custom Made Apps for Your Business',
'servicepage.appdescription' => 'Turn your customers into users with an app for phones and tablets. We make apps for Android and iPhones.',
'servicepage.supporttitle' => 'Support - First Month is Free!',
'servicepage.supportdescription' => 'enbit.dk stays in touch to ensure that your website or app works optimally.',
'mainpagetitle' => 'Web Development, Website Optimization and app agency ',
'mainpagedescription' => 'enbit.dk is a web agency located in Aarhus, Denmark and we create web and app based solutions, custom-made for our clients to make them stand out.',
'servicelist.title' => 'Our services',
'servicelist.premiumtitle' => 'Premium websites',
'servicelist.premiumtext' => 'Stand out from your competitors with our tailor-made websites, designed uniquely to meet your needs.',
'servicelist.apptitle' => 'App development',
'servicelist.apptext' => 'Turn your customers into users with an app for phones and tablets. We make apps for Android and iPhones.',
'servicelist.seotitle' => 'Get discovered',
'servicelist.seotext' => 'Using search engine optimization, we ensure that your site gets to the top of the search results.',
'servicelist.redesigntitle' => 'Re-design',
'servicelist.redesigntext' => 'We will improve what already works on your existing site, and add features to improve it even further.',
'servicelist.printtitle' => 'Print',
'servicelist.printtext' => 'With well-designed flyers and business cards, you will be sure that your clients will come back to you.',
'servicelist.shoptitle' => 'Online shop',
'servicelist.shoptext' => 'Our tailor-made e-commerce solutions fits any convievable kind of use. Boost your sales and your overview.',
'servicelist.biztitle' => 'Business solutions',
'servicelist.biztext' => 'We can make applications for employee management, account handling or whatever you need to make your business run smooth.',
'servicelist.supporttitle' => 'Premium Support',
'servicelist.supporttext' => "We stay in touch to ensure that your website or app works optimally. The first month is free.",
'servicelist.calltoaction' => 'Get in touch',
'servicelist.pricing.from' => 'From',
'servicelist.pricing.freemonth' => 'First month is always free',
'servicelist.pricing.month' => 'month',
'servicelist.view' => 'VIEW',
'about.title' => 'What makes us different?',
'about.firsttitle' => 'Your website or an app will be a pleasure to use',
'about.firsttext' => '<strong>enbit.dk</strong> believes that a <strong>well designed website</strong> or <strong>interface</strong> makes the <strong>user\'s</strong> experience more pleasant, so they want to go back to <strong>your business website</strong> and <strong>use your services</strong> again.',
'about.secondtitle' => 'Everything we build for you is 100% custom made',
'about.secondtext' => 'We <strong>focus on</strong> providing <strong>clear</strong> and <strong>user-friendly design</strong>. By using the <strong>latest technologies</strong>, we guarantee the <strong>best user experience</strong>. Unlike most other agencies, we create <strong>unique design</strong> - you will never see the same website built for someone else.',
'about.thirdtitle' => 'We care about your business',
'about.thirdtext' => 'We like to have <strong>happy clients</strong>. We make sure that everything is <strong>updated</strong> and <strong>working perfectly</strong>, by monitoring and <strong>analyzing</strong> your <strong>user statistics</strong>. Our <strong>support</strong> is <strong>superb</strong> - you will never have to wait for us to <strong>answer your questions</strong>.',
'about.precall' => 'Still not convinced?',
'about.aboutcall' => 'Make an inquiry and get <strong>free</strong> and <strong>noncommittal</strong> price estimates',
'about.aboutcallBtn' => 'Get in touch',
'contact.thanktitle' => 'Thank you for your message',
'contact.thanktext' => 'We will get back to you as soon as possible.',
'contact.thanktitleFail' => 'There was an error',
'contact.thanktextFail' => 'Something went wrong. We apologize for this inconvenience. To send us a mail, use <a href="mailto:<EMAIL>">info<img src="img/at.png" alt="at" />enbit.dk</a>',
'contact.formemail' => 'Email',
'contact.formemailplaceholder' => 'Please enter your email address',
'contact.formname' => 'Name',
'contact.formnameplaceholder' => 'Please enter your name',
'contact.formphone' => 'Phone',
'contact.formphoneplaceholder' => 'Please enter your phone number (optional)',
'contact.formmessage' => 'Message',
'contact.formmessageplaceholder' => 'Your Message',
'contact.formcheckbox' => ' I would like to receive a phone call from you',
'contact.formsubmit' => 'Send',
'premiumweb.01title' => 'Custom-made premium website for your company',
'premiumweb.01text' => 'Web design has evolved to a point where frameworks and libraries are available to simplify the process of making websites, without much coding knowledge required. This means that people without proper coding knowledge can create websites. However, although it’s fast and easy to use these frameworks and libraries, they limit how much you can customize the website to suit specific needs.</p><p class="plead">At enbit.dk, we consider web design an art form and, most importantly, a vital link between you and your customers! While we might use the aforementioned frameworks ourselves, we’re not afraid to code our own scripts and break the norms of these frameworks. We strive to only make websites that we ourselves would feel proud to use. At enbit.dk you will always get value for your money, and you will stand out from your competitors.',
'premiumweb.02title' => 'Time for a redesign?',
'premiumweb.02text' => 'If your current website could use a facelift to keep up with the ever evolving trends in good web design, we will be happy to help out. We will analyze your current website to find out what works well, and work those aspects into your new website while improving upon the aspects of your old website that didn’t work so well. While a brand new design is new and exciting, we also realize that your current users might not like an unfamiliar new design. Therefore, we put great importance in catering to your current users, so that the new website will feel sufficiently familiar to them.',
'premiumweb.03title' => 'Search engine optimization',
'premiumweb.03text' => 'A website is only valuable if people can find it. That is why we at enbit.dk put great importance in search engine optimization (SEO). Using the latest common practices, we will make your website rise to the top among search results on the most popular search engines, such as Google, Yahoo and Bing. We will format the content to make it easily readable for the search engines, include social media and keep the code semantically up to code, so that you can be sure that your customers won’t have troubles finding your website.',
'premiumweb.04title' => 'You are also a user',
'premiumweb.04text' => 'At enbit.dk we distinguish two kinds of users on your websites: your website’s visitors and yourself – after all, you are the one who has to add content to your site. Therefore we strive to make a content management system (CMS) that is a pleasure to use, so you can do what you need to do as fast and efficiently as possible, giving you more time to run your business. You will get easy control over any aspect of your website that you desire.',
'premiumweb.button' => 'Read Others',
'app.01title' => 'Turn your customers into users',
'app.01text' => 'The popularity of mobile devices is exploding, and many companies have apps for various reasons. At enbit.dk we develop mobile and tablet apps for Android and iOS devices. As with our premium website solution, our apps are tailor-made to suit your needs, and we will make the design that works best for your app, whether it’s a platform friendly design, or cutting edge design. Contact us, and we will help you find out whether or not you need an app, for free.',
'app.02title' => 'Distribute',
'app.02text' => 'At enbit.dk we’re glad to assist you in getting your app out on the app stores for the various platforms. We will guide you through the process of acquiring the required licenses and meeting the criteria for releasing the app. In the process, we will make sure to present it in a way, that will make your app rise as close to the top of the search results as possible.',
'app.03title' => 'Native, hybrid and third-party services',
'app.03text' => 'For free, we will help you decide which kind of app you’d need – native or hybrid. Hybrid apps are cheaper, but with less functionality, while native apps are full-featured but more pricy. Whether we make a hybrid or a native app for you, we are happy to include third-party service functionality in your app, like Facebook, Google API’s, Instagram, etc.',
'support.01title' => 'First month is free',
'support.01text' => 'When you receive a product from enbit.dk, it will always include a month of free, noncommittal support. During this month, we will make sure that everyone in your company knows how to use it, and we will analyze and improve your product to ensure that you get the quality you paid for. After the first free month, you get to choose whether you would like to pay for another month, or not. All enbit.dk customers can buy a month of support at any time.',
'support.02title' => 'Analysis',
'support.02text' => 'We implement analysis tools into all products we make. As an enbit.dk customer, you will always have free access to these analysis results. During your support period, we will use these analysis results to improve the product, based on user behavior.',
'support.03title' => 'Bug fixing',
'support.03text' => 'One of the biggest part of the development phase is the launch – after the product has been launched, it is put to the test for real, for the very first time. Before the launch, we learn a lot about the product; platform specific bugs, client-side issues etc. After the launch, we learn even more, also about server issues and traffic related bugs. The launch phase is the time for polishing the jagged edges to really make the product shine. This is the reason why the first month is always free.',
'premiumweb.01list' => '<li>Prices from 4.000 kr.</li><li>One month of free support</li><li>The best user experience</li><li>Stand out from your competitors</li><li>Pay when the product is completed<sup>*</sup></li><li>Modern, responsive web design</li>',
'premiumweb.01small' => '<sup>*</sup>We do charge a minor deposit prior to starting a project',
'premiumweb.02list' => '<li>Analysis of current website</li><li>New design, faithful to the current</li><li>Professional, user-friendly webdesign</li><li>One month of free support</li>',
'premiumweb.03list' => '<li>Semantically correct HTML5</li><li>Optimization of content and keywords</li><li>Help with AdWords and similar</li>',
'premiumweb.04list' => '<li>Unikt, skræddersyet CMS</li><li>Nemt at tilpasse din hjemmeside</li><li>Du vælger, hvad du vil styre</li>',
'app.01list' => '<li>Custom-made apps for Android and iOS</li><li>App development for mobile og tablet</li><li>One month of free support</li>',
'app.02list' => '<li>Play Store and App Store</li><li>SEO - be among the top search results</li><li>Help with getting a developer license</li>',
'app.03list' => '<li>We find the best app type for you</li><li>Google and Facebook services, among others</li>',
'support.01list' => '<li>Intro and instructions for the product</li><li>We make sure that the product works</li><li>Get your questions answered by phone or mail</li>',
'support.02list' => '<li>Improvements based on user statistics</li><li>Free, ample access to analysis results and statistics</li>',
'support.03list' => "<li>We don't stop until it's error-free</li><li>Diagnosis of potential issues</li>",
]; | d79e6ab21952e5b9dd9f21eb7406cd8afa12c9fe | [
"PHP"
] | 5 | PHP | viliusbivainis/laravele | 4f432057172f4cd1fe77c133a00a9d3f90e38099 | b128ab974a6694b830d59f115bcdbb7a13c0cc8e |
refs/heads/master | <repo_name>diego-anderica/FaaS-Web-IBM<file_sep>/votaciones.js
/**
* Web application
*/
const apiUrl = 'https://1e966fab.eu-gb.apiconnect.appdomain.cloud/guestbook';
const webvotacion = {
// retrieve the existing guestbook entries
getVotaciones() {
return $.ajax({
type: 'GET',
url: `${apiUrl}/votos`,
dataType: 'json'
});
},
checkEmail() {
return $.ajax({
type: 'GET',
url: `${apiUrl}/checkEmails`,
dataType: 'json'
});
},
// add a single guestbood entry
nuevoVoto(nombre, email, eleccion) {
console.log('Enviando', nombre, email, eleccion)
return $.ajax({
type: 'PUT',
url: `${apiUrl}/nuevoVoto`,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
nombre,
email,
eleccion,
}),
dataType: 'json',
});
},
actualizarVoto(id, rev, nombre, email, eleccion) {
console.log('Enviando', id, rev, eleccion)
return $.ajax({
type: 'PUT',
url: `${apiUrl}/actualizarVoto`,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
id,
rev,
nombre,
email,
eleccion,
}),
dataType: 'json',
});
}
};
(function() {
// retrieve entries and update the UI
function loadEntries() {
console.log('Cargando resultados...');
webvotacion.getVotaciones().done(function(result) {
if (!result.entries) {
return;
}
if (result.entries.length == 0) {
alert("No hay votaciones aún. Vuelve a intentarlo más tarde o sé la primera persona en votar.");
return;
}
calcularResultados(result.entries);
}).error(function(error) {
alert("Se ha producido un error al contactar con la base de datos.");
console.log(error);
});
}
function calcularResultados(votaciones) {
var votosTotales = votaciones.length;
var votosLunes = 0;
var votosMartes = 0;
var votosJueves = 0;
var prcLunes = 0;
var prcMartes = 0;
var prcJueves = 0;
for (i = 0; i < votosTotales; i++) {
if (votaciones[i].eleccion == "lunes"){
votosLunes++;
} else if (votaciones[i].eleccion == "martes"){
votosMartes++;
} else if (votaciones[i].eleccion == "jueves"){
votosJueves++;
}
}
prcLunes = ((votosLunes * 100) / votosTotales).toFixed(2);
prcMartes = ((votosMartes * 100) / votosTotales).toFixed(2);
prcJueves = ((votosJueves * 100) / votosTotales).toFixed(2);
$("#prgLunes").css("width", prcLunes + "%").attr("aria-valuenow", prcLunes).text(prcLunes + "%");
$("#prgMartes").css("width", prcMartes + "%").attr("aria-valuenow", prcMartes).text(prcMartes + "%");
$("#prgJueves").css("width", prcJueves + "%").attr("aria-valuenow", prcJueves).text(prcJueves + "%");
}
// intercept the click on the submit button, add the guestbook entry and
// reload entries on success
$(document).on('submit', '#frmVoto', function(e) {
e.preventDefault();
var id = "";
var rev = "";
if (comprobarFormulario()){
webvotacion.checkEmail().done(function(result) {
var existe = false;
if (!result.entries) {
return;
}
if (result.entries.length > 0) {
for (i = 0; i < result.entries.length; i++) {
if ($('#email').val().trim() == result.entries[0].email) {
id = result.entries[i].id;
rev = result.entries[i]._rev;
existe = true;
break;
}
}
}
if (existe) {
if (confirm("Si continúas, tu voto anterior será reemplazado por el nuevo. ¿Deseas continuar?")) {
webvotacion.actualizarVoto(
id,
rev,
$('#nombre').val().trim(),
$('#email').val().trim(),
$('input[name=eleccion]:checked').val()
).done(function(result) {
alert("Tu voto ha sido cambiado correctamente");
// reload entries
loadEntries();
}).error(function(error) {
console.log(error);
});
}
} else {
webvotacion.nuevoVoto(
$('#nombre').val().trim(),
$('#email').val().trim(),
$('input[name=eleccion]:checked').val()
).done(function(result) {
alert("Tu voto se ha registrado correctamente");
// reload entries
loadEntries();
}).error(function(error) {
alert("Se ha producido un error al contactar con la base de datos.");
console.log(error);
});
}
}).error(function(error) {
alert("Se ha producido un error al contactar con la base de datos.");
});
}
});
function comprobarFormulario() {
var nombre = $('#nombre').val().trim();
var email = $('#email').val().trim();
var diaElegido = $('input[name=eleccion]:checked').val();
var continuar = false;
if (nombre == "") {
alert("Escribe un nombre");
return continuar;
}
if (email == "") {
alert("Escribe un email");
return continuar;
} else if (!email.includes("@")) {
alert("Escribe una dirección de correo válida");
return continuar;
}
if (diaElegido == undefined) {
alert("Elige un día entre los disponibles");
return continuar;
}
return !continuar;
}
$(document).ready(function() {
loadEntries();
});
})();
<file_sep>/Actions/format-entries.js
const md5 = require('spark-md5');
function main(params) {
return {
entries: params.rows.map((row) => { return {
eleccion: row.doc.eleccion
}})
};
}
<file_sep>/README.md
# FaaS Web IBM
Página web destinada a la realización de una votación utilizando la plataforma de IBM con un enfoque serverless.
Este proyecto está basado en el ejemplo disponible en https://github.com/IBM-Cloud/serverless-guestbook.
## Asignatura
Servicios de Computación de Altas Prestaciones y Disponibilidad.
-----------------------------------------------------------
Escuela Superior de Informática (ESI), 2019<br>
Universidad de Castilla-La Mancha (UCLM) - España | 939cb4469fe9932c3227b8f4970705163cd2a1a7 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | diego-anderica/FaaS-Web-IBM | 26142440badfe893cf07f7e03f3ec6afb251d236 | 50910c726041406458ac8c6aa72b7140d31144c2 |
refs/heads/master | <file_sep>function setup(){
createCanvas(windowWidth,windowHeight);
}
var myColor = 0;
function draw(){
fill('rgba(0,255,0, 0.25)');
ellipse(mouseX, mouseY, 80, 80);
}
function xCoord(var a){
var result = 5 * a * cos(a)
}<file_sep>const {Map, Marker, CircleMarker, Popup, TileLayer, MapLayer} = window.ReactLeaflet
class MapView extends React.Component {
render(){
const businesses = this.props.businesses
const groups = this.props.groups
const users = this.props.users
var barNumbers = _.map(groups,'barID');
var intBars = barNumbers.map(Number);
var bars = _.pick(businesses,intBars);
var activeGroups = _.map(groups,function(e){
return { name : e.name,barID : parseInt(e.barID) };
});
var session = window.localStorage["firebase:session::drinktogether"];
var seesionObj = JSON.parse(session);
var username = seesionObj['google'].displayName;
var user = _.find(users,function(d){
return d.name == username;
})
const barElements = _.map(bars, function(u,i){
var pos = [u.location.coordinate.latitude,u.location.coordinate.longitude];
var activeGroupName = _.find(activeGroups,function(e){
return e.barID == i;
})
var groupName = activeGroupName.name;
var u_icon = L.icon({
iconUrl: '../images/beerIcon.png',
iconSize: [40, 40],
iconAnchor: [0, 40],
popupAnchor: [20, -30]
})
var mapURL = "http://www.google.com/maps/place/" + u.location.coordinate.latitude + "," + u.location.coordinate.longitude;
return <Marker position={pos} key={i} icon={u_icon}>
<Popup>
<span>
<b> {groupName} </b>
<br></br>
<a target="_blank" href={u.mobile_url}>{u.name}</a>
<br></br>
<a target="_blank" href= {mapURL} >Google Map</a>
<br></br>
Rating: {u.rating}
</span>
</Popup>
</Marker>
})
// Note: .bind(this) is important for the handler function's 'this'
// pointer to refer to this MapView instance
return <Map center={this.props.center}
zoom={14}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{barElements}
</Map>
}
}
MyComponents.MapView = MapView<file_sep>function setup(){
createCanvas(windowWidth,windowHeight);
}
var myColor = 0;
function draw(){
if (mouseIsPressed) {
fill('rgba(0,255,0, 0.25)');
ellipse(mouseX, mouseY, 80, 80);
}
else if(keyIsPressed){
fill(255, 204, 0);
rect(random(0,windowWidth),random(0,windowHeight), 60, 60);
}
}
function mouseWheel(event) {
print(event.delta);
myColor += event.delta*5;
} | 379e8dc81faf9f4a6c2b617117cbca7ef7f13b9f | [
"JavaScript"
] | 3 | JavaScript | ZachLamb/book-1 | 2c77b42adaf9390a943d9d5ab0d4e75c8c7755d7 | fe97825c0fcfff2c042fc5d167e377c62a7b2318 |
refs/heads/master | <repo_name>harshit078/FE<file_sep>/README.md
# FE
Feeleat focuses on helping people, especially teenagers, aged 14-18, recovering from eating disorders by providing them with a safe environment to write down their feelings about their meals.
This website can help people face their inner thoughts and discover different standards of beauty, not only about appearance or how they look. As globalization accelerates and different societies become interconnected to one another, the singular standard of beauty develops over time. This means that one tends to not think about their own identity or characteristics anymore, and rather try to follow what others (e.g., celebrities) do in terms of appearance.
<file_sep>/setup.sh
#!/bin/bash
rm -rf /var/www/html/FeelEat
mkdir /var/www/html/FeelEat
cp -r * /var/www/html/FeelEat
| 74bc9b77084c59ddc895b0d9a1b8a10a683199b8 | [
"Markdown",
"Shell"
] | 2 | Markdown | harshit078/FE | ffe08709b5b8230548d98d1817c34460faff3a6e | e157347492f1907b36c2d1b859ca62981be96aeb |
refs/heads/master | <repo_name>ebrand/WebGL<file_sep>/public/scripts/webgl2.js
if (!Detector.webgl) {
Detector.addGetWebGLMessage();
}
var container, stats;
var camera, scene, renderer;
var mesh;
var params = {
rotate : true,
camX : 0,
camY : 0,
camZ : 2750,
camFov : 27,
triangles : 2000,
cubeSize : 500,
triangleSize: 50
};
var prevParams = {
rotate : true,
camX : 0,
camY : 0,
camZ : 2750,
camFov : 27,
triangles : 2000,
cubeSize : 500,
triangleSize: 50
};
init();
initGui();
animate();
function init() {
container = document.getElementById('container');
camera = new THREE.PerspectiveCamera(params.Fov, window.innerWidth / window.innerHeight, 1, 3500);
camera.position.z = params.camZ;
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x050505, 2000, 3500);
scene.add(new THREE.AmbientLight(0x444444));
var light1 = new THREE.DirectionalLight(0xffffff, 0.5);
light1.position.set(1, 1, 1);
scene.add(light1);
var light2 = new THREE.DirectionalLight(0xffffff, 1.5);
light2.position.set(0, -1, 0);
scene.add(light2);
initTriangleMeshes();
renderer = new THREE.WebGLRenderer({ antialias: false });
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.gammaInput = true;
renderer.gammaOutput = true;
container.appendChild(renderer.domElement);
stats = new Stats();
container.appendChild(stats.dom);
window.addEventListener('resize', onWindowResize, false);
}
function initTriangleMeshes() {
scene.remove(mesh);
var triangles = params.triangles;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array(triangles * 3 * 3);
var normals = new Float32Array(triangles * 3 * 3);
var colors = new Float32Array(triangles * 3 * 3);
var color = new THREE.Color();
// triangles spread in the cube
var n = params.cubeSize;
var n2 = n/2;
// individual triangle size
var d = params.triangleSize;
var d2 = d/2;
var pA = new THREE.Vector3();
var pB = new THREE.Vector3();
var pC = new THREE.Vector3();
var cb = new THREE.Vector3();
var ab = new THREE.Vector3();
for (var i = 0; i < positions.length; i += 9) {
// positions
var x = Math.random() * n - n2;
var y = Math.random() * n - n2;
var z = Math.random() * n - n2;
var ax = x + Math.random() * d - d2;
var ay = y + Math.random() * d - d2;
var az = z + Math.random() * d - d2;
var bx = x + Math.random() * d - d2;
var by = y + Math.random() * d - d2;
var bz = z + Math.random() * d - d2;
var cx = x + Math.random() * d - d2;
var cy = y + Math.random() * d - d2;
var cz = z + Math.random() * d - d2;
positions[ i ] = ax;
positions[ i + 1 ] = ay;
positions[ i + 2 ] = az;
positions[ i + 3 ] = bx;
positions[ i + 4 ] = by;
positions[ i + 5 ] = bz;
positions[ i + 6 ] = cx;
positions[ i + 7 ] = cy;
positions[ i + 8 ] = cz;
// flat face normals
pA.set(ax, ay, az);
pB.set(bx, by, bz);
pC.set(cx, cy, cz);
cb.subVectors(pC, pB);
ab.subVectors(pA, pB);
cb.cross(ab);
cb.normalize();
var nx = cb.x;
var ny = cb.y;
var nz = cb.z;
normals[ i ] = nx;
normals[ i + 1 ] = ny;
normals[ i + 2 ] = nz;
normals[ i + 3 ] = nx;
normals[ i + 4 ] = ny;
normals[ i + 5 ] = nz;
normals[ i + 6 ] = nx;
normals[ i + 7 ] = ny;
normals[ i + 8 ] = nz;
// colors
var vx = (x / n) + 0.5;
var vy = (y / n) + 0.5;
var vz = (z / n) + 0.5;
color.setRGB(vx, vy, vz);
colors[ i ] = color.r;
colors[ i + 1 ] = color.g;
colors[ i + 2 ] = color.b;
colors[ i + 3 ] = color.r;
colors[ i + 4 ] = color.g;
colors[ i + 5 ] = color.b;
colors[ i + 6 ] = color.r;
colors[ i + 7 ] = color.g;
colors[ i + 8 ] = color.b;
}
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('normal', new THREE.BufferAttribute(normals, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
geometry.computeBoundingSphere();
var material = new THREE.MeshPhongMaterial({
color: 0xaaaaaa, specular: 0xffffff, shininess: 250,
side: THREE.DoubleSide, vertexColors: THREE.VertexColors
});
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
handleGuiParams();
renderer.render(scene, camera);
}
function handleGuiParams() {
if(
params.rotate != prevParams.rotate ||
params.camX != prevParams.camX ||
params.camY != prevParams.camY ||
params.camZ != prevParams.camZ ||
params.camFov != prevParams.camFov ||
params.triangles != prevParams.triangles ||
params.cubeSize != prevParams.cubeSize ||
params.triangleSize != prevParams.triangleSize) {
camera.position.x = params.camX;
camera.position.y = params.camY;
camera.position.z = params.camZ;
camera.setFocalLength(params.camFov);
initTriangleMeshes();
prevParams.rotate = params.rotate;
prevParams.camX = params.camX;
prevParams.camY = params.camY;
prevParams.camZ = params.camZ;
prevParams.camFov = params.camFov;
prevParams.triangles = params.triangles;
prevParams.cubeSize = params.cubeSize;
prevParams.triangleSize = params.triangleSize;
}
if(params.rotate) {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
}
}
function initGui() {
var gui = new dat.GUI();
gui.add(params, 'rotate');
var camFldr = gui.addFolder('Camera Position');
camFldr.add(params, 'camX', -5000, 5000);
camFldr.add(params, 'camY', -5000, 5000);
camFldr.add(params, 'camZ', 1500, 5000);
camFldr.add(params, 'camFov', 20, 180);
var triFldr = gui.addFolder('Triangles');
triFldr.add(params, 'triangles', 200, 200000);
triFldr.add(params, 'cubeSize', 100, 5000);
triFldr.add(params, 'triangleSize', 1, 200);
gui.open();
} | e65ab0158f1b06f7415450788e3e69f0d967041f | [
"JavaScript"
] | 1 | JavaScript | ebrand/WebGL | 4b4c42cde607e09c3894c9bd623c9cd782352d72 | ee54dd59128874081395a0fd996dc2ce851ab47a |
refs/heads/master | <file_sep>[](https://travis-ci.org/Potatolive/image-store)
# Image store
## Initial setup
```
npm install
```
## To test locally
```
Set the following environment variable
NODE_ENV development
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
```
## Start the application
```
swagger project start
```
## Swagger documentation
```
swagger project edit
```
## To deploy
Push the code to main branch
<file_sep>'use strict';
/*
'use strict' is not required but helpful for turning syntactical errors into true errors in the program flow
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
*/
/*
Modules make it possible to import JavaScript files into your application. Modules are imported
using 'require' statements that give you a reference to the module.
It is a good idea to list the modules that your application depends on in the package.json in the project root
*/
var util = require('util');
var uuid = require('uuid');
var AWS = require('aws-sdk')
var easyimg = require('easyimage');
var fs = require('fs');
/*
Once you 'require' a module you can reference the things that it exports. These are defined in module.exports.
For a controller in a127 (which this is) you should export the functions referenced in your Swagger document by name.
Either:
- The HTTP Verb of the corresponding operation (get, put, post, delete, etc)
- Or the operationId associated with the operation in your Swagger document
In the starter/skeleton project the 'get' operation on the '/hello' path has an operationId named 'hello'. Here,
we specify that in the exports of this module that 'hello' maps to the function named 'hello'
*/
module.exports = {
upload: upload,
crop: crop,
sign: sign
};
var bucketName = 'potatolive-image';
/*
Functions in a127 controllers used for operations should take two parameters:
Param 1: a handle to the request object
Param 2: a handle to the response object
*/
function upload(req, res) {
console.log(req.swagger.params.file.value);
if(
!req.swagger.params ||
!req.swagger.params.file ||
!req.swagger.params.file.value ||
req.swagger.params.file.value.buffer <= 0 )
{
res.status(400).json({'message': 'File or its content missing in the request!'})
} else {
var fileParams = req.swagger.params.file.value;
if(fileParams.mimetype !== 'image/jpeg') {
res.status(500).json({'message': 'Only jpeg files allowed!'});
} else {
var value = req.swagger.params.file.value.buffer;
var key = req.swagger.params.file.value.originalname;
uploadToS3(key, value, function(resp) {
res.json(resp);
}, function error(err) {
res.json({'message': err});
});
}
}
}
function uploadToS3(key, value, success, error) {
var awsConfig = {region: process.env.AWS_DEFAULT_REGION};
AWS.config.update(awsConfig);
if(process.env.NODE_ENV === "development") {
AWS.config.update(
{
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});
}
var s3 = new AWS.S3();
var params = {
Bucket: bucketName,
Key: key,
Body: value,
ACL:'public-read'
};
s3.putObject(params,
function(data) {
var resp = {
url:
'https://s3.' +
process.env.AWS_DEFAULT_REGION +
'.amazonaws.com/' +
bucketName +
'/' +
key
};
success(resp);
},
function(error) {
console.log(error);
error('Error uploading file!');
}
);
}
function crop(req, res) {
var cropParam = req.swagger.params.cropParam.value;
var srcUrl = cropParam.imageUrl;
var dstId = uuid.v4();
var cropOption = {
src: srcUrl,
dst: '/tmp/' + dstId + '.jpeg',
cropwidth: cropParam.w,
cropheight: cropParam.h,
gravity: 'NorthWest',
x: cropParam.x,
y: cropParam.y
}
console.log(cropOption);
easyimg.crop(cropOption).then(function(file) {
console.log(file);
fs.readFile(file.path, function(err, file_buffer) {
uploadToS3(dstId + '.jpeg', file_buffer, function(resp) {
var fileParams = {
id: dstId,
url: resp.url
}
res.json(fileParams);
}, function error(err) {
res.json({'message': err});
});
});
});
}
function sign(req, res) {
var filename = uuid.v4() + ".jpeg";
console.log("File : " + filename);
var awsConfig = {region: process.env.AWS_DEFAULT_REGION};
AWS.config.update(awsConfig);
if(process.env.NODE_ENV === "development") {
AWS.config.update(
{
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});
}
var s3 = new AWS.S3();
var s3_params = {
Bucket: bucketName,
Key: filename,
Expires: 120,
ACL: 'public-read',
ContentType: req.swagger.params.fileType.value
};
console.log(s3_params);
s3.getSignedUrl('putObject', s3_params, function(err, data){
if(err){
console.log(err);
res.json({'message': 'Unable to get signed URL'})
}
else{
console.log(data);
var return_data = {
signed_request: data,
url: 'https://' + bucketName +'.s3.amazonaws.com/'+filename,
filename : filename,
};
res.json(return_data);
}
});
} | 3f0b612bcf7b34641f631943aee8b169cd4ca106 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Potatolive/image-store | 66c8d3a063597b4662de54cea67e44f3f61381e9 | 5aa3bb05f8574ca0105348adbb813ab10b829dfd |
refs/heads/master | <file_sep>
# POSTSubscriptionPreviewTypePreviewAccountInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**classNS** | **String** | Value of the Class field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**customerTypeNS** | [**CustomerTypeNSEnum**](#CustomerTypeNSEnum) | Value of the Customer Type field for the corresponding customer account in NetSuite. The Customer Type field is used when the customer account is created in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Value of the Department field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the account's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Value of the Location field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Value of the Subsidiary field for the corresponding customer account in NetSuite. The Subsidiary field is required if you use NetSuite OneWorld. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the account was sychronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | [**SynctoNetSuiteNSEnum**](#SynctoNetSuiteNSEnum) | Specifies whether the account should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**billCycleDay** | **Long** | The account's bill cycle day (BCD), when bill runs generate invoices for the account. Specify any day of the month (`1`-`31`, where `31` = end-of-month), or `0` for auto-set. |
**billToContact** | [**POSTSubscriptionPreviewTypePreviewAccountInfoBillToContact**](POSTSubscriptionPreviewTypePreviewAccountInfoBillToContact.md) | |
**currency** | **String** | A currency as defined in Billing Settings. |
<a name="CustomerTypeNSEnum"></a>
## Enum: CustomerTypeNSEnum
Name | Value
---- | -----
COMPANY | "Company"
INDIVIDUAL | "Individual"
<a name="SynctoNetSuiteNSEnum"></a>
## Enum: SynctoNetSuiteNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<file_sep>
# ProxyActionqueryRequestConf
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**batchSize** | **Integer** | Defines the batch size of the query result. The range is 1 - 2000 (inclusive). If a value higher than 2000 is submitted, only 2000 results are returned. | [optional]
<file_sep>
# PUTDocumentPropertiesType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFileName** | **String** | The custom file name to use to generate new Word or PDF files for the billing document. | [optional]
<file_sep>
# POSTAccountingCodeType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**glAccountName** | **String** | Name of the account in your general ledger. Field only available if you have Zuora Finance enabled. Maximum of 255 characters. | [optional]
**glAccountNumber** | **String** | Account number in your general ledger. Field only available if you have Zuora Finance enabled. Maximum of 255 characters. | [optional]
**name** | **String** | Name of the accounting code. Accounting code name must be unique. Maximum of 100 characters. |
**notes** | **String** | Maximum of 2,000 characters. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Accounting code type. You cannot create new accounting codes of type `AccountsReceivable`. Note that `On-Account Receivable` is only available if you enable the Invoice Settlement feature. |
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
ACCOUNTSRECEIVABLE | "AccountsReceivable"
ON_ACCOUNT_RECEIVABLE | "On-Account Receivable"
CASH | "Cash"
OTHERASSETS | "OtherAssets"
CUSTOMERCASHONACCOUNT | "CustomerCashOnAccount"
DEFERREDREVENUE | "DeferredRevenue"
SALESTAXPAYABLE | "SalesTaxPayable"
OTHERLIABILITIES | "OtherLiabilities"
SALESREVENUE | "SalesRevenue"
SALESDISCOUNTS | "SalesDiscounts"
OTHERREVENUE | "OtherRevenue"
OTHEREQUITY | "OtherEquity"
BADDEBT | "BadDebt"
OTHEREXPENSES | "OtherExpenses"
<file_sep>
# GETPaymentRunType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | **String** | The ID of the customer account associated with the payment run. | [optional]
**applyCreditBalance** | **Boolean** | **Note:** This field is only available if you have the Credit Balance feature enabled and the Invoice Settlement feature disabled. Whether to apply credit balances in the payment run. This field is only available when you have Invoice Settlement feature disabled. | [optional]
**autoApplyCreditMemo** | **Boolean** | **Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Whether to automatically apply a posted credit memo to one or more receivables in the payment run. | [optional]
**autoApplyUnappliedPayment** | **Boolean** | **Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Whether to automatically apply unapplied payments to one or more receivables in the payment run. | [optional]
**batch** | **String** | The alias name given to a batch. | [optional]
**billCycleDay** | **Integer** | The billing cycle day (BCD), the day of the month when a bill run generates invoices for the account. | [optional]
**billingRunId** | [**UUID**](UUID.md) | The ID of the bill run. | [optional]
**collectPayment** | **Boolean** | Whether to process electronic payments during the execution of payment runs. | [optional]
**completedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment run is completed, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 11:39:58. | [optional]
**consolidatedPayment** | **Boolean** | **Note:** The **Process Electronic Payment** permission also needs to be allowed for a Manage Payment Runs role to work. See [Payments Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/e_Payments_Roles) for more information. Whether to process a single payment for all receivables that are due on an account. | [optional]
**createdById** | **String** | The ID of the Zuora user who created the payment run. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment run was created, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 15:31:10. | [optional]
**currency** | **String** | A currency defined in the web-based UI administrative settings. | [optional]
**executedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment run is executed, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 11:30:37. | [optional]
**id** | **String** | The ID of the payment run. | [optional]
**number** | **String** | The identification number of the payment run. | [optional]
**paymentGatewayId** | [**UUID**](UUID.md) | The ID of the gateway instance that processes the payment. | [optional]
**processPaymentWithClosedPM** | **Boolean** | **Note:** The **Process Electronic Payment** permission also needs to be allowed for a Manage Payment Runs role to work. See [Payments Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/e_Payments_Roles) for more information. Whether to process payments even if the default payment method is closed. | [optional]
**runDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the scheduled payment run is to be executed for collecting payments. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the created payment run. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | The target date used to determine which receivables to be collected in the payment run. | [optional]
**updatedById** | **String** | The ID of the Zuora user who last updated the payment run. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment run was last updated, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-02 15:36:10. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PENDING | "Pending"
PROCESSING | "Processing"
COMPLETED | "Completed"
ERROR | "Error"
CANCELED | "Canceled"
<file_sep>
# GETPaymentRunSummaryResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**numberOfCreditBalanceAdjustments** | **Integer** | **Note:** This field is only available if you have the Credit Balance feature enabled. The number of credit balance adjustments that are successfully processed in the payment run. | [optional]
**numberOfCreditMemos** | **Integer** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total number of credit memos that are successfully processed in the payment run. | [optional]
**numberOfDebitMemos** | **Integer** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total number of debit memos that are picked up for processing in the payment run. | [optional]
**numberOfErrors** | **Integer** | The number of payments with the status of `Error` and `Processing`. | [optional]
**numberOfInvoices** | **Integer** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total number of invoices that are picked up for processing in the payment run. | [optional]
**numberOfPayments** | **Integer** | The number of payments that are successfully processed in the payment run. | [optional]
**numberOfReceivables** | **Integer** | The total number of receivables that are picked up for processing in the payment run. The value of this field is the sum of the value of the `numberOfInvoices` field and that of the `numberOfDebitMemos` field. | [optional]
**numberOfUnappliedPayments** | **Integer** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The number of unapplied payments that are successfully processed in the payment run. | [optional]
**numberOfUnprocessedDebitMemos** | **Integer** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The number of debit memos with remaining positive balances after the payment run is completed. | [optional]
**numberOfUnprocessedInvoices** | **Integer** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The number of invoices with remaining positive balances after the payment run is completed. | [optional]
**numberOfUnprocessedReceivables** | **Integer** | The number of receivables with remaining positive balances after the payment run is completed. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**totalValues** | [**List<GETPaymentRunSummaryTotalValues>**](GETPaymentRunSummaryTotalValues.md) | Container for total values. | [optional]
<file_sep># DebitMemosApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEDebitMemo**](DebitMemosApi.md#dELETEDebitMemo) | **DELETE** /v1/debitmemos/{debitMemoId} | Delete debit memo
[**gETDebitMemo**](DebitMemosApi.md#gETDebitMemo) | **GET** /v1/debitmemos/{debitMemoId} | Get debit memo
[**gETDebitMemoApplicationParts**](DebitMemosApi.md#gETDebitMemoApplicationParts) | **GET** /v1/debitmemos/{debitMemoId}/application-parts | Get debit memo application parts
[**gETDebitMemoItem**](DebitMemosApi.md#gETDebitMemoItem) | **GET** /v1/debitmemos/{debitMemoId}/items/{dmitemid} | Get debit memo item
[**gETDebitMemoItems**](DebitMemosApi.md#gETDebitMemoItems) | **GET** /v1/debitmemos/{debitMemoId}/items | Get debit memo items
[**gETDebitMemos**](DebitMemosApi.md#gETDebitMemos) | **GET** /v1/debitmemos | Get debit memos
[**pOSTDMTaxationItems**](DebitMemosApi.md#pOSTDMTaxationItems) | **POST** /v1/debitmemos/{debitMemoId}/taxationitems | Create taxation items for debit memo
[**pOSTDebitMemoFromPrpc**](DebitMemosApi.md#pOSTDebitMemoFromPrpc) | **POST** /v1/debitmemos | Create debit memo from charge
[**pOSTDebitMemoPDF**](DebitMemosApi.md#pOSTDebitMemoPDF) | **POST** /v1/debitmemos/{debitMemoId}/pdfs | Create debit memo PDF
[**pOSTEmailDebitMemo**](DebitMemosApi.md#pOSTEmailDebitMemo) | **POST** /v1/debitmemos/{debitMemoId}/emails | Email debit memo
[**pUTBatchUpdateDebitMemos**](DebitMemosApi.md#pUTBatchUpdateDebitMemos) | **PUT** /v1/debitmemos | Update debit memos
[**pUTCancelDebitMemo**](DebitMemosApi.md#pUTCancelDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId}/cancel | Cancel debit memo
[**pUTDebitMemo**](DebitMemosApi.md#pUTDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId} | Update debit memo
[**pUTPostDebitMemo**](DebitMemosApi.md#pUTPostDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId}/post | Post debit memo
[**pUTUnpostDebitMemo**](DebitMemosApi.md#pUTUnpostDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId}/unpost | Unpost debit memo
<a name="dELETEDebitMemo"></a>
# **dELETEDebitMemo**
> CommonResponseType dELETEDebitMemo(debitMemoId, zuoraEntityIds)
Delete debit memo
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Deletes a debit memo. Only debit memos with the Cancelled status can be deleted. You can delete a debit memo only if you have the user permission. See [Billing Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEDebitMemo(debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#dELETEDebitMemo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETDebitMemo"></a>
# **gETDebitMemo**
> GETDebitMemoType gETDebitMemo(debitMemoId, zuoraEntityIds)
Get debit memo
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about a specific debit memo.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, <KEY>.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETDebitMemoType result = apiInstance.gETDebitMemo(debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#gETDebitMemo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, <KEY>. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETDebitMemoType**](GETDebitMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETDebitMemoApplicationParts"></a>
# **gETDebitMemoApplicationParts**
> GetDebitMemoApplicationPartCollectionType gETDebitMemoApplicationParts(debitMemoId, zuoraEntityIds)
Get debit memo application parts
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves information about the payments or credit memos that are applied to a specified debit memo.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetDebitMemoApplicationPartCollectionType result = apiInstance.gETDebitMemoApplicationParts(debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#gETDebitMemoApplicationParts");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetDebitMemoApplicationPartCollectionType**](GetDebitMemoApplicationPartCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETDebitMemoItem"></a>
# **gETDebitMemoItem**
> GETDebitMemoItemType gETDebitMemoItem(dmitemid, debitMemoId, zuoraEntityIds)
Get debit memo item
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about a specific item of a debit memo. A debit memo item is a single line item in a debit memo.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String dmitemid = "dmitemid_example"; // String | The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems).
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETDebitMemoItemType result = apiInstance.gETDebitMemoItem(dmitemid, debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#gETDebitMemoItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**dmitemid** | **String**| The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems). |
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETDebitMemoItemType**](GETDebitMemoItemType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETDebitMemoItems"></a>
# **gETDebitMemoItems**
> GETDebitMemoItemCollectionType gETDebitMemoItems(debitMemoId, zuoraEntityIds, pageSize, amount, beAppliedAmount, createdById, createdDate, id, serviceEndDate, serviceStartDate, sku, skuName, sourceItemId, subscriptionId, updatedById, updatedDate, sort)
Get debit memo items
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all items of a debit memo. A debit memo item is a single line item in a debit memo. ### Filtering You can use query parameters to restrict the data returned in the response. Each query parameter corresponds to one field in the response body. If the value of a filterable field is string, you can set the corresponding query parameter to `null` when filtering. Then, you can get the response data with this field value being `null`. Examples: - /v1/debitmemos/402890245c7ca371015c7cb40b28001f/items?amount=100 - /v1/debitmemos/402890245c7ca371015c7cb40b28001f/items?amount=100&sort=createdDate
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
Double amount = 3.4D; // Double | This parameter filters the response based on the `amount` field.
Double beAppliedAmount = 3.4D; // Double | This parameter filters the response based on the `beAppliedAmount` field.
String createdById = "createdById_example"; // String | This parameter filters the response based on the `createdById` field.
OffsetDateTime createdDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `createdDate` field.
String id = "id_example"; // String | This parameter filters the response based on the `id` field.
LocalDate serviceEndDate = new LocalDate(); // LocalDate | This parameter filters the response based on the `serviceEndDate` field.
LocalDate serviceStartDate = new LocalDate(); // LocalDate | This parameter filters the response based on the `serviceStartDate` field.
String sku = "sku_example"; // String | This parameter filters the response based on the `sku` field.
String skuName = "skuName_example"; // String | This parameter filters the response based on the `skuName` field.
String sourceItemId = "sourceItemId_example"; // String | This parameter filters the response based on the `sourceItemId` field.
String subscriptionId = "subscriptionId_example"; // String | This parameter filters the response based on the `subscriptionId` field.
String updatedById = "updatedById_example"; // String | This parameter filters the response based on the `updatedById` field.
OffsetDateTime updatedDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `updatedDate` field.
String sort = "sort_example"; // String | This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by updated date. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - id - amount - beAppliedAmount - sku - skuName - serviceStartDate - serviceEndDate - sourceItemId - createdDate - createdById - updatedDate - updatedById - subscriptionId Examples: - /v1/debitmemos/402890245c7ca371015c7cb40b28001f/items?sort=createdDate - /v1/debitmemos/402890245c7ca371015c7cb40b28001f/items?amount=100&sort=createdDate
try {
GETDebitMemoItemCollectionType result = apiInstance.gETDebitMemoItems(debitMemoId, zuoraEntityIds, pageSize, amount, beAppliedAmount, createdById, createdDate, id, serviceEndDate, serviceStartDate, sku, skuName, sourceItemId, subscriptionId, updatedById, updatedDate, sort);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#gETDebitMemoItems");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8<KEY>. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**amount** | **Double**| This parameter filters the response based on the `amount` field. | [optional]
**beAppliedAmount** | **Double**| This parameter filters the response based on the `beAppliedAmount` field. | [optional]
**createdById** | **String**| This parameter filters the response based on the `createdById` field. | [optional]
**createdDate** | **OffsetDateTime**| This parameter filters the response based on the `createdDate` field. | [optional]
**id** | **String**| This parameter filters the response based on the `id` field. | [optional]
**serviceEndDate** | **LocalDate**| This parameter filters the response based on the `serviceEndDate` field. | [optional]
**serviceStartDate** | **LocalDate**| This parameter filters the response based on the `serviceStartDate` field. | [optional]
**sku** | **String**| This parameter filters the response based on the `sku` field. | [optional]
**skuName** | **String**| This parameter filters the response based on the `skuName` field. | [optional]
**sourceItemId** | **String**| This parameter filters the response based on the `sourceItemId` field. | [optional]
**subscriptionId** | **String**| This parameter filters the response based on the `subscriptionId` field. | [optional]
**updatedById** | **String**| This parameter filters the response based on the `updatedById` field. | [optional]
**updatedDate** | **OffsetDateTime**| This parameter filters the response based on the `updatedDate` field. | [optional]
**sort** | **String**| This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by updated date. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - id - amount - beAppliedAmount - sku - skuName - serviceStartDate - serviceEndDate - sourceItemId - createdDate - createdById - updatedDate - updatedById - subscriptionId Examples: - /v1/debitmemos/402890245c7ca371015c7cb40b28001f/items?sort=createdDate - /v1/debitmemos/402890245c7ca371015c7cb40b28001f/items?amount=100&sort=createdDate | [optional]
### Return type
[**GETDebitMemoItemCollectionType**](GETDebitMemoItemCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETDebitMemos"></a>
# **gETDebitMemos**
> GETDebitMemoCollectionType gETDebitMemos(zuoraEntityIds, pageSize, accountId, amount, balance, beAppliedAmount, createdById, createdDate, currency, debitMemoDate, dueDate, number, referredInvoiceId, status, targetDate, taxAmount, totalTaxExemptAmount, updatedById, updatedDate, sort)
Get debit memos
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all debit memos associated with all customer accounts. ### Filtering You can use query parameters to restrict the data returned in the response. Each query parameter corresponds to one field in the response body. If the value of a filterable field is string, you can set the corresponding query parameter to `null` when filtering. Then, you can get the response data with this field value being `null`. Examples: - /v1/debitmemos?status=Processed - /v1/debitmemos?referredInvoiceId=null&status=Draft - /v1/debitmemos?status=Processed&type=External&sort=+number
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String accountId = "accountId_example"; // String | This parameter filters the response based on the `accountId` field.
Double amount = 3.4D; // Double | This parameter filters the response based on the `amount` field.
Double balance = 3.4D; // Double | This parameter filters the response based on the `balance` field.
Double beAppliedAmount = 3.4D; // Double | This parameter filters the response based on the `beAppliedAmount` field.
String createdById = "createdById_example"; // String | This parameter filters the response based on the `createdById` field.
OffsetDateTime createdDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `createdDate` field.
String currency = "currency_example"; // String | This parameter filters the response based on the `currency` field.
LocalDate debitMemoDate = new LocalDate(); // LocalDate | This parameter filters the response based on the `debitMemoDate` field.
LocalDate dueDate = new LocalDate(); // LocalDate | This parameter filters the response based on the `dueDate` field.
String number = "number_example"; // String | This parameter filters the response based on the `number` field.
String referredInvoiceId = "referredInvoiceId_example"; // String | This parameter filters the response based on the `referredInvoiceId` field.
String status = "status_example"; // String | This parameter filters the response based on the `status` field.
LocalDate targetDate = new LocalDate(); // LocalDate | This parameter filters the response based on the `targetDate` field.
Double taxAmount = 3.4D; // Double | This parameter filters the response based on the `taxAmount` field.
Double totalTaxExemptAmount = 3.4D; // Double | This parameter filters the response based on the `totalTaxExemptAmount` field.
String updatedById = "updatedById_example"; // String | This parameter filters the response based on the `updatedById` field.
OffsetDateTime updatedDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `updatedDate` field.
String sort = "sort_example"; // String | This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by debit memo number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - number - accountId - debitMemoDate - targetDate - dueDate - amount - taxAmount - totalTaxExemptAmount - balance - beAppliedAmount - referredInvoiceId - createdDate - createdById - updatedDate - updatedById Examples: - /v1/debitmemos?sort=+number - /v1/debitmemos?status=Processed&sort=-number,+amount
try {
GETDebitMemoCollectionType result = apiInstance.gETDebitMemos(zuoraEntityIds, pageSize, accountId, amount, balance, beAppliedAmount, createdById, createdDate, currency, debitMemoDate, dueDate, number, referredInvoiceId, status, targetDate, taxAmount, totalTaxExemptAmount, updatedById, updatedDate, sort);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#gETDebitMemos");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**accountId** | **String**| This parameter filters the response based on the `accountId` field. | [optional]
**amount** | **Double**| This parameter filters the response based on the `amount` field. | [optional]
**balance** | **Double**| This parameter filters the response based on the `balance` field. | [optional]
**beAppliedAmount** | **Double**| This parameter filters the response based on the `beAppliedAmount` field. | [optional]
**createdById** | **String**| This parameter filters the response based on the `createdById` field. | [optional]
**createdDate** | **OffsetDateTime**| This parameter filters the response based on the `createdDate` field. | [optional]
**currency** | **String**| This parameter filters the response based on the `currency` field. | [optional]
**debitMemoDate** | **LocalDate**| This parameter filters the response based on the `debitMemoDate` field. | [optional]
**dueDate** | **LocalDate**| This parameter filters the response based on the `dueDate` field. | [optional]
**number** | **String**| This parameter filters the response based on the `number` field. | [optional]
**referredInvoiceId** | **String**| This parameter filters the response based on the `referredInvoiceId` field. | [optional]
**status** | **String**| This parameter filters the response based on the `status` field. | [optional] [enum: Draft, Posted, Canceled, Error, PendingForTax, Generating, CancelInProgress]
**targetDate** | **LocalDate**| This parameter filters the response based on the `targetDate` field. | [optional]
**taxAmount** | **Double**| This parameter filters the response based on the `taxAmount` field. | [optional]
**totalTaxExemptAmount** | **Double**| This parameter filters the response based on the `totalTaxExemptAmount` field. | [optional]
**updatedById** | **String**| This parameter filters the response based on the `updatedById` field. | [optional]
**updatedDate** | **OffsetDateTime**| This parameter filters the response based on the `updatedDate` field. | [optional]
**sort** | **String**| This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by debit memo number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - number - accountId - debitMemoDate - targetDate - dueDate - amount - taxAmount - totalTaxExemptAmount - balance - beAppliedAmount - referredInvoiceId - createdDate - createdById - updatedDate - updatedById Examples: - /v1/debitmemos?sort=+number - /v1/debitmemos?status=Processed&sort=-number,+amount | [optional]
### Return type
[**GETDebitMemoCollectionType**](GETDebitMemoCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTDMTaxationItems"></a>
# **pOSTDMTaxationItems**
> GETTaxationItemListType pOSTDMTaxationItems(debitMemoId, body, zuoraEntityIds)
Create taxation items for debit memo
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates taxation items for a debit memo.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, <KEY>.
POSTTaxationItemListForDMType body = new POSTTaxationItemListForDMType(); // POSTTaxationItemListForDMType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETTaxationItemListType result = apiInstance.pOSTDMTaxationItems(debitMemoId, body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pOSTDMTaxationItems");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, <KEY>. |
**body** | [**POSTTaxationItemListForDMType**](POSTTaxationItemListForDMType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETTaxationItemListType**](GETTaxationItemListType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTDebitMemoFromPrpc"></a>
# **pOSTDebitMemoFromPrpc**
> GETDebitMemoType pOSTDebitMemoFromPrpc(body, zuoraEntityIds, zuoraVersion)
Create debit memo from charge
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates an ad-hoc debit memo from a product rate plan charge. Zuora supports the creation of debit memos from any type of product rate plan charge. The charges can also have any amount and any charge model, except for discout charge models. You can create a debit memo only if you have the user permission. See [Billing Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
DebitMemoFromChargeType body = new DebitMemoFromChargeType(); // DebitMemoFromChargeType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * amount * memoItemAmount
try {
GETDebitMemoType result = apiInstance.pOSTDebitMemoFromPrpc(body, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pOSTDebitMemoFromPrpc");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**DebitMemoFromChargeType**](DebitMemoFromChargeType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * amount * memoItemAmount | [optional]
### Return type
[**GETDebitMemoType**](GETDebitMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTDebitMemoPDF"></a>
# **pOSTDebitMemoPDF**
> POSTMemoPdfResponse pOSTDebitMemoPDF(debitMemoId, zuoraEntityIds)
Create debit memo PDF
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates a PDF file for a specified debit memo. To access the generated PDF file, you can download it by clicking **View PDF** on the detailed debit memo page through the Zuora UI. This REST API operation can be used only if you have the Billing user permission \"Regenerate PDF\" enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of the debit memo that you want to create a PDF file for. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTMemoPdfResponse result = apiInstance.pOSTDebitMemoPDF(debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pOSTDebitMemoPDF");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of the debit memo that you want to create a PDF file for. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTMemoPdfResponse**](POSTMemoPdfResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTEmailDebitMemo"></a>
# **pOSTEmailDebitMemo**
> CommonResponseType pOSTEmailDebitMemo(request, debitMemoId, zuoraEntityIds)
Email debit memo
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Sends a posted debit memo to the specified email addresses manually. ## Notes - You must activate the **Email Debit Memo | Manually email Debit Memo** notification before emailing debit memos. To include the debit memo PDF in the email, select the **Include Debit Memo PDF** check box in the **Edit notification** dialog from the Zuora UI. See [Create and Edit Notifications](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/Notifications/C_Create_Notifications#section_2) for more information. - Zuora sends the email messages based on the email template you set. You can set the email template to use in the **Delivery Options** panel of the **Edit notification** dialog from the Zuora UI. By default, the **Manual Email for Debit Memo Default Template** template is used. See [Create and Edit Email Templates](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/Notifications/Create_Email_Templates) for more information. - The debit memos are sent only to the work email addresses or personal email addresses of the Bill To contact if the following conditions are all met: * The `useEmailTemplateSetting` field is set to `false`. * The email addresses are not specified in the `emailAddresses` field.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
PostDebitMemoEmailType request = new PostDebitMemoEmailType(); // PostDebitMemoEmailType |
String debitMemoId = "debitMemoId_example"; // String | The ID of a posted debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pOSTEmailDebitMemo(request, debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pOSTEmailDebitMemo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**PostDebitMemoEmailType**](PostDebitMemoEmailType.md)| |
**debitMemoId** | **String**| The ID of a posted debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTBatchUpdateDebitMemos"></a>
# **pUTBatchUpdateDebitMemos**
> CommonResponseType pUTBatchUpdateDebitMemos(body, zuoraEntityIds)
Update debit memos
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Updates the due date for multiple debit memos in batches with one call.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
PUTBatchDebitMemosRequest body = new PUTBatchDebitMemosRequest(); // PUTBatchDebitMemosRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTBatchUpdateDebitMemos(body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pUTBatchUpdateDebitMemos");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**PUTBatchDebitMemosRequest**](PUTBatchDebitMemosRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTCancelDebitMemo"></a>
# **pUTCancelDebitMemo**
> GETDebitMemoType pUTCancelDebitMemo(debitMemoId, zuoraEntityIds)
Cancel debit memo
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Cancels a debit memo. Only debit memos with the Draft status can be cancelled. You can cancel a debit memo only if you have the user permission. See [Billing Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8a<KEY>e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETDebitMemoType result = apiInstance.pUTCancelDebitMemo(debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pUTCancelDebitMemo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETDebitMemoType**](GETDebitMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTDebitMemo"></a>
# **pUTDebitMemo**
> GETDebitMemoType pUTDebitMemo(body, debitMemoId, zuoraEntityIds)
Update debit memo
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Updates the basic and finance information about a debit memo. Currently, Zuora supports updating tax-exclusive memo items, but does not support updating tax-inclusive memo items. If the amount of a memo item is updated, the tax will be recalculated in the following conditions: - The memo is created from a product rate plan charge and you use Avalara to calculate the tax. - The memo is created from an invoice and you use Avalara or Zuora Tax to calculate the tax. You can update a debit memo only if you have the user permission. See [Billing Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
PUTDebitMemoType body = new PUTDebitMemoType(); // PUTDebitMemoType |
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETDebitMemoType result = apiInstance.pUTDebitMemo(body, debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pUTDebitMemo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**PUTDebitMemoType**](PUTDebitMemoType.md)| |
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETDebitMemoType**](GETDebitMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTPostDebitMemo"></a>
# **pUTPostDebitMemo**
> GETDebitMemoType pUTPostDebitMemo(debitMemoId, zuoraEntityIds)
Post debit memo
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Posts a debit memo to activate it. You can post debit memos only if you have the [Billing permissions](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles#Billing_Permissions).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETDebitMemoType result = apiInstance.pUTPostDebitMemo(debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pUTPostDebitMemo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8a8082e65b27f6c3015ba419f3c2644e. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETDebitMemoType**](GETDebitMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUnpostDebitMemo"></a>
# **pUTUnpostDebitMemo**
> GETDebitMemoType pUTUnpostDebitMemo(debitMemoId, zuoraEntityIds)
Unpost debit memo
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Unposts a debit memo that is in Posted status. If any credit memo or payment has been applied to a debit memo, you are not allowed to unpost the debit memo. After a debit memo is unposted, its status becomes Draft. You can unpost debit memos only if you have the [Billing permissions](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles#Billing_Permissions).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DebitMemosApi;
DebitMemosApi apiInstance = new DebitMemosApi();
String debitMemoId = "debitMemoId_example"; // String | The unique ID of a debit memo. For example, 8<KEY>.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETDebitMemoType result = apiInstance.pUTUnpostDebitMemo(debitMemoId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DebitMemosApi#pUTUnpostDebitMemo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**debitMemoId** | **String**| The unique ID of a debit memo. For example, 8<KEY>. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETDebitMemoType**](GETDebitMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# CreatePMPayPalECPayPalNativeEC
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**BAID** | **String** | ID of a PayPal billing agreement. For example, I-1TJ3GAGG82Y9. | [optional]
**email** | **String** | Email address associated with the payment method. This field is required if you want to create a PayPal Express Checkout payment method or a PayPal Adaptive payment method. | [optional]
<file_sep>
# ChargeRatedResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**appliedToChargeNumber** | **String** | The regular charge number that this discount charge is applied to. | [optional]
**chargeNumber** | **String** | | [optional]
**ratedItems** | [**List<RatedItem>**](RatedItem.md) | The amount changes per date duration. | [optional]
<file_sep>
# POSTBillingDocumentFilesDeletionJobResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **String** | The unique ID of the billing document file deletion job. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the billing document file deletion job. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PENDING | "Pending"
<file_sep>
# GetInvoiceApplicationPartType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**appliedAmount** | **Double** | The amount that is applied to the invoice. | [optional]
**createdById** | [**UUID**](UUID.md) | The ID of the Zuora user who created the payment or credit memo. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment or credit memo was created, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-12-01 15:31:10. | [optional]
**creditMemoId** | [**UUID**](UUID.md) | The ID of credit memo that is applied to the specified invoice. | [optional]
**paymentId** | [**UUID**](UUID.md) | The ID of the payment that is applied to the specified invoice. | [optional]
**updatedById** | [**UUID**](UUID.md) | The ID of the Zuora user who last updated the payment or credit memo. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment or credit memo was last updated, in `yyyy-mm-dd hh:mm:ss` format. For example, 2018-01-02 11:42:16. | [optional]
<file_sep>
# GETTaxationItemTypeFinanceInformation
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**onAccountAccountingCode** | **String** | The accounting code that maps to an on account in your accounting system. | [optional]
**onAccountAccountingCodeType** | **String** | The type of the accounting code that maps to an on account in your accounting system. | [optional]
**salesTaxPayableAccountingCode** | **String** | The accounting code for the sales taxes payable. | [optional]
**salesTaxPayableAccountingCodeType** | **String** | The type of the accounting code for the sales taxes payable. | [optional]
<file_sep>
# POSTSubscriptionCancellationResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cancelledDate** | [**LocalDate**](LocalDate.md) | The date that the subscription was canceled. | [optional]
**creditMemoId** | **String** | The credit memo ID, if a credit memo is generated during the subscription process. **Note:** This field is only available if you have the Invoice Settlements feature enabled. | [optional]
**invoiceId** | **String** | ID of the invoice, if one is generated. | [optional]
**paidAmount** | **String** | Amount paid. | [optional]
**paymentId** | **String** | ID of the payment, if a payment is collected. | [optional]
**subscriptionId** | **String** | The subscription ID. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**totalDeltaMrr** | **String** | Change in the subscription monthly recurring revenue as a result of the update. | [optional]
**totalDeltaTcv** | **String** | Change in the total contracted value of the subscription as a result of the update. | [optional]
<file_sep>
# FinanceInformation
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**deferredRevenueAccountingCode** | **String** | The accounting code for deferred revenue, such as Monthly Recurring Liability. | [optional]
**deferredRevenueAccountingCodeType** | **String** | The type associated with the deferred revenue accounting code, such as Deferred Revenue. | [optional]
**recognizedRevenueAccountingCode** | **String** | The accounting code for recognized revenue, such as Monthly Recurring Charges or Overage Charges. | [optional]
**recognizedRevenueAccountingCodeType** | **String** | The type associated with the recognized revenue accounting code, such as Sales Revenue or Sales Discount. | [optional]
<file_sep>
# GETAccountingPeriodTypeFileIds
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountsReceivableAccountAgingDetailExportFileId** | **String** | File ID of the Accounts Receivable Aging Account Detail report. | [optional]
**accountsReceivableInvoiceAgingDetailExportFileId** | **String** | File ID of the Accounts Receivable Aging Invoice Detail report. | [optional]
**arRollForwardDetailExportFileId** | **String** | File ID of the Accounts Receivable Detail report. | [optional]
**fxRealizedGainAndLossDetailExportFileId** | **String** | File ID of the Realized Gain and Loss Detail report. Returned only if you have Foreign Currency Conversion enabled. | [optional]
**fxUnrealizedGainAndLossDetailExportFileId** | **String** | File ID of the Unrealized Gain and Loss Detail report. Returned only if you have Foreign Currency Conversion enabled | [optional]
**revenueDetailCsvFileId** | **String** | File ID of the Revenue Detail report in CSV format. | [optional]
**revenueDetailExcelFileId** | **String** | File ID of the Revenue Detail report in XLSX format. | [optional]
**unprocessedChargesFileId** | **String** | File ID of a report containing all unprocessed charges for the accounting period. | [optional]
<file_sep>
# EventType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**description** | **String** | The description of the event type. | [optional]
**displayName** | **String** | The display name for the event type. |
**name** | **String** | The name of the event. Should be unique, contain no space, and be in the pattern: ^[A-Za-z]{1,}[\\\\w\\\\-]*$ |
<file_sep>
# ProxyActiongenerateRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**objects** | [**List<ZObject>**](ZObject.md) | |
**type** | [**TypeEnum**](#TypeEnum) | |
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
INVOICE | "Invoice"
<file_sep>
# GETCatalogType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nextPage** | **String** | URL to retrieve the next page of the response if it exists; otherwise absent. | [optional]
**products** | [**List<GETProductType>**](GETProductType.md) | Container for one or more products: | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<file_sep>
# GETRevenueEventDetailsType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nextPage** | **String** | URL to retrieve the next page of the response if it exists; otherwise absent. | [optional]
**revenueEventDetails** | [**List<GETRevenueEventDetailWithoutSuccessType>**](GETRevenueEventDetailWithoutSuccessType.md) | Represents a change to a revenue schedule, such as posting an invoice or distributing revenue. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<file_sep>
# PreviewOrderCreateSubscription
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoiceSeparately** | **Boolean** | Specifies whether the subscription appears on a separate invoice when Zuora generates invoices. | [optional]
**newSubscriptionOwnerAccount** | [**PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount**](PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount.md) | | [optional]
**notes** | **String** | Notes about the subscription. These notes are only visible to Zuora users. | [optional]
**subscribeToRatePlans** | [**List<PreviewOrderRatePlanOverride>**](PreviewOrderRatePlanOverride.md) | List of rate plans associated with the subscription. | [optional]
**subscriptionNumber** | **String** | Subscription number of the subscription. For example, A-S00000001. If you do not set this field, Zuora will generate the subscription number. | [optional]
**subscriptionOwnerAccountNumber** | **String** | Account number of an existing account that will own the subscription. For example, A00000001. If you do not set this field or the `newSubscriptionOwnerAccount` field, the account that owns the order will also own the subscription. Zuora will return an error if you set this field and the `newSubscriptionOwnerAccount` field. | [optional]
**terms** | [**CreateOrderCreateSubscriptionTerms**](CreateOrderCreateSubscriptionTerms.md) | | [optional]
<file_sep># UnitOfMeasureApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEUnitOfMeasure**](UnitOfMeasureApi.md#objectDELETEUnitOfMeasure) | **DELETE** /v1/object/unit-of-measure/{id} | CRUD: Delete UnitOfMeasure
[**objectGETUnitOfMeasure**](UnitOfMeasureApi.md#objectGETUnitOfMeasure) | **GET** /v1/object/unit-of-measure/{id} | CRUD: Retrieve UnitOfMeasure
[**objectPOSTUnitOfMeasure**](UnitOfMeasureApi.md#objectPOSTUnitOfMeasure) | **POST** /v1/object/unit-of-measure | CRUD: Create UnitOfMeasure
[**objectPUTUnitOfMeasure**](UnitOfMeasureApi.md#objectPUTUnitOfMeasure) | **PUT** /v1/object/unit-of-measure/{id} | CRUD: Update UnitOfMeasure
<a name="objectDELETEUnitOfMeasure"></a>
# **objectDELETEUnitOfMeasure**
> ProxyDeleteResponse objectDELETEUnitOfMeasure(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete UnitOfMeasure
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UnitOfMeasureApi;
UnitOfMeasureApi apiInstance = new UnitOfMeasureApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEUnitOfMeasure(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UnitOfMeasureApi#objectDELETEUnitOfMeasure");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETUnitOfMeasure"></a>
# **objectGETUnitOfMeasure**
> ProxyGetUnitOfMeasure objectGETUnitOfMeasure(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve UnitOfMeasure
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UnitOfMeasureApi;
UnitOfMeasureApi apiInstance = new UnitOfMeasureApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetUnitOfMeasure result = apiInstance.objectGETUnitOfMeasure(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UnitOfMeasureApi#objectGETUnitOfMeasure");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetUnitOfMeasure**](ProxyGetUnitOfMeasure.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTUnitOfMeasure"></a>
# **objectPOSTUnitOfMeasure**
> ProxyCreateOrModifyResponse objectPOSTUnitOfMeasure(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create UnitOfMeasure
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UnitOfMeasureApi;
UnitOfMeasureApi apiInstance = new UnitOfMeasureApi();
ProxyCreateUnitOfMeasure createRequest = new ProxyCreateUnitOfMeasure(); // ProxyCreateUnitOfMeasure |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTUnitOfMeasure(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UnitOfMeasureApi#objectPOSTUnitOfMeasure");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateUnitOfMeasure**](ProxyCreateUnitOfMeasure.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTUnitOfMeasure"></a>
# **objectPUTUnitOfMeasure**
> ProxyCreateOrModifyResponse objectPUTUnitOfMeasure(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update UnitOfMeasure
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UnitOfMeasureApi;
UnitOfMeasureApi apiInstance = new UnitOfMeasureApi();
String id = "id_example"; // String | Object id
ProxyModifyUnitOfMeasure modifyRequest = new ProxyModifyUnitOfMeasure(); // ProxyModifyUnitOfMeasure |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTUnitOfMeasure(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UnitOfMeasureApi#objectPUTUnitOfMeasure");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyUnitOfMeasure**](ProxyModifyUnitOfMeasure.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># FeaturesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEFeature**](FeaturesApi.md#objectDELETEFeature) | **DELETE** /v1/object/feature/{id} | CRUD: Delete Feature
[**objectGETFeature**](FeaturesApi.md#objectGETFeature) | **GET** /v1/object/feature/{id} | CRUD: Retrieve Feature
<a name="objectDELETEFeature"></a>
# **objectDELETEFeature**
> ProxyDeleteResponse objectDELETEFeature(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Feature
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.FeaturesApi;
FeaturesApi apiInstance = new FeaturesApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEFeature(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling FeaturesApi#objectDELETEFeature");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETFeature"></a>
# **objectGETFeature**
> ProxyGetFeature objectGETFeature(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Feature
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.FeaturesApi;
FeaturesApi apiInstance = new FeaturesApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetFeature result = apiInstance.objectGETFeature(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling FeaturesApi#objectGETFeature");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetFeature**](ProxyGetFeature.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# SubscribeRequestSubscribeOptionsSubscribeInvoiceProcessingOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoiceDate** | [**LocalDate**](LocalDate.md) | | [optional]
**invoiceProcessingScope** | **String** | | [optional]
**invoiceTargetDate** | [**LocalDate**](LocalDate.md) | | [optional]
<file_sep>
# ProxyGetCreditBalanceAdjustment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the credit balance adjustment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the credit balance adjustment was sychronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The account ID of the credit balance's account. Zuora generates this value from the source transaction. **Character limit**: 32 **V****alues**: automatically generated from: - CreditBalanceAdjustment.SourceTransactionId or - CreditBalanceAdjustment.SourceTransactionNumber | [optional]
**accountingCode** | **String** | The Chart of Accounts | [optional]
**adjustmentDate** | [**LocalDate**](LocalDate.md) | The date when the credit balance adjustment is applied. **Character limit**: 29 **Values**: automatically generated | [optional]
**amount** | **Double** | The amount of the adjustment. **Character limit**: 16 **Values**: a valid currency amount | [optional]
**cancelledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the credit balance adjustment was canceled. **Character limit**: 29 **Values**: automatically generated | [optional]
**comment** | **String** | Use this field to record comments about the credit balance adjustment. **Character limit**: 255 **Values**: a string of 255 characters or fewer | [optional]
**createdById** | **String** | The user ID of the person who created the credit balance adjustment. **Character limit**: 32 **Values**: automatically generated | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the credit balance adjustmentwas generated. **Character limit**: 29 **Values**: automatically generated | [optional]
**id** | **String** | Object identifier. | [optional]
**number** | **String** | A unique identifier for the credit balance adjustment. Zuora generates this number in the format, <em>CBA-xxxxxxxx</em>, such as CBA-00375919. **Character limit**: 255 **Values**: automatically generated | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. Must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. **Character limit**: 32 **V****alues**: a valid reason code | [optional]
**referenceId** | **String** | The ID of the payment that the credit balance adjustment is for. **Character limit**: 32 **Values**: a string of 60 characters or fewer | [optional]
**sourceTransactionId** | **String** | The ID of the object that the credit balance adjustment is applied to. You must specify a value for either the `SourceTransactionId` field or the `SourceTransactionNumber` field. **Character limit**: 32 **Values**: one of the following: - InvoiceId - PaymentId - RefundId | [optional]
**sourceTransactionNumber** | **String** | The number of the object that the credit balance adjustment is applied to. You must specify a value for either the `SourceTransactionId` field or the `SourceTransactionNumber` field. **Character limit**: 50 **Values**: one of the following: - InvoiceNumber - PaymentNumber - RefundNumber | [optional]
**sourceTransactionType** | **String** | The source of the credit balance adjustment. **Character limit**: **Values**: automatically generated; one of the following: - Invoice - Payment - Refund | [optional]
**status** | **String** | The status of the credit balance adjustment. **Character limit**: 9 **Values**: automatically generated; one of the following: - Processed - Canceled | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Indicates the status of the credit balance adjustment's transfer to an external accounting system, such as NetSuite. | [optional]
**type** | **String** | Create Query Filter | [optional]
**updatedById** | **String** | The ID of the user who last updated the credit balance adjustment. **Character limit**: 32 **Values**: automatically generated | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the credit balance adjustment was last updated. **Character limit**: 29 **Values**: automatically generated | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
NO | "No"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# CreditCard
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cardHolderInfo** | [**AccountCreditCardHolder**](AccountCreditCardHolder.md) | | [optional]
**cardNumber** | **String** | Card number. Once set, you cannot update or query the value of this field. The value of this field is only available in masked format. For example, XXXX-XXXX-XXXX-1234. | [optional]
**cardType** | [**CardTypeEnum**](#CardTypeEnum) | Type of card. | [optional]
**expirationMonth** | **Integer** | Expiration date of the card. | [optional]
**expirationYear** | **Integer** | Expiration year of the card. | [optional]
**securityCode** | **String** | CVV or CVV2 security code of the card. To ensure PCI compliance, Zuora does not store the value of this field. | [optional]
<a name="CardTypeEnum"></a>
## Enum: CardTypeEnum
Name | Value
---- | -----
VISA | "Visa"
MASTERCARD | "MasterCard"
AMERICANEXPRESS | "AmericanExpress"
DISCOVER | "Discover"
JCB | "JCB"
DINERS | "Diners"
CUP | "CUP"
MAESTRO | "Maestro"
ELECTRON | "Electron"
APPLEVISA | "AppleVisa"
APPLEMASTERCARD | "AppleMasterCard"
APPLEAMERICANEXPRESS | "AppleAmericanExpress"
APPLEDISCOVER | "AppleDiscover"
APPLEJCB | "AppleJCB"
ELO | "Elo"
HIPERCARD | "Hipercard"
NARANJA | "Naranja"
NATIVA | "Nativa"
TARJETASHOPPING | "TarjetaShopping"
CENCOSUD | "Cencosud"
ARGENCARD | "Argencard"
CABAL | "Cabal"
<file_sep>
# ProxyActionqueryMoreResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**done** | **Boolean** | | [optional]
**queryLocator** | **String** | | [optional]
**records** | [**List<ZObject>**](ZObject.md) | | [optional]
**size** | **Integer** | | [optional]
<file_sep>
# GETAccountType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**basicInfo** | [**GETAccountTypeBasicInfo**](GETAccountTypeBasicInfo.md) | | [optional]
**billToContact** | [**GETAccountTypeBillToContact**](GETAccountTypeBillToContact.md) | | [optional]
**billingAndPayment** | [**GETAccountTypeBillingAndPayment**](GETAccountTypeBillingAndPayment.md) | | [optional]
**metrics** | [**GETAccountTypeMetrics**](GETAccountTypeMetrics.md) | | [optional]
**soldToContact** | [**GETAccountTypeSoldToContact**](GETAccountTypeSoldToContact.md) | | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**taxInfo** | [**GETAccountSummaryTypeTaxInfo**](GETAccountSummaryTypeTaxInfo.md) | | [optional]
<file_sep>
# UsagePerUnitPricingUpdate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**priceChangeOption** | [**PriceChangeOptionEnum**](#PriceChangeOptionEnum) | Specifies how Zuora changes the price of the charge each time the subscription renews. If the value of this field is `SpecificPercentageValue`, use the `priceIncreasePercentage` field to specify how much the price of the charge should change. | [optional]
**priceIncreasePercentage** | [**BigDecimal**](BigDecimal.md) | Specifies the percentage by which the price of the charge should change each time the subscription renews. Only applicable if the value of the `priceChangeOption` field is `SpecificPercentageValue`. | [optional]
**listPrice** | [**BigDecimal**](BigDecimal.md) | | [optional]
<a name="PriceChangeOptionEnum"></a>
## Enum: PriceChangeOptionEnum
Name | Value
---- | -----
NOCHANGE | "NoChange"
SPECIFICPERCENTAGEVALUE | "SpecificPercentageValue"
USELATESTPRODUCTCATALOGPRICING | "UseLatestProductCatalogPricing"
<file_sep>
# ProxyGetPaymentTransactionLog
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**avSResponseCode** | **String** | The response code returned by the payment gateway referring to the AVS international response of the payment transaction. | [optional]
**batchId** | **String** | The ID of the batch used to send the transaction if the request was sent in a batch. | [optional]
**cvVResponseCode** | **String** | The response code returned by the payment gateway referring to the CVV international response of the payment transaction. | [optional]
**gateway** | **String** | The name of the payment gateway used to transact the current payment transaction log. | [optional]
**gatewayReasonCode** | **String** | The code returned by the payment gateway for the payment. This code is gateway-dependent. | [optional]
**gatewayReasonCodeDescription** | **String** | The message returned by the payment gateway for the payment. This message is gateway-dependent. | [optional]
**gatewayState** | [**GatewayStateEnum**](#GatewayStateEnum) | The state of the transaction at the payment gateway. | [optional]
**gatewayTransactionType** | [**GatewayTransactionTypeEnum**](#GatewayTransactionTypeEnum) | The type of the transaction, either making a payment, or canceling a payment. | [optional]
**id** | **String** | The ID of the payment transaction log. | [optional]
**paymentId** | **String** | The ID of the payment wherein the payment transaction log was recorded. | [optional]
**requestString** | **String** | The payment transaction request string sent to the payment gateway. | [optional]
**responseString** | **String** | The payment transaction response string returned by the payment gateway. | [optional]
**transactionDate** | [**OffsetDateTime**](OffsetDateTime.md) | The transaction date when the payment was performed. | [optional]
**transactionId** | **String** | The transaction ID returned by the payment gateway. This field is used to reconcile payment transactions between the payment gateway and records in Zuora. | [optional]
<a name="GatewayStateEnum"></a>
## Enum: GatewayStateEnum
Name | Value
---- | -----
MARKEDFORSUBMISSION | "MarkedForSubmission"
SUBMITTED | "Submitted"
SETTLED | "Settled"
NOTSUBMITTED | "NotSubmitted"
FAILEDTOSETTLE | "FailedToSettle"
<a name="GatewayTransactionTypeEnum"></a>
## Enum: GatewayTransactionTypeEnum
Name | Value
---- | -----
AUTHORIZATION | "Authorization"
SALE | "Sale"
VOID | "Void"
INQUIRY | "Inquiry"
VOIDAUTH | "VoidAuth"
<file_sep>
# UnapplyPaymentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**debitMemos** | [**List<PaymentDebitMemoApplicationUnapplyRequestType>**](PaymentDebitMemoApplicationUnapplyRequestType.md) | Container for debit memos. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the payment is unapplied, in `yyyy-mm-dd` format. | [optional]
**invoices** | [**List<PaymentInvoiceApplicationUnapplyRequestType>**](PaymentInvoiceApplicationUnapplyRequestType.md) | Container for invoices. | [optional]
<file_sep># SettingsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETRevenueAutomationStartDate**](SettingsApi.md#gETRevenueAutomationStartDate) | **GET** /v1/settings/finance/revenue-automation-start-date | Get the revenue automation start date
<a name="gETRevenueAutomationStartDate"></a>
# **gETRevenueAutomationStartDate**
> GETRevenueStartDateSettingType gETRevenueAutomationStartDate(zuoraEntityIds)
Get the revenue automation start date
This REST API reference describes how to get the revenue automation start date. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SettingsApi;
SettingsApi apiInstance = new SettingsApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRevenueStartDateSettingType result = apiInstance.gETRevenueAutomationStartDate(zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SettingsApi#gETRevenueAutomationStartDate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRevenueStartDateSettingType**](GETRevenueStartDateSettingType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# GetBillingPreviewRunResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**assumeRenewal** | **String** | | [optional]
**batch** | **String** | The customer batch included in the billing preview run. | [optional]
**chargeTypeToExclude** | **String** | The charge types excluded from the forecast run. | [optional]
**createdById** | **String** | The ID of the user who created the billing preview run. | [optional]
**createdDate** | **String** | The date and time when the billing preview run was created. | [optional]
**endDate** | **String** | The date and time when the billing preview run completes. | [optional]
**errorMessage** | **String** | The error message generated by a failed billing preview run. | [optional]
**includingEvergreenSubscription** | **Boolean** | Indicates if evergreen subscriptions are included in the billing preview run. | [optional]
**resultFileUrl** | **String** | The URL of the zipped CSV result file generated by the billing preview run. This file contains the preview invoice item data and credit memo item data for the specified customers. **Note:** The credit memo item data is only available if you have Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). | [optional]
**runNumber** | **String** | The run number of the billing preview run. | [optional]
**startDate** | **String** | The date and time when the billing preview run starts. | [optional]
**status** | **String** | The status of the >billing preview run. **Possible values:** * 0: Pending * 1: Processing * 2: Completed * 3: Error * 4: Canceled | [optional]
**succeededAccounts** | **Integer** | The number of accounts for which preview invoice item data and credit memo item data was successfully generated during the billing preview run. **Note:** The credit memo item data is only available if you have Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | The target date for the billing preview run. | [optional]
**totalAccounts** | **Integer** | The total number of accounts in the billing preview run. | [optional]
**updatedById** | **String** | The ID of the user who last updated the billing preview run. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the billing preview run was last updated. | [optional]
<file_sep>
# ProxyActionqueryMoreRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**queryLocator** | **String** | |
<file_sep>
# ChargePreviewMetricsTax
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**discount** | [**BigDecimal**](BigDecimal.md) | Total tax amount of all discount charges which are applied to one specific recurring charge. This value is calculated from the rating results for the latest subscription version in the order. | [optional]
**discountDelta** | [**BigDecimal**](BigDecimal.md) | Delta discount TAX value between the base and the latest subscription version in the order for the specific recurring charge. | [optional]
**regular** | [**BigDecimal**](BigDecimal.md) | | [optional]
**regularDelta** | [**BigDecimal**](BigDecimal.md) | Delta tax value between the base and the latest subscription version in the order. | [optional]
<file_sep># InvoicesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETInvoiceApplicationParts**](InvoicesApi.md#gETInvoiceApplicationParts) | **GET** /v1/invoices/{invoiceId}/application-parts | Get invoice application parts
[**gETInvoiceFiles**](InvoicesApi.md#gETInvoiceFiles) | **GET** /v1/invoices/{invoice-id}/files | Get invoice files
[**gETInvoiceItems**](InvoicesApi.md#gETInvoiceItems) | **GET** /v1/invoices/{invoice-id}/items | Get invoice items
[**objectDELETEInvoice**](InvoicesApi.md#objectDELETEInvoice) | **DELETE** /v1/object/invoice/{id} | CRUD: Delete Invoice
[**objectGETInvoice**](InvoicesApi.md#objectGETInvoice) | **GET** /v1/object/invoice/{id} | CRUD: Retrieve Invoice
[**objectPUTInvoice**](InvoicesApi.md#objectPUTInvoice) | **PUT** /v1/object/invoice/{id} | CRUD: Update Invoice
[**pOSTCreditMemoFromInvoice**](InvoicesApi.md#pOSTCreditMemoFromInvoice) | **POST** /v1/invoices/{invoiceId}/creditmemos | Create credit memo from invoice
[**pOSTDebitMemoFromInvoice**](InvoicesApi.md#pOSTDebitMemoFromInvoice) | **POST** /v1/invoices/{invoiceId}/debitmemos | Create debit memo from invoice
[**pOSTEmailInvoice**](InvoicesApi.md#pOSTEmailInvoice) | **POST** /v1/invoices/{invoiceId}/emails | Email invoice
[**pUTBatchUpdateInvoices**](InvoicesApi.md#pUTBatchUpdateInvoices) | **PUT** /v1/invoices | Update invoices
[**pUTReverseInvoice**](InvoicesApi.md#pUTReverseInvoice) | **PUT** /v1/invoices/{invoiceId}/reverse | Reverse invoice
[**pUTUpdateInvoice**](InvoicesApi.md#pUTUpdateInvoice) | **PUT** /v1/invoices/{invoiceId} | Update invoice
[**pUTWriteOffInvoice**](InvoicesApi.md#pUTWriteOffInvoice) | **PUT** /v1/invoices/{invoiceId}/write-off | Write off invoice
<a name="gETInvoiceApplicationParts"></a>
# **gETInvoiceApplicationParts**
> GetInvoiceApplicationPartCollectionType gETInvoiceApplicationParts(invoiceId, zuoraEntityIds)
Get invoice application parts
Note: The Invoice Settlement feature is in Limited Availability. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at Zuora Global Support. Retrieves information about the payments or credit memos that are applied to a specified invoice.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String invoiceId = "invoiceId_example"; // String | The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetInvoiceApplicationPartCollectionType result = apiInstance.gETInvoiceApplicationParts(invoiceId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#gETInvoiceApplicationParts");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceId** | **String**| The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetInvoiceApplicationPartCollectionType**](GetInvoiceApplicationPartCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETInvoiceFiles"></a>
# **gETInvoiceFiles**
> GETInvoiceFilesResponse gETInvoiceFiles(invoiceId, zuoraEntityIds, pageSize)
Get invoice files
Retrieves the information about all PDF files of a specified invoice. Invoice PDF files are returned in reverse chronological order by the value of the `versionNumber` field.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String invoiceId = "invoiceId_example"; // String | The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETInvoiceFilesResponse result = apiInstance.gETInvoiceFiles(invoiceId, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#gETInvoiceFiles");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceId** | **String**| The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETInvoiceFilesResponse**](GETInvoiceFilesResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETInvoiceItems"></a>
# **gETInvoiceItems**
> GETInvoiceItemsResponse gETInvoiceItems(invoiceId, zuoraEntityIds, pageSize)
Get invoice items
Retrieves the information about all items of a specified invoice.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String invoiceId = "invoiceId_example"; // String | The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETInvoiceItemsResponse result = apiInstance.gETInvoiceItems(invoiceId, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#gETInvoiceItems");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceId** | **String**| The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETInvoiceItemsResponse**](GETInvoiceItemsResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETEInvoice"></a>
# **objectDELETEInvoice**
> ProxyDeleteResponse objectDELETEInvoice(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Invoice
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEInvoice(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#objectDELETEInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETInvoice"></a>
# **objectGETInvoice**
> ProxyGetInvoice objectGETInvoice(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Invoice
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetInvoice result = apiInstance.objectGETInvoice(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#objectGETInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetInvoice**](ProxyGetInvoice.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTInvoice"></a>
# **objectPUTInvoice**
> ProxyCreateOrModifyResponse objectPUTInvoice(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update Invoice
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String id = "id_example"; // String | Object id
ProxyModifyInvoice modifyRequest = new ProxyModifyInvoice(); // ProxyModifyInvoice |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTInvoice(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#objectPUTInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyInvoice**](ProxyModifyInvoice.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTCreditMemoFromInvoice"></a>
# **pOSTCreditMemoFromInvoice**
> GETCreditMemoType pOSTCreditMemoFromInvoice(body, invoiceId, zuoraEntityIds)
Create credit memo from invoice
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates an ad-hoc credit memo from an invoice. You can create a credit memo from an invoice only if you have the user permission. See [Billing Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
CreditMemoFromInvoiceType body = new CreditMemoFromInvoiceType(); // CreditMemoFromInvoiceType |
String invoiceId = "invoiceId_example"; // String | The ID of an invoice that you want to create a credit memo from.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETCreditMemoType result = apiInstance.pOSTCreditMemoFromInvoice(body, invoiceId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#pOSTCreditMemoFromInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**CreditMemoFromInvoiceType**](CreditMemoFromInvoiceType.md)| |
**invoiceId** | **String**| The ID of an invoice that you want to create a credit memo from. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETCreditMemoType**](GETCreditMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTDebitMemoFromInvoice"></a>
# **pOSTDebitMemoFromInvoice**
> GETDebitMemoType pOSTDebitMemoFromInvoice(invoiceId, body, zuoraEntityIds)
Create debit memo from invoice
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates an ad-hoc debit memo from an invoice. You can create a debit memo from an invoice only if you have the user permission. See [Billing Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/d_Billing_Roles) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String invoiceId = "invoiceId_example"; // String | The ID of an invoice that you want to create a debit memo from.
DebitMemoFromInvoiceType body = new DebitMemoFromInvoiceType(); // DebitMemoFromInvoiceType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETDebitMemoType result = apiInstance.pOSTDebitMemoFromInvoice(invoiceId, body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#pOSTDebitMemoFromInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceId** | **String**| The ID of an invoice that you want to create a debit memo from. |
**body** | [**DebitMemoFromInvoiceType**](DebitMemoFromInvoiceType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETDebitMemoType**](GETDebitMemoType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTEmailInvoice"></a>
# **pOSTEmailInvoice**
> CommonResponseType pOSTEmailInvoice(request, invoiceId, zuoraEntityIds)
Email invoice
Sends a posted invoice to the specified email addresses manually. ## Notes - You must activate the **Manual Email For Invoice | Manual Email For Invoice** notification before emailing invoices. To include the invoice PDF in the email, select the **Include Invoice PDF** check box in the **Edit notification** dialog from the Zuora UI. See [Create and Edit Notifications](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/Notifications/C_Create_Notifications#section_2) for more information. - Zuora sends the email messages based on the email template you set. You can set the email template to use in the **Delivery Options** panel of the **Edit notification** dialog from the Zuora UI. By default, the **Invoice Posted Default Email Template** template is used. See [Create and Edit Email Templates](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/Notifications/Create_Email_Templates) for more information. - The invoices are sent only to the work email addresses or personal email addresses of the Bill To contact if the following conditions are all met: * The `useEmailTemplateSetting` field is set to `false`. * The email addresses are not specified in the `emailAddresses` field.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
PostInvoiceEmailRequestType request = new PostInvoiceEmailRequestType(); // PostInvoiceEmailRequestType |
String invoiceId = "invoiceId_example"; // String | The ID of the invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pOSTEmailInvoice(request, invoiceId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#pOSTEmailInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**PostInvoiceEmailRequestType**](PostInvoiceEmailRequestType.md)| |
**invoiceId** | **String**| The ID of the invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTBatchUpdateInvoices"></a>
# **pUTBatchUpdateInvoices**
> CommonResponseType pUTBatchUpdateInvoices(request, zuoraEntityIds)
Update invoices
Updates multiple invoices in batches with one call.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
PutBatchInvoiceType request = new PutBatchInvoiceType(); // PutBatchInvoiceType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTBatchUpdateInvoices(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#pUTBatchUpdateInvoices");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**PutBatchInvoiceType**](PutBatchInvoiceType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTReverseInvoice"></a>
# **pUTReverseInvoice**
> PutReverseInvoiceResponseType pUTReverseInvoice(invoiceId, request, zuoraEntityIds)
Reverse invoice
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Reverses a posted invoice. **Restrictions** You are not allowed to reverse an invoice if one of the following restrictions is met: * Payments and credit memos are applied to the invoice. * The invoice is split. * The invoice is not in Posted status. * The total amount of the invoice is less than 0 (a negative invoice). * Using Tax Connector for Extension Platform to calculate taxes. See [Reverse Posted Invoices](https://knowledgecenter.zuora.com/CB_Billing/IA_Invoices/Reverse_Posted_Invoices) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String invoiceId = "invoiceId_example"; // String | The ID of the invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab.
PutReverseInvoiceType request = new PutReverseInvoiceType(); // PutReverseInvoiceType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PutReverseInvoiceResponseType result = apiInstance.pUTReverseInvoice(invoiceId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#pUTReverseInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceId** | **String**| The ID of the invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab. |
**request** | [**PutReverseInvoiceType**](PutReverseInvoiceType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PutReverseInvoiceResponseType**](PutReverseInvoiceResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUpdateInvoice"></a>
# **pUTUpdateInvoice**
> PutInvoiceResponseType pUTUpdateInvoice(invoiceId, request, zuoraEntityIds)
Update invoice
Updates a specific invoice.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String invoiceId = "invoiceId_example"; // String | The ID of the invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab.
PutInvoiceType request = new PutInvoiceType(); // PutInvoiceType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PutInvoiceResponseType result = apiInstance.pUTUpdateInvoice(invoiceId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#pUTUpdateInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceId** | **String**| The ID of the invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab. |
**request** | [**PutInvoiceType**](PutInvoiceType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PutInvoiceResponseType**](PutInvoiceResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTWriteOffInvoice"></a>
# **pUTWriteOffInvoice**
> PUTWriteOffInvoiceResponse pUTWriteOffInvoice(invoiceId, request, zuoraEntityIds)
Write off invoice
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Writes off a posted invoice. By writing off an invoice, a credit memo is created and applied to the invoice. The credit memo items and credit memo taxation items are one-to-one mapped to invoice items and invoice of the invoice. If an invoice is written off, the balance of each invoice item and invoice taxation item must be zero. An invoice cannot be written off in the following situations: - Any transactions such as payments or credit memos are applied to an invoice. - The balance of an invoice has been changed.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoicesApi;
InvoicesApi apiInstance = new InvoicesApi();
String invoiceId = "invoiceId_example"; // String | The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab.
PUTWriteOffInvoiceRequest request = new PUTWriteOffInvoiceRequest(); // PUTWriteOffInvoiceRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTWriteOffInvoiceResponse result = apiInstance.pUTWriteOffInvoice(invoiceId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoicesApi#pUTWriteOffInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceId** | **String**| The unique ID of an invoice. For example, 2c92c8955bd63cc1015bd7c151af02ab. |
**request** | [**PUTWriteOffInvoiceRequest**](PUTWriteOffInvoiceRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTWriteOffInvoiceResponse**](PUTWriteOffInvoiceResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# NewChargeMetrics
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeNumber** | **String** | | [optional]
**DMRR** | **Double** | | [optional]
**DTCV** | **Double** | | [optional]
**MRR** | **Double** | | [optional]
**originalId** | **String** | | [optional]
**originalRatePlanId** | **String** | | [optional]
**productRatePlanChargeId** | **String** | | [optional]
**productRatePlanId** | **String** | | [optional]
**TCV** | **Double** | | [optional]
<file_sep>
# PaymentInvoiceApplicationApplyRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The amount that is applied from the payment to the invoice. |
**invoiceId** | **String** | The unique ID of the invoice that the payment is applied to. | [optional]
**items** | [**List<PaymentInvoiceApplicationItemApplyRequestType>**](PaymentInvoiceApplicationItemApplyRequestType.md) | Container for invoice items. **Note:** The Invoice Item Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). | [optional]
<file_sep>
# GETSubscriptionType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cpqBundleJsonIdQT** | **String** | The Bundle product structures from Zuora Quotes if you utilize Bundling in Salesforce. Do not change the value in this field. | [optional]
**opportunityCloseDateQT** | [**LocalDate**](LocalDate.md) | The closing date of the Opportunity. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**opportunityNameQT** | **String** | The unique identifier of the Opportunity. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteBusinessTypeQT** | **String** | The specific identifier for the type of business transaction the Quote represents such as New, Upsell, Downsell, Renewal or Churn. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteNumberQT** | **String** | The unique identifier of the Quote. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteTypeQT** | **String** | The Quote type that represents the subscription lifecycle stage such as New, Amendment, Renew or Cancel. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the subscription's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**projectNS** | **String** | The NetSuite project that the subscription was created from. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**salesOrderNS** | **String** | The NetSuite sales order than the subscription was created from. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the subscription was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | | [optional]
**accountName** | **String** | | [optional]
**accountNumber** | **String** | | [optional]
**autoRenew** | **Boolean** | If `true`, the subscription automatically renews at the end of the term. Default is `false`. | [optional]
**contractEffectiveDate** | [**LocalDate**](LocalDate.md) | Effective contract date for this subscription, as yyyy-mm-dd. | [optional]
**contractedMrr** | **String** | Monthly recurring revenue of the subscription. | [optional]
**currentTerm** | **Long** | The length of the period for the current subscription term. | [optional]
**currentTermPeriodType** | **String** | The period type for the current subscription term. Values are: * `Month` (default) * `Year` * `Day` * `Week` | [optional]
**customerAcceptanceDate** | [**LocalDate**](LocalDate.md) | The date on which the services or products within a subscription have been accepted by the customer, as yyyy-mm-dd. | [optional]
**id** | **String** | Subscription ID. | [optional]
**initialTerm** | **Long** | The length of the period for the first subscription term. | [optional]
**initialTermPeriodType** | **String** | The period type for the first subscription term. Values are: * `Month` (default) * `Year` * `Day` * `Week` | [optional]
**invoiceOwnerAccountId** | **String** | | [optional]
**invoiceOwnerAccountName** | **String** | | [optional]
**invoiceOwnerAccountNumber** | **String** | | [optional]
**invoiceSeparately** | **String** | Separates a single subscription from other subscriptions and creates an invoice for the subscription. If the value is `true`, the subscription is billed separately from other subscriptions. If the value is `false`, the subscription is included with other subscriptions in the account invoice. | [optional]
**notes** | **String** | A string of up to 65,535 characters. | [optional]
**orderNumber** | **String** | The order number of the order in which the changes on the subscription are made. **Note:** This field is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. | [optional]
**ratePlans** | [**List<GETSubscriptionRatePlanType>**](GETSubscriptionRatePlanType.md) | Container for rate plans. | [optional]
**renewalSetting** | **String** | Specifies whether a termed subscription will remain `TERMED` or change to `EVERGREEN` when it is renewed. Values are: * `RENEW_WITH_SPECIFIC_TERM` (default) * `RENEW_TO_EVERGREEN` | [optional]
**renewalTerm** | **Long** | The length of the period for the subscription renewal term. | [optional]
**renewalTermPeriodType** | **String** | The period type for the subscription renewal term. Values are: * `Month` (default) * `Year` * `Day` * `Week` | [optional]
**serviceActivationDate** | [**LocalDate**](LocalDate.md) | The date on which the services or products within a subscription have been activated and access has been provided to the customer, as yyyy-mm-dd | [optional]
**status** | **String** | Subscription status; possible values are: * `Draft` * `PendingActivation` * `PendingAcceptance` * `Active` * `Cancelled` * `Suspended` (This value is in Limited Availability.) | [optional]
**subscriptionNumber** | **String** | | [optional]
**subscriptionStartDate** | [**LocalDate**](LocalDate.md) | Date the subscription becomes effective. | [optional]
**termEndDate** | [**LocalDate**](LocalDate.md) | Date the subscription term ends. If the subscription is evergreen, this is null or is the cancellation date (if one has been set). | [optional]
**termStartDate** | [**LocalDate**](LocalDate.md) | Date the subscription term begins. If this is a renewal subscription, this date is different from the subscription start date. | [optional]
**termType** | **String** | Possible values are: `TERMED`, `EVERGREEN`. | [optional]
**totalContractedValue** | **String** | Total contracted value of the subscription. | [optional]
<file_sep>
# ProxyGetPaymentMethodTransactionLog
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**gateway** | **String** | | [optional]
**gatewayReasonCode** | **String** | | [optional]
**gatewayReasonCodeDescription** | **String** | | [optional]
**gatewayTransactionType** | **String** | | [optional]
**id** | **String** | Object identifier. | [optional]
**paymentMethodId** | **String** | | [optional]
**paymentMethodType** | **String** | | [optional]
**requestString** | **String** | | [optional]
**responseString** | **String** | | [optional]
**transactionDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional]
**transactionId** | **String** | | [optional]
<file_sep>
# ProxyPostImport
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **String** | The ID of the Import object that was created. | [optional]
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
<file_sep># RefundsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETERefund**](RefundsApi.md#dELETERefund) | **DELETE** /v1/refunds/{refundId} | Delete refund
[**gETRefund**](RefundsApi.md#gETRefund) | **GET** /v1/refunds/{refundId} | Get refund
[**gETRefundItemPart**](RefundsApi.md#gETRefundItemPart) | **GET** /v1/refunds/{refundId}/parts/{refundpartid}/itemparts/{itempartid} | Get refund part item
[**gETRefundItemParts**](RefundsApi.md#gETRefundItemParts) | **GET** /v1/refunds/{refundId}/parts/{refundpartid}/itemparts | Get refund part items
[**gETRefundPart**](RefundsApi.md#gETRefundPart) | **GET** /v1/refunds/{refundId}/parts/{refundpartid} | Get refund part
[**gETRefundParts**](RefundsApi.md#gETRefundParts) | **GET** /v1/refunds/{refundId}/parts | Get refund parts
[**gETRefunds**](RefundsApi.md#gETRefunds) | **GET** /v1/refunds | Get all refunds
[**objectDELETERefund**](RefundsApi.md#objectDELETERefund) | **DELETE** /v1/object/refund/{id} | CRUD: Delete refund
[**objectGETRefund**](RefundsApi.md#objectGETRefund) | **GET** /v1/object/refund/{id} | CRUD: Get refund
[**objectPOSTRefund**](RefundsApi.md#objectPOSTRefund) | **POST** /v1/object/refund | CRUD: Create refund
[**objectPUTRefund**](RefundsApi.md#objectPUTRefund) | **PUT** /v1/object/refund/{id} | CRUD: Update refund
[**pUTCancelRefund**](RefundsApi.md#pUTCancelRefund) | **PUT** /v1/refunds/{refundId}/cancel | Cancel refund
[**pUTUpdateRefund**](RefundsApi.md#pUTUpdateRefund) | **PUT** /v1/refunds/{refundId} | Update refund
<a name="dELETERefund"></a>
# **dELETERefund**
> CommonResponseType dELETERefund(refundId, zuoraEntityIds)
Delete refund
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Deletes a refund. You can delete a refund with the Canceled or Error status.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETERefund(refundId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#dELETERefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRefund"></a>
# **gETRefund**
> GETRefundType gETRefund(refundId, zuoraEntityIds)
Get refund
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about a specific refund.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRefundType result = apiInstance.gETRefund(refundId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#gETRefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRefundType**](GETRefundType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRefundItemPart"></a>
# **gETRefundItemPart**
> GETRefundItemPartType gETRefundItemPart(itempartid, refundpartid, refundId, zuoraEntityIds)
Get refund part item
**Note:** The Invoice Item Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about a specific refund part item. A refund part item is a single line item in a refund part. A refund part can consist of several different types of items.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String itempartid = "itempartid_example"; // String | The unique ID of a specific refund part item. You can get the refund part item ID from the response of [Get refund part items](https://www.zuora.com/developer/api-reference/#operation/GET_RefundItemParts).
String refundpartid = "refundpartid_example"; // String | The unique ID of a specific refund part. You can get the refund part ID from the response of [Get refund parts](https://www.zuora.com/developer/api-reference/#operation/GET_RefundParts).
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRefundItemPartType result = apiInstance.gETRefundItemPart(itempartid, refundpartid, refundId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#gETRefundItemPart");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**itempartid** | **String**| The unique ID of a specific refund part item. You can get the refund part item ID from the response of [Get refund part items](https://www.zuora.com/developer/api-reference/#operation/GET_RefundItemParts). |
**refundpartid** | **String**| The unique ID of a specific refund part. You can get the refund part ID from the response of [Get refund parts](https://www.zuora.com/developer/api-reference/#operation/GET_RefundParts). |
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRefundItemPartType**](GETRefundItemPartType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRefundItemParts"></a>
# **gETRefundItemParts**
> GETRefundItemPartCollectionType gETRefundItemParts(refundpartid, refundId, zuoraEntityIds, pageSize)
Get refund part items
**Note:** The Invoice Item Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all items of a refund part. A refund part item is a single line item in a refund part. A refund part can consist of several different types of items.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String refundpartid = "refundpartid_example"; // String | The unique ID of a specific refund part. You can get the refund part ID from the response of [Get refund parts](https://www.zuora.com/developer/api-reference/#operation/GET_RefundParts).
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETRefundItemPartCollectionType result = apiInstance.gETRefundItemParts(refundpartid, refundId, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#gETRefundItemParts");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**refundpartid** | **String**| The unique ID of a specific refund part. You can get the refund part ID from the response of [Get refund parts](https://www.zuora.com/developer/api-reference/#operation/GET_RefundParts). |
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETRefundItemPartCollectionType**](GETRefundItemPartCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRefundPart"></a>
# **gETRefundPart**
> RefundPartResponseType gETRefundPart(refundpartid, refundId, zuoraEntityIds)
Get refund part
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about a specific refund part.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String refundpartid = "refundpartid_example"; // String | The unique ID of a specific refund part. You can get the refund part ID from the response of [Get refund parts](https://www.zuora.com/developer/api-reference/#operation/GET_RefundParts).
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
RefundPartResponseType result = apiInstance.gETRefundPart(refundpartid, refundId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#gETRefundPart");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**refundpartid** | **String**| The unique ID of a specific refund part. You can get the refund part ID from the response of [Get refund parts](https://www.zuora.com/developer/api-reference/#operation/GET_RefundParts). |
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**RefundPartResponseType**](RefundPartResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRefundParts"></a>
# **gETRefundParts**
> GETRefundPartCollectionType gETRefundParts(refundId, zuoraEntityIds)
Get refund parts
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all parts of a refund.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRefundPartCollectionType result = apiInstance.gETRefundParts(refundId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#gETRefundParts");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRefundPartCollectionType**](GETRefundPartCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRefunds"></a>
# **gETRefunds**
> GETRefundCollectionType gETRefunds(zuoraEntityIds, pageSize, accountId, amount, createdById, createdDate, methodType, number, paymentId, refundDate, status, type, updatedById, updatedDate, sort)
Get all refunds
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all refunds. Two types of refunds are available, electronic refunds and external refunds. ### Filtering You can use query parameters to restrict the data returned in the response. Each query parameter corresponds to one field in the response body. If the value of a filterable field is string, you can set the corresponding query parameter to `null` when filtering. Then, you can get the response data with this field value being `null`. Examples: - /v1/refunds?status=Processed - /v1/refunds?amount=4&status=Processed - /v1/refunds?status=Processed&type=External&sort=+number
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String accountId = "accountId_example"; // String | This parameter filters the response based on the `accountId` field.
Double amount = 3.4D; // Double | This parameter filters the response based on the `amount` field.
String createdById = "createdById_example"; // String | This parameter filters the response based on the `createdById` field.
OffsetDateTime createdDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `createdDate` field.
String methodType = "methodType_example"; // String | This parameter filters the response based on the `methodType` field.
String number = "number_example"; // String | This parameter filters the response based on the `number` field.
String paymentId = "paymentId_example"; // String | This parameter filters the response based on the `paymentId` field.
LocalDate refundDate = new LocalDate(); // LocalDate | This parameter filters the response based on the `refundDate` field.
String status = "status_example"; // String | This parameter filters the response based on the `status` field.
String type = "type_example"; // String | This parameter filters the response based on the `type` field.
String updatedById = "updatedById_example"; // String | This parameter filters the response based on the `updatedById` field.
OffsetDateTime updatedDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `updatedDate` field.
String sort = "sort_example"; // String | This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by refund number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - number - accountId - amount - refundDate - paymentId - createdDate - createdById - updatedDate - updatedById Examples: - /v1/refunds?sort=+number - /v1/refunds?status=Processed&sort=-number,+amount
try {
GETRefundCollectionType result = apiInstance.gETRefunds(zuoraEntityIds, pageSize, accountId, amount, createdById, createdDate, methodType, number, paymentId, refundDate, status, type, updatedById, updatedDate, sort);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#gETRefunds");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**accountId** | **String**| This parameter filters the response based on the `accountId` field. | [optional]
**amount** | **Double**| This parameter filters the response based on the `amount` field. | [optional]
**createdById** | **String**| This parameter filters the response based on the `createdById` field. | [optional]
**createdDate** | **OffsetDateTime**| This parameter filters the response based on the `createdDate` field. | [optional]
**methodType** | **String**| This parameter filters the response based on the `methodType` field. | [optional] [enum: ACH, Cash, Check, CreditCard, PayPal, WireTransfer, DebitCard, CreditCardReferenceTransaction, BankTransfer, Other]
**number** | **String**| This parameter filters the response based on the `number` field. | [optional]
**paymentId** | **String**| This parameter filters the response based on the `paymentId` field. | [optional]
**refundDate** | **LocalDate**| This parameter filters the response based on the `refundDate` field. | [optional]
**status** | **String**| This parameter filters the response based on the `status` field. | [optional] [enum: Processed, Canceled, Error, Processing]
**type** | **String**| This parameter filters the response based on the `type` field. | [optional] [enum: External, Electronic]
**updatedById** | **String**| This parameter filters the response based on the `updatedById` field. | [optional]
**updatedDate** | **OffsetDateTime**| This parameter filters the response based on the `updatedDate` field. | [optional]
**sort** | **String**| This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by refund number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - number - accountId - amount - refundDate - paymentId - createdDate - createdById - updatedDate - updatedById Examples: - /v1/refunds?sort=+number - /v1/refunds?status=Processed&sort=-number,+amount | [optional]
### Return type
[**GETRefundCollectionType**](GETRefundCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETERefund"></a>
# **objectDELETERefund**
> ProxyDeleteResponse objectDELETERefund(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete refund
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETERefund(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#objectDELETERefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETRefund"></a>
# **objectGETRefund**
> ProxyGetRefund objectGETRefund(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Get refund
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetRefund result = apiInstance.objectGETRefund(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#objectGETRefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetRefund**](ProxyGetRefund.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTRefund"></a>
# **objectPOSTRefund**
> ProxyCreateOrModifyResponse objectPOSTRefund(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create refund
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
ProxyCreateRefund createRequest = new ProxyCreateRefund(); // ProxyCreateRefund |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTRefund(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#objectPOSTRefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateRefund**](ProxyCreateRefund.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTRefund"></a>
# **objectPUTRefund**
> ProxyCreateOrModifyResponse objectPUTRefund(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update refund
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String id = "id_example"; // String | Object id
ProxyModifyRefund modifyRequest = new ProxyModifyRefund(); // ProxyModifyRefund |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTRefund(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#objectPUTRefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyRefund**](ProxyModifyRefund.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTCancelRefund"></a>
# **pUTCancelRefund**
> GETRefundType pUTCancelRefund(refundId, zuoraEntityIds)
Cancel refund
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Cancels a refund.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRefundType result = apiInstance.pUTCancelRefund(refundId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#pUTCancelRefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRefundType**](GETRefundType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUpdateRefund"></a>
# **pUTUpdateRefund**
> GETRefundType pUTUpdateRefund(body, refundId, zuoraEntityIds)
Update refund
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Updates the basic and finance information about a refund.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RefundsApi;
RefundsApi apiInstance = new RefundsApi();
PUTRefundType body = new PUTRefundType(); // PUTRefundType |
String refundId = "refundId_example"; // String | The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRefundType result = apiInstance.pUTUpdateRefund(body, refundId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RefundsApi#pUTUpdateRefund");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**PUTRefundType**](PUTRefundType.md)| |
**refundId** | **String**| The unique ID of a refund. For example, 4028905f5a87c0ff015a889e590e00c9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRefundType**](GETRefundType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# PreviewOrderOrderAction
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**addProduct** | [**PreviewOrderRatePlanOverride**](PreviewOrderRatePlanOverride.md) | | [optional]
**cancelSubscription** | [**CancelSubscription**](CancelSubscription.md) | | [optional]
**createSubscription** | [**PreviewOrderCreateSubscription**](PreviewOrderCreateSubscription.md) | | [optional]
**customFields** | [**OrderActionObjectCustomFields**](OrderActionObjectCustomFields.md) | | [optional]
**ownerTransfer** | [**OwnerTransfer**](OwnerTransfer.md) | | [optional]
**removeProduct** | [**RemoveProduct**](RemoveProduct.md) | | [optional]
**termsAndConditions** | [**TermsAndConditions**](TermsAndConditions.md) | | [optional]
**triggerDates** | [**List<TriggerDate>**](TriggerDate.md) | Container for the contract effective, service activation, and customer acceptance dates of the order action. If the service activation date is set as a required field in Default Subscription Settings, skipping this field in a `CreateSubscription` order action of your JSON request will result in a `Pending` order and a `Pending Activation` subscription. If the customer acceptance date is set as a required field in Default Subscription Settings, skipping this field in a `CreateSubscription` order action of your JSON request will result in a `Pending` order and a `Pending Acceptance` subscription. If the service activation date field is at the same time required and skipped (or set as null), it will be a `Pending Activation` subscription. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Type of order action. Unless the type of order action is `RenewSubscription`, you must use the corresponding field to provide information about the order action. For example, if the type of order action is `AddProduct`, you must set the `addProduct` field. Zuora returns an error if you set a field that corresponds to a different type of order action. For example, if the type of order action is `AddProduct`, Zuora returns an error if you set the `updateProduct` field. |
**updateProduct** | [**PreviewOrderRatePlanUpdate**](PreviewOrderRatePlanUpdate.md) | | [optional]
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
CREATESUBSCRIPTION | "CreateSubscription"
TERMSANDCONDITIONS | "TermsAndConditions"
ADDPRODUCT | "AddProduct"
UPDATEPRODUCT | "UpdateProduct"
REMOVEPRODUCT | "RemoveProduct"
RENEWSUBSCRIPTION | "RenewSubscription"
CANCELSUBSCRIPTION | "CancelSubscription"
OWNERTRANSFER | "OwnerTransfer"
<file_sep>
# ProxyCreateAccount
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**classNS** | **String** | Value of the Class field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**customerTypeNS** | [**CustomerTypeNSEnum**](#CustomerTypeNSEnum) | Value of the Customer Type field for the corresponding customer account in NetSuite. The Customer Type field is used when the customer account is created in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Value of the Department field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the account's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Value of the Location field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Value of the Subsidiary field for the corresponding customer account in NetSuite. The Subsidiary field is required if you use NetSuite OneWorld. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the account was sychronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | [**SynctoNetSuiteNSEnum**](#SynctoNetSuiteNSEnum) | Specifies whether the account should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountNumber** | **String** | Unique account number assigned to the account. **Character limit**: 50 **Values**: one of the following: - null to auto-generate - a string of 50 characters or fewer that doesn't begin with the default account number prefix | [optional]
**additionalEmailAddresses** | **String** | List of additional email addresses to receive emailed invoices. **Character limit**: 120 **Values**: comma-separated list of email addresses | [optional]
**allowInvoiceEdit** | **Boolean** | Indicates if associated invoices can be edited. **Character limit**: 5 **Values**: `true`, `false` (default if left null) | [optional]
**autoPay** | **Boolean** | Indicates if future payments are automatically collected when they're due during a Payment Run. **Character limit**: 5 **Values**: `true`, `false` (default) | [optional]
**batch** | **String** | Organizes your customer accounts into groups to optimize your billing and payment operations. Required if use the Subscribe call. **Character limit**: 20 **Values**:any system-defined batch (`Batch1` - `Batch50 `or by name). | [optional]
**bcdSettingOption** | **String** | Billing cycle day setting option. **Character limit**: 9 **Values**: `AutoSet`, `ManualSet` | [optional]
**billCycleDay** | **Integer** | Billing cycle day (BCD) on which bill runs generate invoices for the account. **Character limit**: 2 **Values**: any activated system-defined bill cycle day (`1` - `31`) |
**billToId** | **String** | ID of the person to bill for the account. This field is only required if the `Status` field is set to `Active`. **Character limit**: 32 **Values**: a valid contact ID for the account | [optional]
**communicationProfileId** | **String** | Associates the account with a specified communication profile. **Character limit**: 32 **Values**: a valid communication profile ID | [optional]
**crmId** | **String** | CRM account ID for the account. A CRM is a customer relationship management system, such as Salesforce.com. **Character limit**: 100 **Values**: a string of 100 characters or fewer | [optional]
**currency** | **String** | Currency that the customer is billed in. |
**customerServiceRepName** | **String** | Name of the account's customer service representative, if applicable. **Character limit**: 50 **Values**: a string of 50 characters or fewer | [optional]
**defaultPaymentMethodId** | **String** | ID of the default payment method for the account. This field is only required if the `AutoPay` field is set to `true`. **Character limit**: 32 **Values**: a valid ID for an existing payment method | [optional]
**invoiceDeliveryPrefsEmail** | **Boolean** | Indicates if the customer wants to receive invoices through email. **Character limit**: 5 **Values**: `true`, `false` (default if left null) | [optional]
**invoiceDeliveryPrefsPrint** | **Boolean** | Indicates if the customer wants to receive printed invoices, such as through postal mail. **Character limit**: 5 **Values**: `true`, `false` (default if left null) | [optional]
**invoiceTemplateId** | **String** | The ID of the invoice template. Each customer account can use a specific invoice template for invoice generation. **Character limit**: 32 **Values**: a valid template ID configured in Zuora Billing Settings | [optional]
**name** | **String** | Name of the account as displayed in the Zuora UI. **Character limit**: 255 **Values**: a string of 255 characters or fewer |
**notes** | **String** | Comments about the account. **Character limit**: 65,535 **Values**: a string of 65,535 characters | [optional]
**parentId** | **String** | Identifier of the parent customer account for this Account object. Use this field if you have customer hierarchy enabled. **Character limit**: 32 **Values**: a valid account ID | [optional]
**paymentGateway** | **String** | Gateway used for processing electronic payments and refunds. This field is only required if there is no default payment gateway is defined in the tenant. **Character limit**: 40 **Values**: one of the following: - a valid configured gateway name - Null to inherit the default value set in Zuora Payment Settings | [optional]
**paymentTerm** | **String** | Indicates when the customer pays for subscriptions. **Character limit**: 100 **Values**: a valid, active payment term defined in the web-based UI administrative settings | [optional]
**purchaseOrderNumber** | **String** | The number of the purchase order associated with this account. Purchase order information generally comes from customers. **Character limit**: 100 **Values**: a string of 100 characters or fewer | [optional]
**salesRepName** | **String** | The name of the sales representative associated with this account, if applicable. **Character limit**: 50 **Values**: a string of 50 characters or fewer | [optional]
**soldToId** | **String** | ID of the person who bought the subscription associated with the account. This field is only required if the `Status` field is set to `Active`. **Character limit**: 32 **Values**: a valid contact ID for the account | [optional]
**status** | **String** | Status of the account in the system. **Character limit**: 8 **Values**: one of the following: - leave null if you're using The Subscribe call - if you're using Create: - `Draft` - `Active` - `Canceled` |
**taxCompanyCode** | **String** | Unique code that identifies a company account in Avalara. Use this field to calculate taxes based on origin and sold-to addresses in Avalara. This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). **Character limit**: 50 **Values**: a valid company code | [optional]
**taxExemptCertificateID** | **String** | ID of your customer's tax exemption certificate. **Character limit**: 32 **Values**: a string of 32 characters or fewer | [optional]
**taxExemptCertificateType** | **String** | Type of the tax exemption certificate that your customer holds. **Character limit**: 32 **Values**: a string of 32 characters or fewer | [optional]
**taxExemptDescription** | **String** | Description of the tax exemption certificate that your customer holds. **Character limit**: 500 **Values**: a string of 500 characters or fewer | [optional]
**taxExemptEffectiveDate** | [**LocalDate**](LocalDate.md) | Date when the the customer's tax exemption starts. **Character limit**: 29 **Version notes**: requires Zuora Tax | [optional]
**taxExemptExpirationDate** | [**LocalDate**](LocalDate.md) | Date when the customer's tax exemption certificate expires **Character limit**: 29 **Version notes**: requires Zuora Tax | [optional]
**taxExemptIssuingJurisdiction** | **String** | Indicates the jurisdiction in which the customer's tax exemption certificate was issued. **Character limit**: 32 **Values**: a string of 32 characters or fewer | [optional]
**taxExemptStatus** | **String** | Status of the account's tax exemption. This field is only required if you use Zuora Tax. This field is not available if you do not use Zuora Tax. **Character limit**: 19 **Values**: one of the following: - `Yes` - `No` - `PendingVerification` | [optional]
**vaTId** | **String** | EU Value Added Tax ID. This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). **Character limit**: 25 **Values**: a valid Value Added Tax ID | [optional]
<a name="CustomerTypeNSEnum"></a>
## Enum: CustomerTypeNSEnum
Name | Value
---- | -----
COMPANY | "Company"
INDIVIDUAL | "Individual"
<a name="SynctoNetSuiteNSEnum"></a>
## Enum: SynctoNetSuiteNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<file_sep># HmacSignaturesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**pOSTHMACSignatures**](HmacSignaturesApi.md#pOSTHMACSignatures) | **POST** /v1/hmac-signatures | Return HMAC signatures
<a name="pOSTHMACSignatures"></a>
# **pOSTHMACSignatures**
> POSTHMACSignatureResponseType pOSTHMACSignatures(request, zuoraEntityIds)
Return HMAC signatures
This REST API reference describes how to return unique signature and token values that used to process a CORS enabled API call.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.HmacSignaturesApi;
HmacSignaturesApi apiInstance = new HmacSignaturesApi();
POSTHMACSignatureType request = new POSTHMACSignatureType(); // POSTHMACSignatureType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTHMACSignatureResponseType result = apiInstance.pOSTHMACSignatures(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling HmacSignaturesApi#pOSTHMACSignatures");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTHMACSignatureType**](POSTHMACSignatureType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTHMACSignatureResponseType**](POSTHMACSignatureResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# TriggerParams
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**specificTriggerDate** | [**LocalDate**](LocalDate.md) | Date in YYYY-MM-DD format. Only applicable if the value of the `triggerEvent` field is `SpecificDate`. While this field is applicable, if this field is skipped or its value is left as null, your `CreateSubscription` order action will create a `Pending` order and a `Pending Acceptance` subscription. If at the same time the service activation date is set as required and its value is null, a `Pending Activation` subscription will be created. | [optional]
**triggerEvent** | [**TriggerEventEnum**](#TriggerEventEnum) | Condition for the charge to become active. If the value of this field is `SpecificDate`, use the `specificTriggerDate` field to specify the date when the charge becomes active. | [optional]
<a name="TriggerEventEnum"></a>
## Enum: TriggerEventEnum
Name | Value
---- | -----
CONTRACTEFFECTIVE | "ContractEffective"
SERVICEACTIVATION | "ServiceActivation"
CUSTOMERACCEPTANCE | "CustomerAcceptance"
SPECIFICDATE | "SpecificDate"
<file_sep>
# PreviewContactInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**city** | **String** | | [optional]
**country** | **String** | Country; must be a valid country name or abbreviation. If using Zuora Tax, you must specify a country to calculate tax. | [optional]
**county** | **String** | | [optional]
**postalCode** | **String** | | [optional]
**state** | **String** | | [optional]
**taxRegion** | **String** | | [optional]
<file_sep>
# SubscribeResultInvoiceResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoice** | [**List<SubscribeResultInvoiceResultInvoice>**](SubscribeResultInvoiceResultInvoice.md) | | [optional]
<file_sep>
# PUTBasicSummaryJournalEntryType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**journalEntryItems** | [**List<PUTJournalEntryItemType>**](PUTJournalEntryItemType.md) | Key name that represents the list of journal entry items. | [optional]
**notes** | **String** | Additional information about this record. ***Character limit:*** 2,000 | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Status shows whether the journal entry has been transferred to an accounting system. This field cannot be changed after the summary journal entry has been canceled. **Note:** The Zuora Finance ***Override Transferred to Accounting*** permission is required to change `transferredToAccounting` from `Yes` to any other value. | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
NO | "No"
PROCESSING | "Processing"
YES | "Yes"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# GetCreditMemoAmountBreakdownByOrderResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**breakdowns** | [**List<CreditMemoItemBreakdown>**](CreditMemoItemBreakdown.md) | Invoice breakdown details. | [optional]
**currency** | **String** | Currency code. | [optional]
<file_sep># SubscriptionsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETSubscriptionsByAccount**](SubscriptionsApi.md#gETSubscriptionsByAccount) | **GET** /v1/subscriptions/accounts/{account-key} | Get subscriptions by account
[**gETSubscriptionsByKey**](SubscriptionsApi.md#gETSubscriptionsByKey) | **GET** /v1/subscriptions/{subscription-key} | Get subscriptions by key
[**gETSubscriptionsByKeyAndVersion**](SubscriptionsApi.md#gETSubscriptionsByKeyAndVersion) | **GET** /v1/subscriptions/{subscription-key}/versions/{version} | Get subscriptions by key and version
[**objectDELETESubscription**](SubscriptionsApi.md#objectDELETESubscription) | **DELETE** /v1/object/subscription/{id} | CRUD: Delete Subscription
[**objectGETSubscription**](SubscriptionsApi.md#objectGETSubscription) | **GET** /v1/object/subscription/{id} | CRUD: Retrieve Subscription
[**objectPUTSubscription**](SubscriptionsApi.md#objectPUTSubscription) | **PUT** /v1/object/subscription/{id} | CRUD: Update Subscription
[**pOSTPreviewSubscription**](SubscriptionsApi.md#pOSTPreviewSubscription) | **POST** /v1/subscriptions/preview | Preview subscription
[**pOSTSubscription**](SubscriptionsApi.md#pOSTSubscription) | **POST** /v1/subscriptions | Create subscription
[**pUTCancelSubscription**](SubscriptionsApi.md#pUTCancelSubscription) | **PUT** /v1/subscriptions/{subscription-key}/cancel | Cancel subscription
[**pUTRenewSubscription**](SubscriptionsApi.md#pUTRenewSubscription) | **PUT** /v1/subscriptions/{subscription-key}/renew | Renew subscription
[**pUTResumeSubscription**](SubscriptionsApi.md#pUTResumeSubscription) | **PUT** /v1/subscriptions/{subscription-key}/resume | Resume subscription
[**pUTSubscription**](SubscriptionsApi.md#pUTSubscription) | **PUT** /v1/subscriptions/{subscription-key} | Update subscription
[**pUTSuspendSubscription**](SubscriptionsApi.md#pUTSuspendSubscription) | **PUT** /v1/subscriptions/{subscription-key}/suspend | Suspend subscription
<a name="gETSubscriptionsByAccount"></a>
# **gETSubscriptionsByAccount**
> GETSubscriptionWrapper gETSubscriptionsByAccount(accountKey, zuoraEntityIds, pageSize, chargeDetail)
Get subscriptions by account
Retrieves all subscriptions associated with the specified account. Zuora only returns the latest version of the subscriptions. Subscription data is returned in reverse chronological order based on `updatedDate`.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String accountKey = "accountKey_example"; // String | Possible values are: * an account number * an account ID
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String chargeDetail = "chargeDetail_example"; // String | The segmented rate plan charges. When an amendment results in a change to a charge, Zuora creates a segmented rate plan charge. Use this field to track segment charges. Possible values are: * __last-segment__: (Default) The last rate plan charge on the subscription. The last rate plan charge is the last one in the order of time on the subscription rather than the most recent changed charge on the subscription. * __current-segment__: The segmented charge that is active on today’s date (effectiveStartDate <= today’s date < effectiveEndDate). * __all-segments__: All the segmented charges. The `chargeSegments` field is returned in the response. The `chargeSegments` field contains an array of the charge information for all the charge segments. * __specific-segment&as-of-date=date__: The segmented charge that is active on a date you specified (effectiveStartDate <= specific date < effectiveEndDate). The format of the date is yyyy-mm-dd.
try {
GETSubscriptionWrapper result = apiInstance.gETSubscriptionsByAccount(accountKey, zuoraEntityIds, pageSize, chargeDetail);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#gETSubscriptionsByAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Possible values are: * an account number * an account ID |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**chargeDetail** | **String**| The segmented rate plan charges. When an amendment results in a change to a charge, Zuora creates a segmented rate plan charge. Use this field to track segment charges. Possible values are: * __last-segment__: (Default) The last rate plan charge on the subscription. The last rate plan charge is the last one in the order of time on the subscription rather than the most recent changed charge on the subscription. * __current-segment__: The segmented charge that is active on today’s date (effectiveStartDate <= today’s date < effectiveEndDate). * __all-segments__: All the segmented charges. The `chargeSegments` field is returned in the response. The `chargeSegments` field contains an array of the charge information for all the charge segments. * __specific-segment&as-of-date=date__: The segmented charge that is active on a date you specified (effectiveStartDate <= specific date < effectiveEndDate). The format of the date is yyyy-mm-dd. | [optional]
### Return type
[**GETSubscriptionWrapper**](GETSubscriptionWrapper.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETSubscriptionsByKey"></a>
# **gETSubscriptionsByKey**
> GETSubscriptionTypeWithSuccess gETSubscriptionsByKey(subscriptionKey, zuoraEntityIds, chargeDetail)
Get subscriptions by key
This REST API reference describes how to retrieve detailed information about a specified subscription in the latest version.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String subscriptionKey = "subscriptionKey_example"; // String | Possible values are: * a subscription number * a subscription ID
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String chargeDetail = "chargeDetail_example"; // String | The segmented rate plan charges. When an amendment results in a change to a charge, Zuora creates a segmented rate plan charge. Use this field to track segment charges. Possible values are: * __last-segment__: (Default) The last rate plan charge on the subscription. The last rate plan charge is the last one in the order of time on the subscription rather than the most recent changed charge on the subscription. * __current-segment__: The segmented charge that is active on today’s date (effectiveStartDate <= today’s date < effectiveEndDate). * __all-segments__: All the segmented charges. The `chargeSegments` field is returned in the response. The `chargeSegments` field contains an array of the charge information for all the charge segments. * __specific-segment&as-of-date=date__: The segmented charge that is active on a date you specified (effectiveStartDate <= specific date < effectiveEndDate). The format of the date is yyyy-mm-dd.
try {
GETSubscriptionTypeWithSuccess result = apiInstance.gETSubscriptionsByKey(subscriptionKey, zuoraEntityIds, chargeDetail);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#gETSubscriptionsByKey");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionKey** | **String**| Possible values are: * a subscription number * a subscription ID |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**chargeDetail** | **String**| The segmented rate plan charges. When an amendment results in a change to a charge, Zuora creates a segmented rate plan charge. Use this field to track segment charges. Possible values are: * __last-segment__: (Default) The last rate plan charge on the subscription. The last rate plan charge is the last one in the order of time on the subscription rather than the most recent changed charge on the subscription. * __current-segment__: The segmented charge that is active on today’s date (effectiveStartDate <= today’s date < effectiveEndDate). * __all-segments__: All the segmented charges. The `chargeSegments` field is returned in the response. The `chargeSegments` field contains an array of the charge information for all the charge segments. * __specific-segment&as-of-date=date__: The segmented charge that is active on a date you specified (effectiveStartDate <= specific date < effectiveEndDate). The format of the date is yyyy-mm-dd. | [optional]
### Return type
[**GETSubscriptionTypeWithSuccess**](GETSubscriptionTypeWithSuccess.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETSubscriptionsByKeyAndVersion"></a>
# **gETSubscriptionsByKeyAndVersion**
> GETSubscriptionTypeWithSuccess gETSubscriptionsByKeyAndVersion(subscriptionKey, version, zuoraEntityIds, chargeDetail)
Get subscriptions by key and version
This REST API reference describes how to retrieve detailed information about a specified subscription in a specified version. When you create a subscription amendment, you create a new version of the subscription. You can use this method to retrieve information about a subscription in any version.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String subscriptionKey = "subscriptionKey_example"; // String | Subscription number. For example, A-S00000135.
String version = "version_example"; // String | Subscription version. For example, 1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String chargeDetail = "chargeDetail_example"; // String | The segmented rate plan charges. When an amendment results in a change to a charge, Zuora creates a segmented rate plan charge. Use this field to track segment charges. Possible values are: * __last-segment__: (Default) The last rate plan charge on the subscription. The last rate plan charge is the last one in the order of time on the subscription rather than the most recent changed charge on the subscription. * __current-segment__: The segmented charge that is active on today’s date (effectiveStartDate <= today’s date < effectiveEndDate). * __all-segments__: All the segmented charges. The `chargeSegments` field is returned in the response. The `chargeSegments` field contains an array of the charge information for all the charge segments. * __specific-segment&as-of-date=date__: The segmented charge that is active on a date you specified (effectiveStartDate <= specific date < effectiveEndDate). The format of the date is yyyy-mm-dd.
try {
GETSubscriptionTypeWithSuccess result = apiInstance.gETSubscriptionsByKeyAndVersion(subscriptionKey, version, zuoraEntityIds, chargeDetail);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#gETSubscriptionsByKeyAndVersion");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionKey** | **String**| Subscription number. For example, A-S00000135. |
**version** | **String**| Subscription version. For example, 1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**chargeDetail** | **String**| The segmented rate plan charges. When an amendment results in a change to a charge, Zuora creates a segmented rate plan charge. Use this field to track segment charges. Possible values are: * __last-segment__: (Default) The last rate plan charge on the subscription. The last rate plan charge is the last one in the order of time on the subscription rather than the most recent changed charge on the subscription. * __current-segment__: The segmented charge that is active on today’s date (effectiveStartDate <= today’s date < effectiveEndDate). * __all-segments__: All the segmented charges. The `chargeSegments` field is returned in the response. The `chargeSegments` field contains an array of the charge information for all the charge segments. * __specific-segment&as-of-date=date__: The segmented charge that is active on a date you specified (effectiveStartDate <= specific date < effectiveEndDate). The format of the date is yyyy-mm-dd. | [optional]
### Return type
[**GETSubscriptionTypeWithSuccess**](GETSubscriptionTypeWithSuccess.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETESubscription"></a>
# **objectDELETESubscription**
> ProxyDeleteResponse objectDELETESubscription(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Subscription
**Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETESubscription(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#objectDELETESubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETSubscription"></a>
# **objectGETSubscription**
> ProxyGetSubscription objectGETSubscription(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Subscription
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetSubscription result = apiInstance.objectGETSubscription(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#objectGETSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetSubscription**](ProxyGetSubscription.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTSubscription"></a>
# **objectPUTSubscription**
> ProxyCreateOrModifyResponse objectPUTSubscription(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update Subscription
**Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String id = "id_example"; // String | Object id
ProxyModifySubscription modifyRequest = new ProxyModifySubscription(); // ProxyModifySubscription |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTSubscription(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#objectPUTSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifySubscription**](ProxyModifySubscription.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTPreviewSubscription"></a>
# **pOSTPreviewSubscription**
> POSTSubscriptionPreviewResponseType pOSTPreviewSubscription(request, zuoraEntityIds, zuoraVersion)
Preview subscription
The REST API reference describes how to create a new subscription in preview mode. This call does not require a valid customer account. It can be used to show potential new customers a preview of a subscription with complete details and charges before creating an account, or to let existing customers preview a subscription with all charges before committing. ## Notes - This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. - The response of the Preview Subscription call is based on the REST API minor version you set in the request header. The response structure might be different if you use different minor version numbers. - If you have the Invoice Settlement feature enabled, we recommend that you set the `zuora-version` parameter to `207.0` or later. Otherwise, an error is returned. - Default values for **customerAcceptanceDate** and **serviceActivationDate** are set as follows. | | serviceActivationDate (SA) specified | serviceActivationDate (SA) NOT specified | | ------------- |:-------------:| -----:| | customerAcceptanceDate (CA) specified | SA uses value in the request call; CA uses value in the request call| CA uses value in the request call;SA uses CE as default | | customerAcceptanceDate (CA) NOT specified | SA uses value in the request call; CA uses SA as default | SA and CA use CE as default |
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
POSTSubscriptionPreviewType request = new POSTSubscriptionPreviewType(); // POSTSubscriptionPreviewType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * targetDate * includeExistingDraftDocItems * previewType If you have the Invoice Settlement feature enabled, you need to specify this parameter. Otherwise, an error is returned. See [Zuora REST API Versions](https://www.zuora.com/developer/api-reference/#section/API-Versions) for more information.
try {
POSTSubscriptionPreviewResponseType result = apiInstance.pOSTPreviewSubscription(request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#pOSTPreviewSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTSubscriptionPreviewType**](POSTSubscriptionPreviewType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * targetDate * includeExistingDraftDocItems * previewType If you have the Invoice Settlement feature enabled, you need to specify this parameter. Otherwise, an error is returned. See [Zuora REST API Versions](https://www.zuora.com/developer/api-reference/#section/API-Versions) for more information. | [optional]
### Return type
[**POSTSubscriptionPreviewResponseType**](POSTSubscriptionPreviewResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTSubscription"></a>
# **pOSTSubscription**
> POSTSubscriptionResponseType pOSTSubscription(request, zuoraEntityIds, zuoraVersion)
Create subscription
This REST API reference describes how to create a new subscription for an existing customer account. ## Notes This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. If invoiceCollect is `true`, the call will not return success = `true` unless the subscription, invoice, and payment are all successful. Default values for **customerAcceptanceDate** and **serviceActivationDate** are set as follows. | | serviceActivationDate(SA) specified | serviceActivationDate (SA) NOT specified | | ------------- |:-------------:| -----:| | customerAcceptanceDate (CA) specified| SA uses value in the request call; CA uses value in the request call| CA uses value in the request call;SA uses CE as default | | customerAcceptanceDate (CA) NOT specified | SA uses value in the request call; CA uses SA as default | SA and CA use CE as default |
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
POSTSubscriptionType request = new POSTSubscriptionType(); // POSTSubscriptionType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate
try {
POSTSubscriptionResponseType result = apiInstance.pOSTSubscription(request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#pOSTSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTSubscriptionType**](POSTSubscriptionType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate | [optional]
### Return type
[**POSTSubscriptionResponseType**](POSTSubscriptionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTCancelSubscription"></a>
# **pUTCancelSubscription**
> POSTSubscriptionCancellationResponseType pUTCancelSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion)
Cancel subscription
This REST API reference describes how to cancel an active subscription. **Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String subscriptionKey = "subscriptionKey_example"; // String | Subscription number or ID. Subscription status must be `Active`.
POSTSubscriptionCancellationType request = new POSTSubscriptionCancellationType(); // POSTSubscriptionCancellationType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate
try {
POSTSubscriptionCancellationResponseType result = apiInstance.pUTCancelSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#pUTCancelSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionKey** | **String**| Subscription number or ID. Subscription status must be `Active`. |
**request** | [**POSTSubscriptionCancellationType**](POSTSubscriptionCancellationType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate | [optional]
### Return type
[**POSTSubscriptionCancellationResponseType**](POSTSubscriptionCancellationResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTRenewSubscription"></a>
# **pUTRenewSubscription**
> PUTRenewSubscriptionResponseType pUTRenewSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion)
Renew subscription
Renews a termed subscription using existing renewal terms. **Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String subscriptionKey = "subscriptionKey_example"; // String | Subscription number or ID
PUTRenewSubscriptionType request = new PUTRenewSubscriptionType(); // PUTRenewSubscriptionType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate
try {
PUTRenewSubscriptionResponseType result = apiInstance.pUTRenewSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#pUTRenewSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionKey** | **String**| Subscription number or ID |
**request** | [**PUTRenewSubscriptionType**](PUTRenewSubscriptionType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate | [optional]
### Return type
[**PUTRenewSubscriptionResponseType**](PUTRenewSubscriptionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTResumeSubscription"></a>
# **pUTResumeSubscription**
> PUTSubscriptionResumeResponseType pUTResumeSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion)
Resume subscription
This REST API reference describes how to resume a suspended subscription. This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://suport.zuora.com). **Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. This feature is also unavailable if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String subscriptionKey = "subscriptionKey_example"; // String | Subscription number or ID. Subscription status must be Active.
PUTSubscriptionResumeType request = new PUTSubscriptionResumeType(); // PUTSubscriptionResumeType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate
try {
PUTSubscriptionResumeResponseType result = apiInstance.pUTResumeSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#pUTResumeSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionKey** | **String**| Subscription number or ID. Subscription status must be Active. |
**request** | [**PUTSubscriptionResumeType**](PUTSubscriptionResumeType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate | [optional]
### Return type
[**PUTSubscriptionResumeResponseType**](PUTSubscriptionResumeResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTSubscription"></a>
# **pUTSubscription**
> PUTSubscriptionResponseType pUTSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion)
Update subscription
Use this call to make the following kinds of changes to a subscription: * Add a note * Change the renewal term or auto-renewal flag * Change the term length or change between evergreen and termed * Add a new product rate plan * Remove an existing subscription rate plan * Change the quantity or price of an existing subscription rate plan ## Notes * This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. * The Update Subscription call creates a new subscription, which has the old subscription number but a new subscription ID. The old subscription is canceled but remains in the system. * In one request, this call can make: * Up to 9 combined add, update, and remove changes * No more than 1 change to terms & conditions * Updates are performed in the following sequence: 1. First change the notes on the existing subscription, if requested. 2. Then change the terms and conditions, if requested. 3. Then perform the remaining amendments based upon the effective dates specified. If multiple amendments have the same contract-effective dates, then execute adds before updates, and updates before removes. * The update operation is atomic. If any of the updates fails, the entire operation is rolled back. * The response of the Update Subscription call is based on the REST API minor version you set in the request header. The response structure might be different if you use different minor version numbers. * If you have the Invoice Settlement feature enabled, we recommend that you set the `zuora-version` parameter to `207.0` or later. Otherwise, an error is returned. ## Override a Tiered Price There are two ways you override a tiered price: * Override a specific tier number For example: `tiers[{tier:1,price:8},{tier:2,price:6}]` * Override the entire tier structure For example: `tiers[{tier:1,price:8,startingUnit:1,endingUnit:100,priceFormat:\"FlatFee\"}, {tier:2,price:6,startingUnit:101,priceFormat:\"FlatFee\"}]` If you just override a specific tier, do not include the `startingUnit` field in the request.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String subscriptionKey = "subscriptionKey_example"; // String | Subscription number or ID.
PUTSubscriptionType request = new PUTSubscriptionType(); // PUTSubscriptionType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * collect * invoice * includeExistingDraftDocItems * previewType * runBilling * targetDate If you have the Invoice Settlement feature enabled, you need to specify this parameter. Otherwise, an error is returned. See [Zuora REST API Versions](https://www.zuora.com/developer/api-reference/#section/API-Versions) for more information.
try {
PUTSubscriptionResponseType result = apiInstance.pUTSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#pUTSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionKey** | **String**| Subscription number or ID. |
**request** | [**PUTSubscriptionType**](PUTSubscriptionType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * collect * invoice * includeExistingDraftDocItems * previewType * runBilling * targetDate If you have the Invoice Settlement feature enabled, you need to specify this parameter. Otherwise, an error is returned. See [Zuora REST API Versions](https://www.zuora.com/developer/api-reference/#section/API-Versions) for more information. | [optional]
### Return type
[**PUTSubscriptionResponseType**](PUTSubscriptionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTSuspendSubscription"></a>
# **pUTSuspendSubscription**
> PUTSubscriptionSuspendResponseType pUTSuspendSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion)
Suspend subscription
This REST API reference describes how to suspend an active subscription. This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://suport.zuora.com). **Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. This feature is also unavailable if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SubscriptionsApi;
SubscriptionsApi apiInstance = new SubscriptionsApi();
String subscriptionKey = "subscriptionKey_example"; // String | Subscription number or ID. Subscription status must be Active.
PUTSubscriptionSuspendType request = new PUTSubscriptionSuspendType(); // PUTSubscriptionSuspendType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate
try {
PUTSubscriptionSuspendResponseType result = apiInstance.pUTSuspendSubscription(subscriptionKey, request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubscriptionsApi#pUTSuspendSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionKey** | **String**| Subscription number or ID. Subscription status must be Active. |
**request** | [**PUTSubscriptionSuspendType**](PUTSubscriptionSuspendType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate | [optional]
### Return type
[**PUTSubscriptionSuspendResponseType**](PUTSubscriptionSuspendResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# TermsAndConditions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**autoRenew** | **Boolean** | | [optional]
**lastTerm** | [**LastTerm**](LastTerm.md) | | [optional]
**renewalSetting** | [**RenewalSettingEnum**](#RenewalSettingEnum) | | [optional]
**renewalTerms** | [**List<RenewalTerm>**](RenewalTerm.md) | | [optional]
<a name="RenewalSettingEnum"></a>
## Enum: RenewalSettingEnum
Name | Value
---- | -----
WITH_SPECIFIC_TERM | "RENEW_WITH_SPECIFIC_TERM"
TO_EVERGREEN | "RENEW_TO_EVERGREEN"
<file_sep>
# GETAccountSummaryUsageType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**quantity** | **String** | Number of units used. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The start date of a usage period as `yyyy-mm`. Zuora uses this field value to determine the usage date. | [optional]
**unitOfMeasure** | **String** | Unit by which consumption is measured, as configured in the Billing Settings section of the web-based UI. | [optional]
<file_sep>
# ProxyGetProductFeature
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**createdById** | **String** | The ID of the Zuora user who created the Account object. **Character limit**: 32 **Values**: automatically generated | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the Account object was created. **Character limit**: 29 **Values**: automatically generated | [optional]
**featureId** | **String** | Internal Zuora ID of the product feature. This field is not editable. **Character limit**: 32 **Values**: a string of 32 characters or fewer | [optional]
**id** | **String** | Object identifier. | [optional]
**productId** | **String** | Id of the product to which the feature belongs. This field is not editable. **Character limit**: 32 **Values**: a string of 32 characters or fewer | [optional]
**updatedById** | **String** | The ID of the user who last updated the account. **Character limit**: 32 **Values**: automatically generated | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the account was last updated. **Character limit**: 29 **Values**: automatically generated | [optional]
<file_sep>
# PostGenerateBillingDocumentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**autoPost** | **Boolean** | Determines whether to auto post the billing documents once the draft billing documents are generated. If an error occurred during posting billing documents, the draft billing documents are not generated too. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date on which to generate the billing documents, in `yyyy-mm-dd` format. | [optional]
**subscriptionIds** | **List<String>** | The IDs of the subscriptions that you want to create the billing documents for. | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | The date used to determine which charges are to be billed, in `yyyy-mm-dd` format. | [optional]
<file_sep>
# PUTRefundType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the refund's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the refund was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | **String** | Specifies whether the refund should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**comment** | **String** | Comments about the refund. | [optional]
**financeInformation** | [**PUTRefundTypeFinanceInformation**](PUTRefundTypeFinanceInformation.md) | | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. | [optional]
<file_sep>rootProject.name = "zuora-api-client"<file_sep>
# OwnerTransfer
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**destinationAccountNumber** | **String** | The account number of the account that the subscription is being transferred to. | [optional]
**destinationInvoiceAccountNumber** | **String** | The account number of the invoice owner account that the subscription is being transferred to. | [optional]
<file_sep>
# GETDebitMemoTypewithSuccess
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the debit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the debit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The ID of the customer account associated with the debit memo. | [optional]
**amount** | **Double** | The total amount of the debit memo. | [optional]
**autoPay** | **Boolean** | Whether debit memos are automatically picked up for processing in the corresponding payment run. By default, debit memos are automatically picked up for processing in the corresponding payment run. | [optional]
**balance** | **Double** | The balance of the debit memo. | [optional]
**beAppliedAmount** | **Double** | The applied amount of the debit memo. | [optional]
**cancelledById** | **String** | The ID of the Zuora user who cancelled the debit memo. | [optional]
**cancelledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the debit memo was cancelled, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**comment** | **String** | Comments about the debit memo. | [optional]
**createdById** | **String** | The ID of the Zuora user who created the debit memo. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the debit memo was created, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 15:31:10. | [optional]
**debitMemoDate** | [**LocalDate**](LocalDate.md) | The date when the debit memo takes effect, in `yyyy-mm-dd` format. For example, 2017-05-20. | [optional]
**dueDate** | [**LocalDate**](LocalDate.md) | The date by which the payment for the debit memo is due, in `yyyy-mm-dd` format. | [optional]
**id** | **String** | The unique ID of the debit memo. | [optional]
**latestPDFFileId** | **String** | The ID of the latest PDF file generated for the debit memo. | [optional]
**number** | **String** | The unique identification number of the debit memo. | [optional]
**postedById** | **String** | The ID of the Zuora user who posted the debit memo. | [optional]
**postedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the debit memo was posted, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. | [optional]
**referredInvoiceId** | **String** | The ID of a referred invoice. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the debit memo. | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | The target date for the debit memo, in `yyyy-mm-dd` format. For example, 2017-07-20. | [optional]
**taxAmount** | **Double** | The amount of taxation. | [optional]
**totalTaxExemptAmount** | **Double** | The total amount of taxes or VAT for which the customer has an exemption. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the debit memo was transferred to an external accounting system. Use this field for integration with accounting systems, such as NetSuite. | [optional]
**updatedById** | **String** | The ID of the Zuora user who last updated the debit memo. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the debit memo was last updated, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-02 15:31:10. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
DRAFT | "Draft"
POSTED | "Posted"
CANCELED | "Canceled"
ERROR | "Error"
PENDINGFORTAX | "PendingForTax"
GENERATING | "Generating"
CANCELINPROGRESS | "CancelInProgress"
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
NO | "No"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# OrderItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**endDate** | [**LocalDate**](LocalDate.md) | The order item's effective end date, aligned with the end date of an increased quantity order metrics. | [optional]
**id** | **String** | The ID of the order item. | [optional]
**orderActionId** | **String** | Specify the order action that creates this order item. | [optional]
**quantity** | [**BigDecimal**](BigDecimal.md) | The order item quantity. For the usage charge type, the value of this field is always zero. Also, the Owner Transfer order action always creates an order item whose Quantity field is zero. | [optional]
**scId** | **String** | The ID of the charge segment that gets newly generated when the order item is created. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The order item's effective start date, aligned with the start date of an increased quantity order metrics. | [optional]
<file_sep>
# GETRefundCollectionType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nextPage** | **String** | URL to retrieve the next page of the response if it exists; otherwise absent. | [optional]
**refunds** | [**List<GETRefundTypewithSuccess>**](GETRefundTypewithSuccess.md) | Container for refunds. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<file_sep>
# SubscribeRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**account** | [**SubscribeRequestAccount**](SubscribeRequestAccount.md) | |
**billToContact** | [**SubscribeRequestBillToContact**](SubscribeRequestBillToContact.md) | | [optional]
**paymentMethod** | [**SubscribeRequestPaymentMethod**](SubscribeRequestPaymentMethod.md) | | [optional]
**previewOptions** | [**SubscribeRequestPreviewOptions**](SubscribeRequestPreviewOptions.md) | | [optional]
**soldToContact** | [**SubscribeRequestSoldToContact**](SubscribeRequestSoldToContact.md) | | [optional]
**subscribeOptions** | [**SubscribeRequestSubscribeOptions**](SubscribeRequestSubscribeOptions.md) | | [optional]
**subscriptionData** | [**SubscribeRequestSubscriptionData**](SubscribeRequestSubscriptionData.md) | |
<file_sep>
# PutEventTriggerRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**active** | **Boolean** | The status of the trigger. | [optional]
**condition** | **String** | The JEXL expression to be evaluated against object changes. See above for more information and an example. | [optional]
**description** | **String** | The description of the trigger. | [optional]
**eventType** | [**PutEventTriggerRequestEventType**](PutEventTriggerRequestEventType.md) | | [optional]
<file_sep># BillingDocumentsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETBillingDocuments**](BillingDocumentsApi.md#gETBillingDocuments) | **GET** /v1/billing-documents | Get billing documents
<a name="gETBillingDocuments"></a>
# **gETBillingDocuments**
> BillingDocumentQueryResponseElementType gETBillingDocuments(accountId, zuoraEntityIds, pageSize, documentDate, status, sort)
Get billing documents
Retrieves the information about all billing documents associated with a specified account. The billing documents contain invoices, credit memos, and debit memos. To retrieve information about credit memos and debit memos, you must have the Invoice Settlement feature enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillingDocumentsApi;
BillingDocumentsApi apiInstance = new BillingDocumentsApi();
UUID accountId = new UUID(); // UUID | The ID of the customer account that the billing documents are associated with.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
LocalDate documentDate = new LocalDate(); // LocalDate | The date of the billing document. It represents the invoice date for invoices, credit memo date for credit memos, and debit memo date for debit memos.
String status = "status_example"; // String | The status of the billing document.
String sort = "sort_example"; // String | This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. If you do not specify any sortable field, the response data is sorted by the `documentDate` field in descending order. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - documentDate - documentType Examples: - /billing-documents?accountId=4028905f5e4feb38015e50af9aa002d1 &sort=+documentDate,-documentType - /billing-documents?accountId=4028905f5e4feb38015e50af9aa002d1 &status=Posted&sort=+documentDate&page=2&pageSize=15
try {
BillingDocumentQueryResponseElementType result = apiInstance.gETBillingDocuments(accountId, zuoraEntityIds, pageSize, documentDate, status, sort);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillingDocumentsApi#gETBillingDocuments");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountId** | [**UUID**](.md)| The ID of the customer account that the billing documents are associated with. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**documentDate** | **LocalDate**| The date of the billing document. It represents the invoice date for invoices, credit memo date for credit memos, and debit memo date for debit memos. | [optional]
**status** | **String**| The status of the billing document. | [optional] [enum: Draft, Posted, Canceled, Error]
**sort** | **String**| This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. If you do not specify any sortable field, the response data is sorted by the `documentDate` field in descending order. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - documentDate - documentType Examples: - /billing-documents?accountId=4028905f5e4feb38015e50af9aa002d1 &sort=+documentDate,-documentType - /billing-documents?accountId=4028905f5e4feb38015e50af9aa002d1 &status=Posted&sort=+documentDate&page=2&pageSize=15 | [optional]
### Return type
[**BillingDocumentQueryResponseElementType**](BillingDocumentQueryResponseElementType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# CreditMemoApplyInvoiceRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The credit memo amount to be applied to the invoice. |
**invoiceId** | **String** | The unique ID of the invoice that the credit memo is applied to. |
**items** | [**List<CreditMemoApplyInvoiceItemRequestType>**](CreditMemoApplyInvoiceItemRequestType.md) | Container for items. | [optional]
<file_sep>
# SubscribeRequestPreviewOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**enablePreviewMode** | **Boolean** | Specifies whether to create a subscription or preview the invoices that would be generated. | [optional]
**numberOfPeriods** | **Integer** | The number of invoice periods to show in a preview. | [optional]
**previewThroughTermEnd** | **Boolean** | Specifies whether to preview the charge through the end of the subscription term. Applicable to termed subscriptions only. | [optional]
**previewType** | [**PreviewTypeEnum**](#PreviewTypeEnum) | The type of preview to return: * `InvoiceItem` - Return an invoice item preview * `ChargeMetrics` - Return a charge metrics preview * `InvoiceItemChargeMetrics` - Return an invoice item and charge metrics of that item | [optional]
<a name="PreviewTypeEnum"></a>
## Enum: PreviewTypeEnum
Name | Value
---- | -----
INVOICEITEM | "InvoiceItem"
CHARGEMETRICS | "ChargeMetrics"
INVOICEITEMCHARGEMETRICS | "InvoiceItemChargeMetrics"
<file_sep>
# ApplyPaymentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**debitMemos** | [**List<PaymentDebitMemoApplicationApplyRequestType>**](PaymentDebitMemoApplicationApplyRequestType.md) | Container for debit memos. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the payment application takes effect, in `yyyy-mm-dd` format. | [optional]
**invoices** | [**List<PaymentInvoiceApplicationApplyRequestType>**](PaymentInvoiceApplicationApplyRequestType.md) | Container for invoices. | [optional]
<file_sep>
# CreditMemoFromInvoiceType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the credit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the credit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**autoApplyToInvoiceUponPosting** | **Boolean** | Whether the credit memo automatically applies to the invoice upon posting. | [optional]
**comment** | **String** | Comments about the credit memo. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the credit memo takes effect. | [optional]
**excludeFromAutoApplyRules** | **Boolean** | Whether the credit memo is excluded from the rule of automatically applying credit memos to invoices. | [optional]
**invoiceId** | **String** | The ID of the invoice that the credit memo is created from. | [optional]
**items** | [**List<CreditMemoItemFromInvoiceItemType>**](CreditMemoItemFromInvoiceItemType.md) | Container for items. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. | [optional]
**taxAutoCalculation** | **Boolean** | Whether to automatically calculate taxes in the credit memo. | [optional]
<file_sep>
# POSTDelayAuthorizeCapture
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | **String** | The ID of the customer account. |
**accountNumber** | **String** | The number of the customer account. |
**amount** | [**BigDecimal**](BigDecimal.md) | The amount of the trasaction. |
**gatewayOrderId** | **String** | The order ID for the specific gateway. |
**softDescriptor** | **String** | A text, rendered on a cardholder’s statement, describing a particular product or service purchased by the cardholder. | [optional]
**softDescriptorPhone** | **String** | The phone number that relates to the soft descriptor, usually the phone number of customer service. | [optional]
<file_sep>
# GETPaidInvoicesType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**appliedPaymentAmount** | **String** | Amount of the payment applied to this invoice. | [optional]
**invoiceId** | **String** | Invoice ID. | [optional]
**invoiceNumber** | **String** | Invoice number. | [optional]
<file_sep>
# CreateOrderRatePlanUpdate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeUpdates** | [**List<CreateOrderChargeUpdate>**](CreateOrderChargeUpdate.md) | | [optional]
**customFields** | [**RatePlanObjectCustomFields**](RatePlanObjectCustomFields.md) | | [optional]
**ratePlanId** | **String** | The id of the rate plan to be updated. It can be the latest version or any history version id. | [optional]
**specificUpdateDate** | [**LocalDate**](LocalDate.md) | Used for the 'update before update' and 'update before remove' cases. | [optional]
**uniqueToken** | **String** | A unique string to represent the rate plan charge in the order. The unique token is used to perform multiple actions against a newly added rate plan. For example, if you want to add and update a product in the same order, you would assign a unique token to the product rate plan when added and use that token in future order actions. | [optional]
<file_sep>
# ProductRatePlanObjectNSFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**billingPeriodNS** | [**BillingPeriodNSEnum**](#BillingPeriodNSEnum) | Billing period associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**classNS** | **String** | Class associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Department associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**includeChildrenNS** | [**IncludeChildrenNSEnum**](#IncludeChildrenNSEnum) | Specifies whether the corresponding item in NetSuite is visible under child subsidiaries. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the product rate plan's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**itemTypeNS** | [**ItemTypeNSEnum**](#ItemTypeNSEnum) | Type of item that is created in NetSuite for the product rate plan. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Location associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**multiCurrencyPriceNS** | **String** | Multi-currency price associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**priceNS** | **String** | Price associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Subsidiary associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the product rate plan was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
<a name="BillingPeriodNSEnum"></a>
## Enum: BillingPeriodNSEnum
Name | Value
---- | -----
MONTHLY | "Monthly"
QUARTERLY | "Quarterly"
ANNUAL | "Annual"
SEMI_ANNUAL | "Semi-Annual"
<a name="IncludeChildrenNSEnum"></a>
## Enum: IncludeChildrenNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<a name="ItemTypeNSEnum"></a>
## Enum: ItemTypeNSEnum
Name | Value
---- | -----
INVENTORY | "Inventory"
NON_INVENTORY | "Non Inventory"
SERVICE | "Service"
<file_sep>
# PutEventTriggerRequestEventType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**description** | **String** | The description for the event type. | [optional]
**displayName** | **String** | The display name for the event type. | [optional]
<file_sep>
# TaxInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**vaTId** | **String** | EU Value Added Tax ID. **Note:** This feature is in Limited Availability. If you wish to have access to the feature, submit a request at [Zuora Global Support](https://support.zuora.com). | [optional]
**companyCode** | **String** | Unique code that identifies a company account in Avalara. Use this field to calculate taxes based on origin and sold-to addresses in Avalara. **Note:** This feature is in Limited Availability. If you wish to have access to the feature, submit a request at [Zuora Global Support](https://support.zuora.com). | [optional]
**exemptCertificateId** | **String** | ID of the customer tax exemption certificate. Only applicable if you use Zuora Tax. | [optional]
**exemptCertificateType** | **String** | Type of tax exemption certificate that the customer holds. Only applicable if you use Zuora Tax. | [optional]
**exemptDescription** | **String** | Description of the tax exemption certificate that the customer holds. Only applicable if you use Zuora Tax. | [optional]
**exemptEffectiveDate** | [**LocalDate**](LocalDate.md) | Date when the customer tax exemption starts, in YYYY-MM-DD format. Only applicable if you use Zuora Tax. | [optional]
**exemptExpirationDate** | [**LocalDate**](LocalDate.md) | Date when the customer tax exemption expires, in YYYY-MM-DD format. Only applicable if you use Zuora Tax. | [optional]
**exemptIssuingJurisdiction** | **String** | Jurisdiction in which the customer tax exemption certificate was issued. | [optional]
**exemptStatus** | [**ExemptStatusEnum**](#ExemptStatusEnum) | Status of the account tax exemption. Required if you use Zuora Tax. Only applicable if you use Zuora Tax. | [optional]
<a name="ExemptStatusEnum"></a>
## Enum: ExemptStatusEnum
Name | Value
---- | -----
NO | "No"
YES | "Yes"
PENDINGVERIFICATION | "PendingVerification"
<file_sep>
# CreditMemoFromChargeType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the credit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the credit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The ID of the account associated with the credit memo. |
**charges** | [**List<CreditMemoFromChargeDetailType>**](CreditMemoFromChargeDetailType.md) | Container for product rate plan charges. | [optional]
**comment** | **String** | Comments about the credit memo. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the credit memo takes effect. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. | [optional]
<file_sep>
# POSTSrpCreateType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeOverrides** | [**List<POSTScCreateType>**](POSTScCreateType.md) | This optional container is used to override the quantity of one or more product rate plan charges for this subscription. | [optional]
**productRatePlanId** | **String** | ID of a product rate plan for this subscription. |
<file_sep>
# GETAccountingPeriodType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**createdBy** | **String** | ID of the user who created the accounting period. | [optional]
**createdOn** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time when the accounting period was created. | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | The end date of the accounting period. | [optional]
**fileIds** | [**GETAccountingPeriodTypeFileIds**](GETAccountingPeriodTypeFileIds.md) | | [optional]
**fiscalYear** | **String** | Fiscal year of the accounting period. | [optional]
**fiscalQuarter** | **Long** | | [optional]
**id** | **String** | ID of the accounting period. | [optional]
**name** | **String** | Name of the accounting period. | [optional]
**notes** | **String** | Any optional notes about the accounting period. | [optional]
**runTrialBalanceEnd** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time that the trial balance was completed. If the trial balance status is `Pending`, `Processing`, or `Error`, this field is `null`. | [optional]
**runTrialBalanceErrorMessage** | **String** | If trial balance status is Error, an error message is returned in this field. | [optional]
**runTrialBalanceStart** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time that the trial balance was run. If the trial balance status is Pending, this field is null. | [optional]
**runTrialBalanceStatus** | **String** | Status of the trial balance for the accounting period. Possible values: * `Pending` * `Processing` * `Completed` * `Error` | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The start date of the accounting period. | [optional]
**status** | **String** | Status of the accounting period. Possible values: * `Open` * `PendingClose` * `Closed` | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**updatedBy** | **String** | ID of the user who last updated the accounting period. | [optional]
**updatedOn** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time when the accounting period was last updated. | [optional]
<file_sep># DocumentPropertiesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEDocumentProperties**](DocumentPropertiesApi.md#dELETEDocumentProperties) | **DELETE** /v1/document-properties/{documentPropertiesId} | Delete document properties
[**gETDocumentProperies**](DocumentPropertiesApi.md#gETDocumentProperies) | **GET** /v1/document-properties/{documentType}/{documentId} | Get document properties
[**pOSTDocumentProperties**](DocumentPropertiesApi.md#pOSTDocumentProperties) | **POST** /v1/document-properties | Create document properties
[**pUTDocumentProperties**](DocumentPropertiesApi.md#pUTDocumentProperties) | **PUT** /v1/document-properties/{documentPropertiesId} | Update document properties
<a name="dELETEDocumentProperties"></a>
# **dELETEDocumentProperties**
> CommonResponseType dELETEDocumentProperties(documentPropertiesId, zuoraEntityIds, zuoraTrackId)
Delete document properties
**Note:** This feature is available only if you have the Billing Document Properties Setup feature enabled. The Billing Document Properties Setup feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Deletes document properties with a specific ID for a billing document. Billing documents include invoices, credit memos, and debit memos. **Note:** You can delete document properties for credit and debit memos only if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DocumentPropertiesApi;
DocumentPropertiesApi apiInstance = new DocumentPropertiesApi();
String documentPropertiesId = "documentPropertiesId_example"; // String | The unique ID of document properties. For example, 402892c74c9193cd014c96bbe7c101f9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
CommonResponseType result = apiInstance.dELETEDocumentProperties(documentPropertiesId, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DocumentPropertiesApi#dELETEDocumentProperties");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**documentPropertiesId** | **String**| The unique ID of document properties. For example, 402892c74c9193cd014c96bbe7c101f9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETDocumentProperies"></a>
# **gETDocumentProperies**
> GETDocumentPropertiesResponseType gETDocumentProperies(documentType, documentId, zuoraEntityIds, zuoraTrackId)
Get document properties
**Note:** This feature is available only if you have the Billing Document Properties Setup feature enabled. The Billing Document Properties Setup feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieve information about document properties of a billing document. Billing documents include invoices, credit memos, and debit memos. **Note:** You can retrieve information about document properties of credit and debit memos only if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DocumentPropertiesApi;
DocumentPropertiesApi apiInstance = new DocumentPropertiesApi();
String documentType = "documentType_example"; // String | The type of the billing document.
String documentId = "documentId_example"; // String | The unique ID of document properties to be retrieved. For example, <KEY>.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
GETDocumentPropertiesResponseType result = apiInstance.gETDocumentProperies(documentType, documentId, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DocumentPropertiesApi#gETDocumentProperies");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**documentType** | **String**| The type of the billing document. | [enum: Invoice, CreditMemo, DebitMemo]
**documentId** | **String**| The unique ID of document properties to be retrieved. For example, 40<KEY>. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**GETDocumentPropertiesResponseType**](GETDocumentPropertiesResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTDocumentProperties"></a>
# **pOSTDocumentProperties**
> GETDocumentPropertiesResponseType pOSTDocumentProperties(request, zuoraEntityIds, zuoraTrackId)
Create document properties
**Note:** This feature is available only if you have the Billing Document Properties Setup feature enabled. The Billing Document Properties Setup feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates custom document properties for a billing document. For example, a document property can be a custom name used for files generated for billing documents. Billing documents include invoices, credit memos, and debit memos. If you want to configure custom file names for billing documents created through API operations, you have to call this operation before posting the billing documents. **Note:** You can create document properties for credit and debit memos only if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DocumentPropertiesApi;
DocumentPropertiesApi apiInstance = new DocumentPropertiesApi();
POSTDocumentPropertiesType request = new POSTDocumentPropertiesType(); // POSTDocumentPropertiesType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
GETDocumentPropertiesResponseType result = apiInstance.pOSTDocumentProperties(request, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DocumentPropertiesApi#pOSTDocumentProperties");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTDocumentPropertiesType**](POSTDocumentPropertiesType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**GETDocumentPropertiesResponseType**](GETDocumentPropertiesResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTDocumentProperties"></a>
# **pUTDocumentProperties**
> GETDocumentPropertiesResponseType pUTDocumentProperties(request, documentPropertiesId, zuoraEntityIds, zuoraTrackId)
Update document properties
**Note:** This feature is available only if you have the Billing Document Properties Setup feature enabled. The Billing Document Properties Setup feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Updates document properties with a specific ID for a billing document. Billing documents include invoices, credit memos, and debit memos. **Note:** You can update document properties for credit and debit memos only if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DocumentPropertiesApi;
DocumentPropertiesApi apiInstance = new DocumentPropertiesApi();
PUTDocumentPropertiesType request = new PUTDocumentPropertiesType(); // PUTDocumentPropertiesType |
String documentPropertiesId = "documentPropertiesId_example"; // String | The unique ID of document properties to be updated. For example, 402892c74c9193cd014c96bbe7c101f9.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
GETDocumentPropertiesResponseType result = apiInstance.pUTDocumentProperties(request, documentPropertiesId, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DocumentPropertiesApi#pUTDocumentProperties");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**PUTDocumentPropertiesType**](PUTDocumentPropertiesType.md)| |
**documentPropertiesId** | **String**| The unique ID of document properties to be updated. For example, 402892c74c9193cd014c96bbe7c101f9. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**GETDocumentPropertiesResponseType**](GETDocumentPropertiesResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# RatePlanData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ratePlan** | [**RatePlanDataRatePlan**](RatePlanDataRatePlan.md) | |
**ratePlanChargeData** | [**List<RatePlanChargeData>**](RatePlanChargeData.md) | | [optional]
**subscriptionProductFeatureList** | [**RatePlanDataSubscriptionProductFeatureList**](RatePlanDataSubscriptionProductFeatureList.md) | | [optional]
<file_sep>
# PUTSubscriptionPatchRequestTypeCharges
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeNumber** | **String** | | [optional]
**customFields** | [**RatePlanChargeObjectCustomFields**](RatePlanChargeObjectCustomFields.md) | | [optional]
<file_sep>
# CalloutAuth
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**domain** | **String** | The domain of the callout auth. | [optional]
**password** | **String** | The field is required when requiredAuth is true. | [optional]
**preemptive** | **Boolean** | Set this field to `true` if you want to enable the preemptive authentication. | [optional]
**username** | **String** | The field is required when requiredAuth is true. | [optional]
<file_sep>
# EndConditions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**endDateCondition** | [**EndDateConditionEnum**](#EndDateConditionEnum) | Condition for the charge to become inactive. If the value of this field is `Fixed_Period`, the charge is active for a predefined duration based on the value of the `upToPeriodsType` and `upToPeriods` fields. If the value of this field is `Specific_End_Date`, use the `specificEndDate` field to specify the date when then charge becomes inactive. | [optional]
**specificEndDate** | [**LocalDate**](LocalDate.md) | Date in YYYY-MM-DD format. Only applicable if the value of the `endDateCondition` field is `Specific_End_Date`. | [optional]
**upToPeriods** | **Integer** | Duration of the charge in billing periods, days, weeks, months, or years, depending on the value of the `upToPeriodsType` field. Only applicable if the value of the `endDateCondition` field is `Fixed_Period`. | [optional]
**upToPeriodsType** | [**UpToPeriodsTypeEnum**](#UpToPeriodsTypeEnum) | Unit of time that the charge duration is measured in. Only applicable if the value of the `endDateCondition` field is `Fixed_Period`. | [optional]
<a name="EndDateConditionEnum"></a>
## Enum: EndDateConditionEnum
Name | Value
---- | -----
SUBSCRIPTION_END | "Subscription_End"
FIXED_PERIOD | "Fixed_Period"
SPECIFIC_END_DATE | "Specific_End_Date"
<a name="UpToPeriodsTypeEnum"></a>
## Enum: UpToPeriodsTypeEnum
Name | Value
---- | -----
BILLING_PERIODS | "Billing_Periods"
DAYS | "Days"
WEEKS | "Weeks"
MONTHS | "Months"
YEARS | "Years"
<file_sep>
# POSTSubscriptionPreviewResponseTypeChargeMetrics
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**dmrr** | **String** | Change in monthly recurring revenue. | [optional]
**dtcv** | **String** | Change in total contract value. | [optional]
**mrr** | **String** | Monthly recurring revenue. | [optional]
**number** | **String** | The charge number of the subscription. Only available for update subscription. | [optional]
**originRatePlanId** | **String** | The origin rate plan ID. Only available for update subscription. | [optional]
**originalId** | **String** | The original rate plan charge ID. Only available for update subscription. | [optional]
**productRatePlanChargeId** | **String** | The product rate plan charge ID. | [optional]
**productRatePlanId** | **String** | The product rate plan ID. | [optional]
**tcv** | **String** | Total contract value. | [optional]
<file_sep>
# PUTOrderPatchRequestTypeOrderActions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFields** | [**OrderActionObjectCustomFields**](OrderActionObjectCustomFields.md) | | [optional]
**sequence** | **Integer** | The sequence number of the order action in the order. | [optional]
<file_sep>
# PUTDebitMemoType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the debit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the debit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**autoPay** | **Boolean** | Whether debit memos are automatically picked up for processing in the corresponding payment run. By default, debit memos are automatically picked up for processing in the corresponding payment run. | [optional]
**comment** | **String** | Comments about the debit memo. | [optional]
**dueDate** | [**LocalDate**](LocalDate.md) | The date by which the payment for the debit memo is due, in `yyyy-mm-dd` format. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the debit memo takes effect. | [optional]
**items** | [**List<PUTDebitMemoItemType>**](PUTDebitMemoItemType.md) | Container for debit memo items. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the debit memo is transferred to an external accounting system. Use this field for integration with accounting systems, such as NetSuite. | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
NO | "No"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# ProcessingOptionsElectronicPaymentOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**paymentMethodId** | **String** | Specifies an electronic payment method. It can be one that has already been associated with an invoice owner, or an orphan payment method, which is not associated with any invoice owner. For an orphan payment method, this operation will then associate it with the account that this order will be created under. | [optional]
<file_sep>
# CreatePaymentMethodCommon
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountKey** | **String** | Internal ID of the customer account that will own the payment method. | [optional]
**authGateway** | **String** | Internal ID of the payment gateway that Zuora will use to authorize the payments that are made with the payment method. If you do not set this field, Zuora will use one of the following payment gateways instead: * The default payment gateway of the customer account that owns the payment method, if the `accountKey` field is set. * The default payment gateway of your Zuora tenant, if the `accountKey` field is not set. | [optional]
**makeDefault** | **Boolean** | Specifies whether the payment method will be the default payment method of the customer account that owns the payment method. Only applicable if the `accountKey` field is set. | [optional]
<file_sep>
# OrderActionForEvergreen
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**addProduct** | [**RatePlanOverrideForEvergreen**](RatePlanOverrideForEvergreen.md) | | [optional]
**cancelSubscription** | [**CancelSubscription**](CancelSubscription.md) | | [optional]
**createSubscription** | [**CreateSubscriptionForEvergreen**](CreateSubscriptionForEvergreen.md) | | [optional]
**customFields** | [**OrderActionObjectCustomFields**](OrderActionObjectCustomFields.md) | | [optional]
**orderMetrics** | [**List<OrderMetricsForEvergreen>**](OrderMetricsForEvergreen.md) | | [optional]
**ownerTransfer** | [**OwnerTransfer**](OwnerTransfer.md) | | [optional]
**removeProduct** | [**RemoveProduct**](RemoveProduct.md) | | [optional]
**sequence** | **Integer** | The sequence of the order actions processed in the order. | [optional]
**termsAndConditions** | [**TermsAndConditions**](TermsAndConditions.md) | | [optional]
**triggerDates** | [**List<TriggerDate>**](TriggerDate.md) | | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Type of the order action. | [optional]
**updateProduct** | [**RatePlanUpdateForEvergreen**](RatePlanUpdateForEvergreen.md) | | [optional]
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
CREATESUBSCRIPTION | "CreateSubscription"
TERMSANDCONDITIONS | "TermsAndConditions"
ADDPRODUCT | "AddProduct"
UPDATEPRODUCT | "UpdateProduct"
REMOVEPRODUCT | "RemoveProduct"
RENEWSUBSCRIPTION | "RenewSubscription"
CANCELSUBSCRIPTION | "CancelSubscription"
OWNERTRANSFER | "OwnerTransfer"
<file_sep>
# GETProductRatePlanChargeType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**classNS** | **String** | Class associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**deferredRevAccountNS** | **String** | Deferrred revenue account associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Department associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**includeChildrenNS** | [**IncludeChildrenNSEnum**](#IncludeChildrenNSEnum) | Specifies whether the corresponding item in NetSuite is visible under child subsidiaries. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the product rate plan charge's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**itemTypeNS** | [**ItemTypeNSEnum**](#ItemTypeNSEnum) | Type of item that is created in NetSuite for the product rate plan charge. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Location associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**recognizedRevAccountNS** | **String** | Recognized revenue account associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**revRecEndNS** | [**RevRecEndNSEnum**](#RevRecEndNSEnum) | End date condition of the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**revRecStartNS** | [**RevRecStartNSEnum**](#RevRecStartNSEnum) | Start date condition of the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**revRecTemplateTypeNS** | **String** | Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Subsidiary associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the product rate plan charge was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**applyDiscountTo** | **String** | Specifies where (to what charge type) the discount will be applied. These field values are case-sensitive. Permissible values: - RECURRING - USAGE - ONETIMERECURRING - ONETIMEUSAGE - RECURRINGUSAGE - ONETIMERECURRINGUSAGE | [optional]
**billingDay** | **String** | The bill cycle day (BCD) for the charge. The BCD determines which day of the month or week the customer is billed. The BCD value in the account can override the BCD in this object. | [optional]
**billingPeriod** | **String** | The billing period for the charge. The start day of the billing period is also called the bill cycle day (BCD). Values: - Month - Quarter - Annual - Semi-Annual - Specific Months - Week - Specific_Weeks | [optional]
**billingPeriodAlignment** | **String** | Aligns charges within the same subscription if multiple charges begin on different dates. Possible values: - AlignToCharge - AlignToSubscriptionStart - AlignToTermStart | [optional]
**billingTiming** | **String** | The billing timing for the charge. You can choose to bill for charges in advance or in arrears. Values: - In Advance - In Arrears **Note:** This feature is in Limited Availability. If you wish to have access to the feature, submit a request at [Zuora Global Support](https://support.zuora.com). | [optional]
**defaultQuantity** | **String** | The default quantity of units. This field is required if you use a per-unit charge model. | [optional]
**description** | **String** | Usually a brief line item summary of the Rate Plan Charge. | [optional]
**discountClass** | **String** | The class that the discount belongs to. The discount class defines the order in which discount product rate plan charges are applied. For more information, see [Manage Discount Classes](https://knowledgecenter.zuora.com/BC_Subscription_Management/Product_Catalog/B_Charge_Models/Manage_Discount_Classes). | [optional]
**discountLevel** | **String** | The level of the discount. Values: - RatePlan - Subscription - Account | [optional]
**endDateCondition** | **String** | Defines when the charge ends after the charge trigger date. If the subscription ends before the charge end date, the charge ends when the subscription ends. But if the subscription end date is subsequently changed through a Renewal, or Terms and Conditions amendment, the charge will end on the charge end date. Values: - Subscription_End - Fixed_Period | [optional]
**financeInformation** | [**FinanceInformation**](FinanceInformation.md) | | [optional]
**id** | **String** | Unique product rate-plan charge ID. | [optional]
**includedUnits** | **String** | Specifies the number of units in the base set of units when the charge model is Overage. | [optional]
**listPriceBase** | **String** | The list price base for the product rate plan charge. Values: - Month - Billing Period - Per_Week | [optional]
**maxQuantity** | **String** | Specifies the maximum number of units for this charge. Use this field and the `minQuantity` field to create a range of units allowed in a product rate plan charge. | [optional]
**minQuantity** | **String** | Specifies the minimum number of units for this charge. Use this field and the `maxQuantity` field to create a range of units allowed in a product rate plan charge. | [optional]
**model** | **String** | Charge model which determines how charges are calculated. Charge models must be individually activated in Zuora Billing administration. Possible values are: - FlatFee - PerUnit - Overage - Volume - Tiered - TieredWithOverage - DiscountFixedAmount - DiscountPercentage The Pricing Summaries section below details these charge models and their associated pricingSummary values. | [optional]
**name** | **String** | Name of the product rate-plan charge. (Not required to be unique.) | [optional]
**numberOfPeriods** | **Long** | Value specifies the number of periods used in the smoothing model calculations Used when overage smoothing model is `RollingWindow` or `Rollover`. | [optional]
**overageCalculationOption** | **String** | Value specifies when to calculate overage charges. Values: - EndOfSmoothingPeriod - PerBillingPeriod | [optional]
**overageUnusedUnitsCreditOption** | **String** | Determines whether to credit the customer with unused units of usage. Values: - NoCredit - CreditBySpecificRate | [optional]
**prepayPeriods** | **Long** | The number of periods to which prepayment is set. **Note:** This field is only available if you already have the prepayment feature enabled. The prepayment feature is deprecated and available only for backward compatibility. Zuora does not support enabling this feature anymore. | [optional]
**priceChangeOption** | **String** | Applies an automatic price change when a termed subscription is renewed and the following applies: 1. AutomatedPriceChange setting is on 2. Charge type is not one-time 3. Charge model is not discount fixed amount Values: - NoChange (default) - SpecificPercentageValue - UseLatestProductCatalogPricing | [optional]
**priceIncreasePercentage** | **String** | Specifies the percentage to increase or decrease the price of a termed subscription's renewal. Use this field if you set the `PriceChangeOption` value to `SpecificPercentageValue`. 1. AutomatedPriceChange setting is on 2. Charge type is not one-time 3. Charge model is not discount fixed amount Values: a decimal between -100 and 100 | [optional]
**pricing** | [**List<GETProductRatePlanChargePricingType>**](GETProductRatePlanChargePricingType.md) | One or more price charge models with attributes that further describe the model. Some attributes show as null values when not applicable. | [optional]
**pricingSummary** | **List<String>** | A concise description of the charge model and pricing that is suitable to show to your customers. When the rate plan charge model is `Tiered` and multi-currency is enabled, this field includes an array of string of each currency, and each string of currency includes tier price description separated by comma. | [optional]
**productDiscountApplyDetails** | [**List<GETProductDiscountApplyDetailsType>**](GETProductDiscountApplyDetailsType.md) | Container for the application details about a discount product rate plan charge. Only discount product rate plan charges have values in this field. | [optional]
**ratingGroup** | **String** | Specifies a rating group based on which usage records are rated. **Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Possible values: - `ByBillingPeriod` (default): The rating is based on all the usages in a billing period. - `ByUsageStartDate`: The rating is based on all the usages on the same usage start date. - `ByUsageRecord`: The rating is based on each usage record. - `ByUsageUpload`: The rating is based on all the usages in a uploaded usage file (`.xls` or `.csv`). - `ByGroupId`: The rating is based on all the usages in a custom group. **Note:** - The `ByBillingPeriod` value can be applied for all charge models. - The `ByUsageStartDate`, `ByUsageRecord`, and `ByUsageUpload` values can only be applied for per unit, volume pricing, and tiered pricing charge models. - The `ByGroupId` value is only available if you have [Real-Time Usage Rating](https://knowledgecenter.zuora.com/CB_Billing/J_Billing_Operations/Real-Time_Usage_Rating) feature enabled. - Use this field only for Usage charges. One-Time Charges and Recurring Charges return `NULL`. | [optional]
**revenueRecognitionRuleName** | **String** | The name of the revenue recognition rule governing the revenue schedule. | [optional]
**smoothingModel** | **String** | Specifies the smoothing model for an overage smoothing charge model or an tiered with overage model, which is an advanced type of a usage model that avoids spikes in usage charges. If a customer's usage spikes in a single period, then an overage smoothing model eases overage charges by considering usage and multiple periods. One of the following values shows which smoothing model will be applied to the charge when `Overage` or `Tiered with Overage` is used: - `RollingWindow` considers a number of periods to smooth usage. The rolling window starts and increments forward based on billing frequency. When allowed usage is met, then period resets and a new window begins. - `Rollover` considers a fixed number of periods before calculating usage. The net balance at the end of a period is unused usage, which is carried over to the next period's balance. | [optional]
**specificBillingPeriod** | **Long** | When the billing period is set to `Specific` Months then this positive integer reflects the number of months for billing period charges. | [optional]
**taxCode** | **String** | Specifies the tax code for taxation rules; used by Zuora Tax. | [optional]
**taxMode** | **String** | Specifies how to define taxation for the charge; used by Zuora Tax. Possible values are: `TaxExclusive`, `TaxInclusive`. | [optional]
**taxable** | **Boolean** | Specifies whether the charge is taxable; used by Zuora Tax. Possible values are:`true`, `false`. | [optional]
**triggerEvent** | **String** | Specifies when to start billing the customer for the charge. Values: one of the following: - `ContractEffective` is the date when the subscription's contract goes into effect and the charge is ready to be billed. - `ServiceActivation` is the date when the services or products for a subscription have been activated and the customers have access. - `CustomerAcceptance` is when the customer accepts the services or products for a subscription. - `SpecificDate` is the date specified. | [optional]
**type** | **String** | The type of charge. Possible values are: `OneTime`, `Recurring`, `Usage`. | [optional]
**uom** | **String** | Describes the Units of Measure (uom) configured in **Settings > Billing** for the productRatePlanCharges. Values: `Each`, `License`, `Seat`, or `null` | [optional]
**upToPeriods** | **Long** | Specifies the length of the period during which the charge is active. If this period ends before the subscription ends, the charge ends when this period ends. If the subscription end date is subsequently changed through a Renewal, or Terms and Conditions amendment, the charge end date will change accordingly up to the original period end. | [optional]
**upToPeriodsType** | **String** | The period type used to define when the charge ends. Values: - Billing_Periods - Days - Weeks - Months - Years | [optional]
**usageRecordRatingOption** | **String** | Determines how Zuora processes usage records for per-unit usage charges. | [optional]
**useDiscountSpecificAccountingCode** | **Boolean** | Determines whether to define a new accounting code for the new discount charge. Values: `true`, `false` | [optional]
**useTenantDefaultForPriceChange** | **Boolean** | Shows the tenant-level percentage uplift value for an automatic price change to a termed subscription's renewal. You set the tenant uplift value in the web-based UI: **Settings > Billing > Define Default Subscription Settings**. Values: `true`, `false` | [optional]
<a name="IncludeChildrenNSEnum"></a>
## Enum: IncludeChildrenNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<a name="ItemTypeNSEnum"></a>
## Enum: ItemTypeNSEnum
Name | Value
---- | -----
INVENTORY | "Inventory"
NON_INVENTORY | "Non Inventory"
SERVICE | "Service"
<a name="RevRecEndNSEnum"></a>
## Enum: RevRecEndNSEnum
Name | Value
---- | -----
CHARGE_PERIOD_START | "Charge Period Start"
REV_REC_TRIGGER_DATE | "Rev Rec Trigger Date"
USE_NETSUITE_REV_REC_TEMPLATE | "Use NetSuite Rev Rec Template"
<a name="RevRecStartNSEnum"></a>
## Enum: RevRecStartNSEnum
Name | Value
---- | -----
CHARGE_PERIOD_START | "Charge Period Start"
REV_REC_TRIGGER_DATE | "Rev Rec Trigger Date"
USE_NETSUITE_REV_REC_TEMPLATE | "Use NetSuite Rev Rec Template"
<file_sep>
# SubscriptionProductFeatureList
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**subscriptionProductFeature** | [**List<SubscriptionProductFeature>**](SubscriptionProductFeature.md) | | [optional]
<file_sep>
# BatchDebitMemoType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**dueDate** | [**LocalDate**](LocalDate.md) | The date by which the payment for the debit memo is due, in `yyyy-mm-dd` format. | [optional]
**id** | **String** | The ID of the debit memo to be updated. | [optional]
<file_sep># RevenueRulesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETRevenueRecRulebyProductRatePlanCharge**](RevenueRulesApi.md#gETRevenueRecRulebyProductRatePlanCharge) | **GET** /v1/revenue-recognition-rules/product-charges/{charge-key} | Get revenue recognition rule by product rate plan charge
[**gETRevenueRecRules**](RevenueRulesApi.md#gETRevenueRecRules) | **GET** /v1/revenue-recognition-rules/subscription-charges/{charge-key} | Get revenue recognition rule by subscription charge
<a name="gETRevenueRecRulebyProductRatePlanCharge"></a>
# **gETRevenueRecRulebyProductRatePlanCharge**
> GETRevenueRecognitionRuleAssociationType gETRevenueRecRulebyProductRatePlanCharge(chargeKey)
Get revenue recognition rule by product rate plan charge
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the revenue recognition rule associated with a production rate plan charge by specifying the charge ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueRulesApi;
RevenueRulesApi apiInstance = new RevenueRulesApi();
String chargeKey = "chargeKey_example"; // String | The unique ID of a product rate plan charge. For example, 8a8082e65ba86084015bb323d3c61d82.
try {
GETRevenueRecognitionRuleAssociationType result = apiInstance.gETRevenueRecRulebyProductRatePlanCharge(chargeKey);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueRulesApi#gETRevenueRecRulebyProductRatePlanCharge");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**chargeKey** | **String**| The unique ID of a product rate plan charge. For example, <KEY>. |
### Return type
[**GETRevenueRecognitionRuleAssociationType**](GETRevenueRecognitionRuleAssociationType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRevenueRecRules"></a>
# **gETRevenueRecRules**
> GETRevenueRecognitionRuleAssociationType gETRevenueRecRules(chargeKey, zuoraEntityIds)
Get revenue recognition rule by subscription charge
Retrieves the revenue recognition rule associated with a subscription charge by specifying the charge ID. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueRulesApi;
RevenueRulesApi apiInstance = new RevenueRulesApi();
String chargeKey = "chargeKey_example"; // String | The unique ID of the subscription rate plan charge. For example, 402892793e173340013e173b81000012.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRevenueRecognitionRuleAssociationType result = apiInstance.gETRevenueRecRules(chargeKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueRulesApi#gETRevenueRecRules");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**chargeKey** | **String**| The unique ID of the subscription rate plan charge. For example, 402892793e173340013e173b81000012. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRevenueRecognitionRuleAssociationType**](GETRevenueRecognitionRuleAssociationType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# ProductFeatureObjectCustomFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
<file_sep>
# GETPaymentRunCollectionType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nextPage** | **String** | The URL for requesting the next page of the response, if it exists; otherwise absent. | [optional]
**paymentRuns** | [**List<GETPaymentRunType>**](GETPaymentRunType.md) | Container for payment runs. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<file_sep>
# GETInvoiceType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the invoice's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the invoice was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | Customer account ID. | [optional]
**accountName** | **String** | Customer account name. | [optional]
**accountNumber** | **String** | Customer account number. | [optional]
**amount** | **String** | Amount of the invoice before adjustments, discounts, and similar items. | [optional]
**balance** | **String** | Balance remaining due on the invoice (after adjustments, discounts, etc.) | [optional]
**body** | **String** | The REST URL of the invoice PDF file. | [optional]
**createdBy** | **String** | User ID of the person who created the invoice. If a bill run generated the invoice, then this is the user ID of person who created the bill run. | [optional]
**creditBalanceAdjustmentAmount** | **String** | | [optional]
**dueDate** | [**LocalDate**](LocalDate.md) | Payment due date as _yyyy-mm-dd_. | [optional]
**id** | **String** | Invoice ID. | [optional]
**invoiceDate** | [**LocalDate**](LocalDate.md) | Invoice date as _yyyy-mm-dd_ | [optional]
**invoiceFiles** | **String** | URL to retrieve information about all files of a specific invoice if any file exists; otherwise absent. For example, `https://rest.zuora.com/v1/invoices/2c92c095511f5b4401512682dcfd7987/files`. If you want to view the invoice file details, call [Get invoice files](https://www.zuora.com/developer/api-reference/#operation/GET_InvoiceFiles) with the returned URL. If your tenant was created before Zuora Release 228 (R228), July 2018, the value of this field is an array of invoice file details. For more information about the array, see the response body of [Get invoice files](https://www.zuora.com/developer/api-reference/#operation/GET_InvoiceFiles). Zuora recommends that you use the latest behavior to retrieve invoice information. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/) asking for invoice item and file references to be enabled in the REST API. | [optional]
**invoiceItems** | **String** | URL to retrieve information about all items of a specific invoice. For example, `https://rest.zuora.com/v1/invoices/2c92c095511f5b4401512682dcfd7987/items`. If you want to view the invoice item details, call [Get invoice items](https://www.zuora.com/developer/api-reference/#operation/GET_InvoiceItems) with the returned URL. If your tenant was created before Zuora Release 228 (R228), July 2018, the value of this field is an array of invoice item details. For more information about the array, see the response body of [Get invoice items](https://www.zuora.com/developer/api-reference/#operation/GET_InvoiceItems). Zuora recommends that you use the latest behavior to retrieve invoice information. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/) asking for invoice item and file references to be enabled in the REST API. | [optional]
**invoiceNumber** | **String** | Unique invoice ID, returned as a string. | [optional]
**invoiceTargetDate** | [**LocalDate**](LocalDate.md) | Date through which charges on this invoice are calculated, as _yyyy-mm-dd_. | [optional]
**status** | **String** | Status of the invoice in the system - not the payment status, but the status of the invoice itself. Possible values are: `Posted`, `Draft`, `Canceled`, `Error`. | [optional]
<file_sep>
# POSTAuthorizeResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**gatewayOrderId** | **String** | The order ID for the gateway. | [optional]
**resultCode** | **String** | The result code of the request. 0 indicates the call succeeded, and other values indicate the call failed. | [optional]
**resultMessage** | **String** | The corresponding request ID. | [optional]
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**transactionId** | **String** | The ID of the transaction. | [optional]
<file_sep>
# GETJournalEntryDetailTypeWithoutSuccess
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountingPeriodName** | **String** | Name of the accounting period that the journal entry belongs to. | [optional]
**aggregateCurrency** | **Boolean** | Returns true if the journal entry is aggregating currencies. That is, if the journal entry was created when the `Aggregate transactions with different currencies during a JournalRun` setting was configured to \"Yes\". Otherwise, returns `false`. | [optional]
**currency** | **String** | Currency used. | [optional]
**homeCurrency** | **String** | Home currency used. | [optional]
**journalEntryDate** | [**LocalDate**](LocalDate.md) | Date of the journal entry. | [optional]
**journalEntryItems** | [**List<GETJournalEntryItemType>**](GETJournalEntryItemType.md) | Key name that represents the list of journal entry items. | [optional]
**notes** | **String** | Additional information about this record. Character limit: 2,000 | [optional]
**number** | **String** | Journal entry number in the format JE-00000001. | [optional]
**segments** | [**List<GETJournalEntrySegmentType>**](GETJournalEntrySegmentType.md) | List of segments that apply to the summary journal entry. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | Status of journal entry. | [optional]
**timePeriodEnd** | [**LocalDate**](LocalDate.md) | End date of time period included in the journal entry. | [optional]
**timePeriodStart** | [**LocalDate**](LocalDate.md) | Start date of time period included in the journal entry. | [optional]
**transactionType** | **String** | Transaction type of the transactions included in the summary journal entry. | [optional]
**transferDateTime** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time that transferredToAccounting was changed to `Yes`. This field is returned only when transferredToAccounting is `Yes`. Otherwise, this field is `null`. | [optional]
**transferredBy** | **String** | User ID of the person who changed transferredToAccounting to `Yes`. This field is returned only when transferredToAccounting is `Yes`. Otherwise, this field is `null`. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Status shows whether the journal entry has been transferred to an accounting system. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
CREATED | "Created"
CANCELLED | "Cancelled"
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
NO | "No"
PROCESSING | "Processing"
YES | "Yes"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# GETAccountTypeMetrics
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**balance** | **String** | The customer's total invoice balance minus credit balance. | [optional]
**contractedMrr** | **String** | Future expected MRR that accounts for future upgrades, downgrades, upsells and cancellations. | [optional]
**creditBalance** | **String** | Current credit balance. | [optional]
**totalInvoiceBalance** | **String** | Total of all open invoices. | [optional]
<file_sep># ImportsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectGETImport**](ImportsApi.md#objectGETImport) | **GET** /v1/object/import/{id} | CRUD: Retrieve Import
[**objectPOSTImport**](ImportsApi.md#objectPOSTImport) | **POST** /v1/object/import | CRUD: Create Import
<a name="objectGETImport"></a>
# **objectGETImport**
> ProxyGetImport objectGETImport(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Import
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ImportsApi;
ImportsApi apiInstance = new ImportsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetImport result = apiInstance.objectGETImport(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ImportsApi#objectGETImport");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetImport**](ProxyGetImport.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTImport"></a>
# **objectPOSTImport**
> ProxyPostImport objectPOSTImport(importType, name, file, zuoraEntityIds, zuoraTrackId)
CRUD: Create Import
Creates a data import.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ImportsApi;
ImportsApi apiInstance = new ImportsApi();
String importType = "importType_example"; // String | The type of data to import.
String name = "name_example"; // String | A descriptive name for the import.
File file = new File("/path/to/file.txt"); // File | The data to import.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyPostImport result = apiInstance.objectPOSTImport(importType, name, file, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ImportsApi#objectPOSTImport");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**importType** | **String**| The type of data to import. | [enum: Usage, Payment, Quote, TaxationDetail, UpdateAccountingCode, CreateRevenueSchedule, UpdateRevenueSchedule, DeleteRevenueSchedule, ImportFXRate, MPU]
**name** | **String**| A descriptive name for the import. |
**file** | **File**| The data to import. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyPostImport**](ProxyPostImport.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json; charset=utf-8
<file_sep>
# GETRsRevenueItemsType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nextPage** | **String** | URL to retrieve the next page of the response if it exists; otherwise absent. | [optional]
**revenueItems** | [**List<GETRsRevenueItemType>**](GETRsRevenueItemType.md) | Revenue items are listed in ascending order by the accounting period start date. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<file_sep>
# GETDocumentPropertiesResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFileName** | **String** | The custom file name used by Word or PDF files generated for the billing document. | [optional]
**documentId** | **String** | The unique ID of a billing document. | [optional]
**documentType** | [**DocumentTypeEnum**](#DocumentTypeEnum) | The type of the billing document. | [optional]
**id** | **String** | The unique ID of a document property. | [optional]
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
<a name="DocumentTypeEnum"></a>
## Enum: DocumentTypeEnum
Name | Value
---- | -----
INVOICE | "Invoice"
CREDITMEMO | "CreditMemo"
DEBITMEMO | "DebitMemo"
<file_sep># ConnectionsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**pOSTConnections**](ConnectionsApi.md#pOSTConnections) | **POST** /v1/connections | Establish connection to Zuora REST API service
<a name="pOSTConnections"></a>
# **pOSTConnections**
> CommonResponseType pOSTConnections(apiAccessKeyId, apiSecretAccessKey, contentType, zuoraEntityIds)
Establish connection to Zuora REST API service
Establishes a connection to the Zuora REST API service based on a valid user credentials. **Note:**This is a legacy REST API. Zuora recommends you to use [OAuth](https://www.zuora.com/developer/api-reference/#section/Authentication/OAuth-v2.0) for authentication instead. This call authenticates the user and returns an API session cookie that's used to authorize subsequent calls to the REST API. The credentials must belong to a user account that has permission to access the API service. As noted elsewhere, it's strongly recommended that an account used for Zuora API activity is never used to log into the Zuora UI. Once an account is used to log into the UI, it may be subject to periodic forced password changes, which may eventually lead to authentication failures when using the API.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ConnectionsApi;
ConnectionsApi apiInstance = new ConnectionsApi();
String apiAccessKeyId = "apiAccessKeyId_example"; // String | Account username
String apiSecretAccessKey = "apiSecretAccessKey_example"; // String | Account password
String contentType = "contentType_example"; // String | Must be set to \"application/json\"
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pOSTConnections(apiAccessKeyId, apiSecretAccessKey, contentType, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConnectionsApi#pOSTConnections");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**apiAccessKeyId** | **String**| Account username |
**apiSecretAccessKey** | **String**| Account password |
**contentType** | **String**| Must be set to \"application/json\" |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># PaymentMethodSnapshotsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEPaymentMethodSnapshot**](PaymentMethodSnapshotsApi.md#objectDELETEPaymentMethodSnapshot) | **DELETE** /v1/object/payment-method-snapshot/{id} | CRUD: Delete PaymentMethodSnapshot
[**objectGETPaymentMethodSnapshot**](PaymentMethodSnapshotsApi.md#objectGETPaymentMethodSnapshot) | **GET** /v1/object/payment-method-snapshot/{id} | CRUD: Retrieve PaymentMethodSnapshot
<a name="objectDELETEPaymentMethodSnapshot"></a>
# **objectDELETEPaymentMethodSnapshot**
> ProxyDeleteResponse objectDELETEPaymentMethodSnapshot(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete PaymentMethodSnapshot
This REST API reference describes how to delete a Payment Method Snapshot.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodSnapshotsApi;
PaymentMethodSnapshotsApi apiInstance = new PaymentMethodSnapshotsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEPaymentMethodSnapshot(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodSnapshotsApi#objectDELETEPaymentMethodSnapshot");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETPaymentMethodSnapshot"></a>
# **objectGETPaymentMethodSnapshot**
> ProxyGetPaymentMethodSnapshot objectGETPaymentMethodSnapshot(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve PaymentMethodSnapshot
This REST API reference describes how to retrieve a Payment Method Snapshot. A Payment Method Snapshot is a copy of the particular Payment Method used in a transaction. If the Payment Method is deleted, the Payment Method Snapshot continues to retain the data used in each of the past transactions. ## Notes The following Payment Method fields are not available in Payment Method Snapshots: * `Active` * `AchAddress1` * `AchAddress2` * `CreatedById` * `CreatedDate` * `UpdatedById` * `UpdatedDate` The Payment Method Snapshot field `PaymentMethodId` is not available in Payment Methods.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodSnapshotsApi;
PaymentMethodSnapshotsApi apiInstance = new PaymentMethodSnapshotsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetPaymentMethodSnapshot result = apiInstance.objectGETPaymentMethodSnapshot(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodSnapshotsApi#objectGETPaymentMethodSnapshot");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetPaymentMethodSnapshot**](ProxyGetPaymentMethodSnapshot.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# CreateOrderCreateSubscriptionTerms
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**autoRenew** | **Boolean** | Specifies whether the subscription automatically renews at the end of the each term. Only applicable if the type of the first term is `TERMED`. | [optional]
**initialTerm** | [**CreateOrderCreateSubscriptionTermsInitialTerm**](CreateOrderCreateSubscriptionTermsInitialTerm.md) | |
**renewalSetting** | [**RenewalSettingEnum**](#RenewalSettingEnum) | Specifies the type of the terms that follow the first term if the subscription is renewed. Only applicable if the type of the first term is `TERMED`. * `RENEW_WITH_SPECIFIC_TERM` - Each renewal term has a predefined duration. The first entry in `renewalTerms` specifies the duration of the second term of the subscription, the second entry in `renewalTerms` specifies the duration of the third term of the subscription, and so on. The last entry in `renewalTerms` specifies the ultimate duration of each renewal term. * `RENEW_TO_EVERGREEN` - The second term of the subscription does not have a predefined duration. | [optional]
**renewalTerms** | [**List<RenewalTerm>**](RenewalTerm.md) | List of renewal terms of the subscription. Only applicable if the type of the first term is `TERMED` and the value of the `renewalSetting` field is `RENEW_WITH_SPECIFIC_TERM`. | [optional]
<a name="RenewalSettingEnum"></a>
## Enum: RenewalSettingEnum
Name | Value
---- | -----
WITH_SPECIFIC_TERM | "RENEW_WITH_SPECIFIC_TERM"
TO_EVERGREEN | "RENEW_TO_EVERGREEN"
<file_sep>
# GetOrderRatedResultResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**orderRatedResult** | [**OrderRatedResult**](OrderRatedResult.md) | | [optional]
<file_sep>
# GETRevenueStartDateSettingType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**startDate** | [**LocalDate**](LocalDate.md) | The date on which revenue automation starts. This is the first day of an accounting period. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**updatedBy** | **String** | The user who made the change. | [optional]
**updatedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the revenue automation start date was set. | [optional]
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.POSTQuoteDocResponseType;
import de.keylight.zuora.client.model.POSTQuoteDocType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.QuotesDocumentApi")
public class QuotesDocumentApi {
private ApiClient apiClient;
public QuotesDocumentApi() {
this(new ApiClient());
}
@Autowired
public QuotesDocumentApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Generate quotes document
* The `document` call generates a quote document and returns the generated document URL. You can directly access the generated quote file through the returned URL. The `document` call should be only used from Zuora Quotes. ## File Size Limitation The maximum export file size is 2047MB. If you have large data requests that go over this limit, you will get the following 403 HTTP response code from Zuora: `security:max-object-size>2047MB</security:max-object-size>` Submit a request at [Zuora Global Support](http://support.zuora.com/) if you require additional assistance. We can work with you to determine if large file optimization is an option for you.
* <p><b>200</b> -
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return POSTQuoteDocResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public POSTQuoteDocResponseType pOSTQuotesDocument(POSTQuoteDocType request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTQuotesDocument");
}
String path = UriComponentsBuilder.fromPath("/v1/quotes/document").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<POSTQuoteDocResponseType> returnType = new ParameterizedTypeReference<POSTQuoteDocResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep># PaymentMethodTransactionLogsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectGETPaymentMethodTransactionLog**](PaymentMethodTransactionLogsApi.md#objectGETPaymentMethodTransactionLog) | **GET** /v1/object/payment-method-transaction-log/{id} | CRUD: Retrieve PaymentMethodTransactionLog
<a name="objectGETPaymentMethodTransactionLog"></a>
# **objectGETPaymentMethodTransactionLog**
> ProxyGetPaymentMethodTransactionLog objectGETPaymentMethodTransactionLog(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve PaymentMethodTransactionLog
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodTransactionLogsApi;
PaymentMethodTransactionLogsApi apiInstance = new PaymentMethodTransactionLogsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetPaymentMethodTransactionLog result = apiInstance.objectGETPaymentMethodTransactionLog(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodTransactionLogsApi#objectGETPaymentMethodTransactionLog");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetPaymentMethodTransactionLog**](ProxyGetPaymentMethodTransactionLog.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# DebitMemoFromChargeType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the debit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the debit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The ID of the account associated with the debit memo. |
**autoPay** | **Boolean** | Whether debit memos are automatically picked up for processing in the corresponding payment run. By default, debit memos are automatically picked up for processing in the corresponding payment run. | [optional]
**charges** | [**List<DebitMemoFromChargeDetailType>**](DebitMemoFromChargeDetailType.md) | Container for product rate plan charges. | [optional]
**comment** | **String** | Comments about the debit memo. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the debit memo takes effect. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. | [optional]
<file_sep>
# RatePlanChargeDataInRatePlanData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ratePlanCharge** | [**RatePlanChargeDataInRatePlanDataRatePlanCharge**](RatePlanChargeDataInRatePlanDataRatePlanCharge.md) | |
**ratePlanChargeTier** | [**List<RatePlanChargeTier>**](RatePlanChargeTier.md) | | [optional]
<file_sep>
# GETJournalEntryItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountingCodeName** | **String** | Name of the accounting code. | [optional]
**accountingCodeType** | [**AccountingCodeTypeEnum**](#AccountingCodeTypeEnum) | Accounting code type. Note that `On-Account Receivable` is only available if you enable the Invoice Settlement feature. | [optional]
**amount** | **String** | Journal entry item amount in transaction currency. | [optional]
**glAccountName** | **String** | The account number in the general ledger (GL) that corresponds to the accounting code. | [optional]
**glAccountNumber** | **String** | The account name in the general ledger (GL) that corresponds to the accounting code. | [optional]
**homeCurrencyAmount** | **String** | Journal entry item amount in home currency. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Type of journal entry item. | [optional]
<a name="AccountingCodeTypeEnum"></a>
## Enum: AccountingCodeTypeEnum
Name | Value
---- | -----
ACCOUNTSRECEIVABLE | "AccountsReceivable"
ON_ACCOUNT_RECEIVABLE | "On-Account Receivable"
CASH | "Cash"
OTHERASSETS | "OtherAssets"
CUSTOMERCASHONACCOUNT | "CustomerCashOnAccount"
DEFERREDREVENUE | "DeferredRevenue"
SALESTAXPAYABLE | "SalesTaxPayable"
OTHERLIABILITIES | "OtherLiabilities"
SALESREVENUE | "SalesRevenue"
SALESDISCOUNTS | "SalesDiscounts"
OTHERREVENUE | "OtherRevenue"
OTHEREQUITY | "OtherEquity"
BADDEBT | "BadDebt"
OTHEREXPENSES | "OtherExpenses"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
CREDIT | "Credit"
DEBIT | "Debit"
<file_sep># zuora-api-client
[](https://jitpack.io/#keylightberlin/zuora-sdk)
## Generation command
```
swagger-codegen generate \
-i https://www.zuora.com/wp-content/themes/zuora/yaml/swagger.yaml \
--api-package de.keylight.zuora.client.api \
--model-package de.keylight.zuora.client.model \
--invoker-package de.keylight.zuora.client.invoker \
--group-id de.keylight \
--artifact-id zuora-api-client \
--artifact-version 0.0.1-SNAPSHOT \
-l java \
--library resttemplate \
-o zuora-sdk2
```
## Requirements
Building the API client library requires [Maven](https://maven.apache.org/) to be installed.
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn deploy
```
Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.
### Maven users
Add this dependency to your project's POM:
```xml
<dependency>
<groupId>de.keylight</groupId>
<artifactId>zuora-api-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
```
### Gradle users
Add this dependency to your project's build file:
```groovy
compile "de.keylight:zuora-api-client:0.0.1-SNAPSHOT"
```
### Others
At first generate the JAR by executing:
mvn package
Then manually install the following JARs:
* target/zuora-api-client-0.0.1-SNAPSHOT.jar
* target/lib/*.jar
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
```java
import de.keylight.zuora.client.invoker.*;
import de.keylight.zuora.client.invoker.auth.*;
import de.keylight.zuora.client.model.*;
import de.keylight.zuora.client.api.AccountingCodesApi;
import java.io.File;
import java.util.*;
public class AccountingCodesApiExample {
public static void main(String[] args) {
AccountingCodesApi apiInstance = new AccountingCodesApi();
String acId = "acId_example"; // String | ID of the accounting code you want to delete.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEAccountingCode(acId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#dELETEAccountingCode");
e.printStackTrace();
}
}
}
```
## Documentation for API Endpoints
All URIs are relative to *https://rest.zuora.com*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AccountingCodesApi* | [**dELETEAccountingCode**](docs/AccountingCodesApi.md#dELETEAccountingCode) | **DELETE** /v1/accounting-codes/{ac-id} | Delete accounting code
*AccountingCodesApi* | [**gETAccountingCode**](docs/AccountingCodesApi.md#gETAccountingCode) | **GET** /v1/accounting-codes/{ac-id} | Query an accounting code
*AccountingCodesApi* | [**gETAllAccountingCodes**](docs/AccountingCodesApi.md#gETAllAccountingCodes) | **GET** /v1/accounting-codes | Get all accounting codes
*AccountingCodesApi* | [**pOSTAccountingCode**](docs/AccountingCodesApi.md#pOSTAccountingCode) | **POST** /v1/accounting-codes | Create accounting code
*AccountingCodesApi* | [**pUTAccountingCode**](docs/AccountingCodesApi.md#pUTAccountingCode) | **PUT** /v1/accounting-codes/{ac-id} | Update an accounting code
*AccountingCodesApi* | [**pUTActivateAccountingCode**](docs/AccountingCodesApi.md#pUTActivateAccountingCode) | **PUT** /v1/accounting-codes/{ac-id}/activate | Activate accounting code
*AccountingCodesApi* | [**pUTDeactivateAccountingCode**](docs/AccountingCodesApi.md#pUTDeactivateAccountingCode) | **PUT** /v1/accounting-codes/{ac-id}/deactivate | Deactivate accounting code
*AccountingPeriodsApi* | [**dELETEAccountingPeriod**](docs/AccountingPeriodsApi.md#dELETEAccountingPeriod) | **DELETE** /v1/accounting-periods/{ap-id} | Delete accounting period
*AccountingPeriodsApi* | [**gETAccountingPeriod**](docs/AccountingPeriodsApi.md#gETAccountingPeriod) | **GET** /v1/accounting-periods/{ap-id} | Get accounting period
*AccountingPeriodsApi* | [**gETAllAccountingPeriods**](docs/AccountingPeriodsApi.md#gETAllAccountingPeriods) | **GET** /v1/accounting-periods | Get all accounting periods
*AccountingPeriodsApi* | [**pOSTAccountingPeriod**](docs/AccountingPeriodsApi.md#pOSTAccountingPeriod) | **POST** /v1/accounting-periods | Create accounting period
*AccountingPeriodsApi* | [**pUTCloseAccountingPeriod**](docs/AccountingPeriodsApi.md#pUTCloseAccountingPeriod) | **PUT** /v1/accounting-periods/{ap-id}/close | Close accounting period
*AccountingPeriodsApi* | [**pUTPendingCloseAccountingPeriod**](docs/AccountingPeriodsApi.md#pUTPendingCloseAccountingPeriod) | **PUT** /v1/accounting-periods/{ap-id}/pending-close | Set accounting period to pending close
*AccountingPeriodsApi* | [**pUTReopenAccountingPeriod**](docs/AccountingPeriodsApi.md#pUTReopenAccountingPeriod) | **PUT** /v1/accounting-periods/{ap-id}/reopen | Re-open accounting period
*AccountingPeriodsApi* | [**pUTRunTrialBalance**](docs/AccountingPeriodsApi.md#pUTRunTrialBalance) | **PUT** /v1/accounting-periods/{ap-id}/run-trial-balance | Run trial balance
*AccountingPeriodsApi* | [**pUTUpdateAccountingPeriod**](docs/AccountingPeriodsApi.md#pUTUpdateAccountingPeriod) | **PUT** /v1/accounting-periods/{ap-id} | Update accounting period
*AccountsApi* | [**gETAccount**](docs/AccountsApi.md#gETAccount) | **GET** /v1/accounts/{account-key} | Get account
*AccountsApi* | [**gETAccountSummary**](docs/AccountsApi.md#gETAccountSummary) | **GET** /v1/accounts/{account-key}/summary | Get account summary
*AccountsApi* | [**gETBillingDocumentFilesDeletionJob**](docs/AccountsApi.md#gETBillingDocumentFilesDeletionJob) | **GET** /v1/accounts/billing-documents/files/deletion-jobs/{jobId} | Get job of hard deleting billing document files
*AccountsApi* | [**objectDELETEAccount**](docs/AccountsApi.md#objectDELETEAccount) | **DELETE** /v1/object/account/{id} | CRUD: Delete Account
*AccountsApi* | [**objectGETAccount**](docs/AccountsApi.md#objectGETAccount) | **GET** /v1/object/account/{id} | CRUD: Retrieve Account
*AccountsApi* | [**objectPOSTAccount**](docs/AccountsApi.md#objectPOSTAccount) | **POST** /v1/object/account | CRUD: Create Account
*AccountsApi* | [**objectPUTAccount**](docs/AccountsApi.md#objectPUTAccount) | **PUT** /v1/object/account/{id} | CRUD: Update Account
*AccountsApi* | [**pOSTAccount**](docs/AccountsApi.md#pOSTAccount) | **POST** /v1/accounts | Create account
*AccountsApi* | [**pOSTBillingDocumentFilesDeletionJob**](docs/AccountsApi.md#pOSTBillingDocumentFilesDeletionJob) | **POST** /v1/accounts/billing-documents/files/deletion-jobs | Create job to hard delete billing document files
*AccountsApi* | [**pOSTGenerateBillingDocuments**](docs/AccountsApi.md#pOSTGenerateBillingDocuments) | **POST** /v1/accounts/{id}/billing-documents/generate | Generate billing documents by account
*AccountsApi* | [**pUTAccount**](docs/AccountsApi.md#pUTAccount) | **PUT** /v1/accounts/{account-key} | Update account
*ActionsApi* | [**actionPOSTamend**](docs/ActionsApi.md#actionPOSTamend) | **POST** /v1/action/amend | Amend
*ActionsApi* | [**actionPOSTcreate**](docs/ActionsApi.md#actionPOSTcreate) | **POST** /v1/action/create | Create
*ActionsApi* | [**actionPOSTdelete**](docs/ActionsApi.md#actionPOSTdelete) | **POST** /v1/action/delete | Delete
*ActionsApi* | [**actionPOSTexecute**](docs/ActionsApi.md#actionPOSTexecute) | **POST** /v1/action/execute | Execute
*ActionsApi* | [**actionPOSTgenerate**](docs/ActionsApi.md#actionPOSTgenerate) | **POST** /v1/action/generate | Generate
*ActionsApi* | [**actionPOSTquery**](docs/ActionsApi.md#actionPOSTquery) | **POST** /v1/action/query | Query
*ActionsApi* | [**actionPOSTqueryMore**](docs/ActionsApi.md#actionPOSTqueryMore) | **POST** /v1/action/queryMore | QueryMore
*ActionsApi* | [**actionPOSTsubscribe**](docs/ActionsApi.md#actionPOSTsubscribe) | **POST** /v1/action/subscribe | Subscribe
*ActionsApi* | [**actionPOSTupdate**](docs/ActionsApi.md#actionPOSTupdate) | **POST** /v1/action/update | Update
*AmendmentsApi* | [**gETAmendmentsByKey**](docs/AmendmentsApi.md#gETAmendmentsByKey) | **GET** /v1/amendments/{amendment-key} | Get amendments by key
*AmendmentsApi* | [**gETAmendmentsBySubscriptionID**](docs/AmendmentsApi.md#gETAmendmentsBySubscriptionID) | **GET** /v1/amendments/subscriptions/{subscription-id} | Get amendments by subscription ID
*AmendmentsApi* | [**objectDELETEAmendment**](docs/AmendmentsApi.md#objectDELETEAmendment) | **DELETE** /v1/object/amendment/{id} | CRUD: Delete amendment
*AmendmentsApi* | [**objectGETAmendment**](docs/AmendmentsApi.md#objectGETAmendment) | **GET** /v1/object/amendment/{id} | CRUD: Get amendment
*AmendmentsApi* | [**objectPUTAmendment**](docs/AmendmentsApi.md#objectPUTAmendment) | **PUT** /v1/object/amendment/{id} | CRUD: Update amendment
*AttachmentsApi* | [**dELETEAttachments**](docs/AttachmentsApi.md#dELETEAttachments) | **DELETE** /v1/attachments/{attachment-id} | Delete attachments
*AttachmentsApi* | [**gETAttachments**](docs/AttachmentsApi.md#gETAttachments) | **GET** /v1/attachments/{attachment-id} | View attachments
*AttachmentsApi* | [**gETAttachmentsList**](docs/AttachmentsApi.md#gETAttachmentsList) | **GET** /v1/attachments/{object-type}/{object-key} | View attachments list
*AttachmentsApi* | [**pOSTAttachments**](docs/AttachmentsApi.md#pOSTAttachments) | **POST** /v1/attachments | Add attachments
*AttachmentsApi* | [**pUTAttachments**](docs/AttachmentsApi.md#pUTAttachments) | **PUT** /v1/attachments/{attachment-id} | Edit attachments
*BillRunApi* | [**objectDELETEBillRun**](docs/BillRunApi.md#objectDELETEBillRun) | **DELETE** /v1/object/bill-run/{id} | CRUD: Delete Bill Run
*BillRunApi* | [**objectGETBillRun**](docs/BillRunApi.md#objectGETBillRun) | **GET** /v1/object/bill-run/{id} | CRUD: Retrieve Bill Run
*BillRunApi* | [**objectPOSTBillRun**](docs/BillRunApi.md#objectPOSTBillRun) | **POST** /v1/object/bill-run | CRUD: Create Bill Run
*BillRunApi* | [**objectPUTBillRun**](docs/BillRunApi.md#objectPUTBillRun) | **PUT** /v1/object/bill-run/{id} | CRUD: Post or Cancel Bill Run
*BillRunApi* | [**pOSTEmailBillingDocumentsfromBillRun**](docs/BillRunApi.md#pOSTEmailBillingDocumentsfromBillRun) | **POST** /v1/bill-runs/{billRunId}/emails | Email billing documents generated from bill run
*BillingDocumentsApi* | [**gETBillingDocuments**](docs/BillingDocumentsApi.md#gETBillingDocuments) | **GET** /v1/billing-documents | Get billing documents
*BillingPreviewRunApi* | [**gETBillingPreviewRun**](docs/BillingPreviewRunApi.md#gETBillingPreviewRun) | **GET** /v1/billing-preview-runs/{billingPreviewRunId} | Get Billing Preview Run
*BillingPreviewRunApi* | [**pOSTBillingPreviewRun**](docs/BillingPreviewRunApi.md#pOSTBillingPreviewRun) | **POST** /v1/billing-preview-runs | Create Billing Preview Run
*CatalogApi* | [**gETCatalog**](docs/CatalogApi.md#gETCatalog) | **GET** /v1/catalog/products | Get product catalog
*CatalogApi* | [**gETProduct**](docs/CatalogApi.md#gETProduct) | **GET** /v1/catalog/product/{product-id} | Get product
*CatalogApi* | [**pOSTCatalog**](docs/CatalogApi.md#pOSTCatalog) | **POST** /v1/catalog/products/{product-id}/share | Multi-entity: Share a product with an Entity
*ChargeRevenueSummariesApi* | [**gETCRSByCRSNumber**](docs/ChargeRevenueSummariesApi.md#gETCRSByCRSNumber) | **GET** /v1/charge-revenue-summaries/{crs-number} | Get charge summary details by CRS number
*ChargeRevenueSummariesApi* | [**gETCRSByChargeID**](docs/ChargeRevenueSummariesApi.md#gETCRSByChargeID) | **GET** /v1/charge-revenue-summaries/subscription-charges/{charge-key} | Get charge summary details by charge ID
*CommunicationProfilesApi* | [**objectGETCommunicationProfile**](docs/CommunicationProfilesApi.md#objectGETCommunicationProfile) | **GET** /v1/object/communication-profile/{id} | CRUD: Retrieve CommunicationProfile
*ConnectionsApi* | [**pOSTConnections**](docs/ConnectionsApi.md#pOSTConnections) | **POST** /v1/connections | Establish connection to Zuora REST API service
*ContactsApi* | [**objectDELETEContact**](docs/ContactsApi.md#objectDELETEContact) | **DELETE** /v1/object/contact/{id} | CRUD: Delete Contact
*ContactsApi* | [**objectGETContact**](docs/ContactsApi.md#objectGETContact) | **GET** /v1/object/contact/{id} | CRUD: Retrieve Contact
*ContactsApi* | [**objectPOSTContact**](docs/ContactsApi.md#objectPOSTContact) | **POST** /v1/object/contact | CRUD: Create Contact
*ContactsApi* | [**objectPUTContact**](docs/ContactsApi.md#objectPUTContact) | **PUT** /v1/object/contact/{id} | CRUD: Update Contact
*CreditBalanceAdjustmentsApi* | [**objectGETCreditBalanceAdjustment**](docs/CreditBalanceAdjustmentsApi.md#objectGETCreditBalanceAdjustment) | **GET** /v1/object/credit-balance-adjustment/{id} | CRUD: Retrieve CreditBalanceAdjustment
*CreditMemosApi* | [**dELETECreditMemo**](docs/CreditMemosApi.md#dELETECreditMemo) | **DELETE** /v1/creditmemos/{creditMemoId} | Delete credit memo
*CreditMemosApi* | [**gETBreakdownCreditMemoByOrder**](docs/CreditMemosApi.md#gETBreakdownCreditMemoByOrder) | **GET** /v1/creditmemos/{creditMemoNumber}/amountBreakdownByOrder | Get breakdown of credit memo by order
*CreditMemosApi* | [**gETCreditMemo**](docs/CreditMemosApi.md#gETCreditMemo) | **GET** /v1/creditmemos/{creditMemoId} | Get credit memo
*CreditMemosApi* | [**gETCreditMemoItem**](docs/CreditMemosApi.md#gETCreditMemoItem) | **GET** /v1/creditmemos/{creditMemoId}/items/{cmitemid} | Get credit memo item
*CreditMemosApi* | [**gETCreditMemoItemPart**](docs/CreditMemosApi.md#gETCreditMemoItemPart) | **GET** /v1/creditmemos/{creditMemoId}/parts/{partid}/itemparts/{itempartid} | Get credit memo part item
*CreditMemosApi* | [**gETCreditMemoItemParts**](docs/CreditMemosApi.md#gETCreditMemoItemParts) | **GET** /v1/creditmemos/{creditMemoId}/parts/{partid}/itemparts | Get credit memo part items
*CreditMemosApi* | [**gETCreditMemoItems**](docs/CreditMemosApi.md#gETCreditMemoItems) | **GET** /v1/creditmemos/{creditMemoId}/items | Get credit memo items
*CreditMemosApi* | [**gETCreditMemoPart**](docs/CreditMemosApi.md#gETCreditMemoPart) | **GET** /v1/creditmemos/{creditMemoId}/parts/{partid} | Get credit memo part
*CreditMemosApi* | [**gETCreditMemoParts**](docs/CreditMemosApi.md#gETCreditMemoParts) | **GET** /v1/creditmemos/{creditMemoId}/parts | Get credit memo parts
*CreditMemosApi* | [**gETCreditMemos**](docs/CreditMemosApi.md#gETCreditMemos) | **GET** /v1/creditmemos | Get credit memos
*CreditMemosApi* | [**pOSTCMTaxationItems**](docs/CreditMemosApi.md#pOSTCMTaxationItems) | **POST** /v1/creditmemos/{creditMemoId}/taxationitems | Create taxation items for credit memo
*CreditMemosApi* | [**pOSTCreditMemoFromPrpc**](docs/CreditMemosApi.md#pOSTCreditMemoFromPrpc) | **POST** /v1/creditmemos | Create credit memo from charge
*CreditMemosApi* | [**pOSTCreditMemoPDF**](docs/CreditMemosApi.md#pOSTCreditMemoPDF) | **POST** /v1/creditmemos/{creditMemoId}/pdfs | Create credit memo PDF
*CreditMemosApi* | [**pOSTEmailCreditMemo**](docs/CreditMemosApi.md#pOSTEmailCreditMemo) | **POST** /v1/creditmemos/{creditMemoId}/emails | Email credit memo
*CreditMemosApi* | [**pOSTRefundCreditMemo**](docs/CreditMemosApi.md#pOSTRefundCreditMemo) | **POST** /v1/creditmemos/{creditmemoId}/refunds | Refund credit memo
*CreditMemosApi* | [**pOSTRequestBreakdownCreditMemoItemsByOrder**](docs/CreditMemosApi.md#pOSTRequestBreakdownCreditMemoItemsByOrder) | **POST** /v1/creditmemos/items/amountBreakdownByOrder | Request breakdown of credit memo items by order
*CreditMemosApi* | [**pUTApplyCreditMemo**](docs/CreditMemosApi.md#pUTApplyCreditMemo) | **PUT** /v1/creditmemos/{creditMemoId}/apply | Apply credit memo
*CreditMemosApi* | [**pUTCancelCreditMemo**](docs/CreditMemosApi.md#pUTCancelCreditMemo) | **PUT** /v1/creditmemos/{creditMemoId}/cancel | Cancel credit memo
*CreditMemosApi* | [**pUTPostCreditMemo**](docs/CreditMemosApi.md#pUTPostCreditMemo) | **PUT** /v1/creditmemos/{creditMemoId}/post | Post credit memo
*CreditMemosApi* | [**pUTUnapplyCreditMemo**](docs/CreditMemosApi.md#pUTUnapplyCreditMemo) | **PUT** /v1/creditmemos/{creditMemoId}/unapply | Unapply credit memo
*CreditMemosApi* | [**pUTUnpostCreditMemo**](docs/CreditMemosApi.md#pUTUnpostCreditMemo) | **PUT** /v1/creditmemos/{creditMemoId}/unpost | Unpost credit memo
*CreditMemosApi* | [**pUTUpdateCreditMemo**](docs/CreditMemosApi.md#pUTUpdateCreditMemo) | **PUT** /v1/creditmemos/{creditMemoId} | Update credit memo
*CustomExchangeRatesApi* | [**gETCustomExchangeRates**](docs/CustomExchangeRatesApi.md#gETCustomExchangeRates) | **GET** /v1/custom-exchange-rates/{currency} | Get custom foreign currency exchange rates
*DebitMemosApi* | [**dELETEDebitMemo**](docs/DebitMemosApi.md#dELETEDebitMemo) | **DELETE** /v1/debitmemos/{debitMemoId} | Delete debit memo
*DebitMemosApi* | [**gETDebitMemo**](docs/DebitMemosApi.md#gETDebitMemo) | **GET** /v1/debitmemos/{debitMemoId} | Get debit memo
*DebitMemosApi* | [**gETDebitMemoApplicationParts**](docs/DebitMemosApi.md#gETDebitMemoApplicationParts) | **GET** /v1/debitmemos/{debitMemoId}/application-parts | Get debit memo application parts
*DebitMemosApi* | [**gETDebitMemoItem**](docs/DebitMemosApi.md#gETDebitMemoItem) | **GET** /v1/debitmemos/{debitMemoId}/items/{dmitemid} | Get debit memo item
*DebitMemosApi* | [**gETDebitMemoItems**](docs/DebitMemosApi.md#gETDebitMemoItems) | **GET** /v1/debitmemos/{debitMemoId}/items | Get debit memo items
*DebitMemosApi* | [**gETDebitMemos**](docs/DebitMemosApi.md#gETDebitMemos) | **GET** /v1/debitmemos | Get debit memos
*DebitMemosApi* | [**pOSTDMTaxationItems**](docs/DebitMemosApi.md#pOSTDMTaxationItems) | **POST** /v1/debitmemos/{debitMemoId}/taxationitems | Create taxation items for debit memo
*DebitMemosApi* | [**pOSTDebitMemoFromPrpc**](docs/DebitMemosApi.md#pOSTDebitMemoFromPrpc) | **POST** /v1/debitmemos | Create debit memo from charge
*DebitMemosApi* | [**pOSTDebitMemoPDF**](docs/DebitMemosApi.md#pOSTDebitMemoPDF) | **POST** /v1/debitmemos/{debitMemoId}/pdfs | Create debit memo PDF
*DebitMemosApi* | [**pOSTEmailDebitMemo**](docs/DebitMemosApi.md#pOSTEmailDebitMemo) | **POST** /v1/debitmemos/{debitMemoId}/emails | Email debit memo
*DebitMemosApi* | [**pUTBatchUpdateDebitMemos**](docs/DebitMemosApi.md#pUTBatchUpdateDebitMemos) | **PUT** /v1/debitmemos | Update debit memos
*DebitMemosApi* | [**pUTCancelDebitMemo**](docs/DebitMemosApi.md#pUTCancelDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId}/cancel | Cancel debit memo
*DebitMemosApi* | [**pUTDebitMemo**](docs/DebitMemosApi.md#pUTDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId} | Update debit memo
*DebitMemosApi* | [**pUTPostDebitMemo**](docs/DebitMemosApi.md#pUTPostDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId}/post | Post debit memo
*DebitMemosApi* | [**pUTUnpostDebitMemo**](docs/DebitMemosApi.md#pUTUnpostDebitMemo) | **PUT** /v1/debitmemos/{debitMemoId}/unpost | Unpost debit memo
*DescribeApi* | [**gETDescribe**](docs/DescribeApi.md#gETDescribe) | **GET** /v1/describe/{object} | Describe object
*DocumentPropertiesApi* | [**dELETEDocumentProperties**](docs/DocumentPropertiesApi.md#dELETEDocumentProperties) | **DELETE** /v1/document-properties/{documentPropertiesId} | Delete document properties
*DocumentPropertiesApi* | [**gETDocumentProperies**](docs/DocumentPropertiesApi.md#gETDocumentProperies) | **GET** /v1/document-properties/{documentType}/{documentId} | Get document properties
*DocumentPropertiesApi* | [**pOSTDocumentProperties**](docs/DocumentPropertiesApi.md#pOSTDocumentProperties) | **POST** /v1/document-properties | Create document properties
*DocumentPropertiesApi* | [**pUTDocumentProperties**](docs/DocumentPropertiesApi.md#pUTDocumentProperties) | **PUT** /v1/document-properties/{documentPropertiesId} | Update document properties
*EntitiesApi* | [**dELETEEntities**](docs/EntitiesApi.md#dELETEEntities) | **DELETE** /v1/entities/{id} | Multi-entity: Delete entity
*EntitiesApi* | [**gETEntities**](docs/EntitiesApi.md#gETEntities) | **GET** /v1/entities | Multi-entity: Get entities
*EntitiesApi* | [**gETEntityById**](docs/EntitiesApi.md#gETEntityById) | **GET** /v1/entities/{id} | Multi-entity: Get entity by Id
*EntitiesApi* | [**pOSTEntities**](docs/EntitiesApi.md#pOSTEntities) | **POST** /v1/entities | Multi-entity: Create entity
*EntitiesApi* | [**pUTEntities**](docs/EntitiesApi.md#pUTEntities) | **PUT** /v1/entities/{id} | Multi-entity: Update entity
*EntitiesApi* | [**pUTProvisionEntity**](docs/EntitiesApi.md#pUTProvisionEntity) | **PUT** /v1/entities/{id}/provision | Multi-entity: Provision entity
*EntityConnectionsApi* | [**gETEntityConnections**](docs/EntityConnectionsApi.md#gETEntityConnections) | **GET** /v1/entity-connections | Multi-entity: Get connections
*EntityConnectionsApi* | [**pOSTEntityConnections**](docs/EntityConnectionsApi.md#pOSTEntityConnections) | **POST** /v1/entity-connections | Multi-entity: Initiate connection
*EntityConnectionsApi* | [**pUTEntityConnectionsAccept**](docs/EntityConnectionsApi.md#pUTEntityConnectionsAccept) | **PUT** /v1/entity-connections/{connection-id}/accept | Multi-entity: Accept connection
*EntityConnectionsApi* | [**pUTEntityConnectionsDeny**](docs/EntityConnectionsApi.md#pUTEntityConnectionsDeny) | **PUT** /v1/entity-connections/{connection-id}/deny | Multi-entity: Deny connection
*EntityConnectionsApi* | [**pUTEntityConnectionsDisconnect**](docs/EntityConnectionsApi.md#pUTEntityConnectionsDisconnect) | **PUT** /v1/entity-connections/{connection-id}/disconnect | Multi-entity: Disconnect connection
*EventTriggersApi* | [**dELETEEventTrigger**](docs/EventTriggersApi.md#dELETEEventTrigger) | **DELETE** /events/event-triggers/{id} | Remove an event trigger
*EventTriggersApi* | [**gETEventTrigger**](docs/EventTriggersApi.md#gETEventTrigger) | **GET** /events/event-triggers/{id} | Get an event trigger by ID
*EventTriggersApi* | [**gETEventTriggers**](docs/EventTriggersApi.md#gETEventTriggers) | **GET** /events/event-triggers | Query event triggers
*EventTriggersApi* | [**pOSTEventTrigger**](docs/EventTriggersApi.md#pOSTEventTrigger) | **POST** /events/event-triggers | Create an event trigger
*EventTriggersApi* | [**pUTEventTrigger**](docs/EventTriggersApi.md#pUTEventTrigger) | **PUT** /events/event-triggers/{id} | Update an event trigger
*ExportsApi* | [**objectGETExport**](docs/ExportsApi.md#objectGETExport) | **GET** /v1/object/export/{id} | CRUD: Retrieve Export
*ExportsApi* | [**objectPOSTExport**](docs/ExportsApi.md#objectPOSTExport) | **POST** /v1/object/export | CRUD: Create Export
*FeaturesApi* | [**objectDELETEFeature**](docs/FeaturesApi.md#objectDELETEFeature) | **DELETE** /v1/object/feature/{id} | CRUD: Delete Feature
*FeaturesApi* | [**objectGETFeature**](docs/FeaturesApi.md#objectGETFeature) | **GET** /v1/object/feature/{id} | CRUD: Retrieve Feature
*GetFilesApi* | [**gETFiles**](docs/GetFilesApi.md#gETFiles) | **GET** /v1/files/{file-id} | Get files
*HmacSignaturesApi* | [**pOSTHMACSignatures**](docs/HmacSignaturesApi.md#pOSTHMACSignatures) | **POST** /v1/hmac-signatures | Return HMAC signatures
*HostedPagesApi* | [**getHostedPages**](docs/HostedPagesApi.md#getHostedPages) | **GET** /v1/hostedpages | Return hosted pages
*ImportsApi* | [**objectGETImport**](docs/ImportsApi.md#objectGETImport) | **GET** /v1/object/import/{id} | CRUD: Retrieve Import
*ImportsApi* | [**objectPOSTImport**](docs/ImportsApi.md#objectPOSTImport) | **POST** /v1/object/import | CRUD: Create Import
*InvoiceAdjustmentsApi* | [**objectDELETEInvoiceAdjustment**](docs/InvoiceAdjustmentsApi.md#objectDELETEInvoiceAdjustment) | **DELETE** /v1/object/invoice-adjustment/{id} | CRUD: Delete InvoiceAdjustment
*InvoiceAdjustmentsApi* | [**objectGETInvoiceAdjustment**](docs/InvoiceAdjustmentsApi.md#objectGETInvoiceAdjustment) | **GET** /v1/object/invoice-adjustment/{id} | CRUD: Retrieve InvoiceAdjustment
*InvoiceAdjustmentsApi* | [**objectPOSTInvoiceAdjustment**](docs/InvoiceAdjustmentsApi.md#objectPOSTInvoiceAdjustment) | **POST** /v1/object/invoice-adjustment | CRUD: Create InvoiceAdjustment
*InvoiceAdjustmentsApi* | [**objectPUTInvoiceAdjustment**](docs/InvoiceAdjustmentsApi.md#objectPUTInvoiceAdjustment) | **PUT** /v1/object/invoice-adjustment/{id} | CRUD: Update InvoiceAdjustment
*InvoiceItemAdjustmentsApi* | [**objectDELETEInvoiceItemAdjustment**](docs/InvoiceItemAdjustmentsApi.md#objectDELETEInvoiceItemAdjustment) | **DELETE** /v1/object/invoice-item-adjustment/{id} | CRUD: Delete InvoiceItemAdjustment
*InvoiceItemAdjustmentsApi* | [**objectGETInvoiceItemAdjustment**](docs/InvoiceItemAdjustmentsApi.md#objectGETInvoiceItemAdjustment) | **GET** /v1/object/invoice-item-adjustment/{id} | CRUD: Retrieve InvoiceItemAdjustment
*InvoiceItemsApi* | [**objectGETInvoiceItem**](docs/InvoiceItemsApi.md#objectGETInvoiceItem) | **GET** /v1/object/invoice-item/{id} | CRUD: Retrieve InvoiceItem
*InvoicePaymentsApi* | [**objectGETInvoicePayment**](docs/InvoicePaymentsApi.md#objectGETInvoicePayment) | **GET** /v1/object/invoice-payment/{id} | CRUD: Retrieve InvoicePayment
*InvoicePaymentsApi* | [**objectPOSTInvoicePayment**](docs/InvoicePaymentsApi.md#objectPOSTInvoicePayment) | **POST** /v1/object/invoice-payment | CRUD: Create InvoicePayment
*InvoicePaymentsApi* | [**objectPUTInvoicePayment**](docs/InvoicePaymentsApi.md#objectPUTInvoicePayment) | **PUT** /v1/object/invoice-payment/{id} | CRUD: Update InvoicePayment
*InvoiceSplitItemsApi* | [**objectGETInvoiceSplitItem**](docs/InvoiceSplitItemsApi.md#objectGETInvoiceSplitItem) | **GET** /v1/object/invoice-split-item/{id} | CRUD: Retrieve InvoiceSplitItem
*InvoiceSplitsApi* | [**objectGETInvoiceSplit**](docs/InvoiceSplitsApi.md#objectGETInvoiceSplit) | **GET** /v1/object/invoice-split/{id} | CRUD: Retrieve InvoiceSplit
*InvoicesApi* | [**gETInvoiceApplicationParts**](docs/InvoicesApi.md#gETInvoiceApplicationParts) | **GET** /v1/invoices/{invoiceId}/application-parts | Get invoice application parts
*InvoicesApi* | [**gETInvoiceFiles**](docs/InvoicesApi.md#gETInvoiceFiles) | **GET** /v1/invoices/{invoice-id}/files | Get invoice files
*InvoicesApi* | [**gETInvoiceItems**](docs/InvoicesApi.md#gETInvoiceItems) | **GET** /v1/invoices/{invoice-id}/items | Get invoice items
*InvoicesApi* | [**objectDELETEInvoice**](docs/InvoicesApi.md#objectDELETEInvoice) | **DELETE** /v1/object/invoice/{id} | CRUD: Delete Invoice
*InvoicesApi* | [**objectGETInvoice**](docs/InvoicesApi.md#objectGETInvoice) | **GET** /v1/object/invoice/{id} | CRUD: Retrieve Invoice
*InvoicesApi* | [**objectPUTInvoice**](docs/InvoicesApi.md#objectPUTInvoice) | **PUT** /v1/object/invoice/{id} | CRUD: Update Invoice
*InvoicesApi* | [**pOSTCreditMemoFromInvoice**](docs/InvoicesApi.md#pOSTCreditMemoFromInvoice) | **POST** /v1/invoices/{invoiceId}/creditmemos | Create credit memo from invoice
*InvoicesApi* | [**pOSTDebitMemoFromInvoice**](docs/InvoicesApi.md#pOSTDebitMemoFromInvoice) | **POST** /v1/invoices/{invoiceId}/debitmemos | Create debit memo from invoice
*InvoicesApi* | [**pOSTEmailInvoice**](docs/InvoicesApi.md#pOSTEmailInvoice) | **POST** /v1/invoices/{invoiceId}/emails | Email invoice
*InvoicesApi* | [**pUTBatchUpdateInvoices**](docs/InvoicesApi.md#pUTBatchUpdateInvoices) | **PUT** /v1/invoices | Update invoices
*InvoicesApi* | [**pUTReverseInvoice**](docs/InvoicesApi.md#pUTReverseInvoice) | **PUT** /v1/invoices/{invoiceId}/reverse | Reverse invoice
*InvoicesApi* | [**pUTUpdateInvoice**](docs/InvoicesApi.md#pUTUpdateInvoice) | **PUT** /v1/invoices/{invoiceId} | Update invoice
*InvoicesApi* | [**pUTWriteOffInvoice**](docs/InvoicesApi.md#pUTWriteOffInvoice) | **PUT** /v1/invoices/{invoiceId}/write-off | Write off invoice
*JournalRunsApi* | [**dELETEJournalRun**](docs/JournalRunsApi.md#dELETEJournalRun) | **DELETE** /v1/journal-runs/{jr-number} | Delete journal run
*JournalRunsApi* | [**gETJournalRun**](docs/JournalRunsApi.md#gETJournalRun) | **GET** /v1/journal-runs/{jr-number} | Get journal run
*JournalRunsApi* | [**pOSTJournalRun**](docs/JournalRunsApi.md#pOSTJournalRun) | **POST** /v1/journal-runs | Create journal run
*JournalRunsApi* | [**pUTJournalRun**](docs/JournalRunsApi.md#pUTJournalRun) | **PUT** /v1/journal-runs/{jr-number}/cancel | Cancel journal run
*MassUpdaterApi* | [**gETMassUpdater**](docs/MassUpdaterApi.md#gETMassUpdater) | **GET** /v1/bulk/{bulk-key} | Get mass action result
*MassUpdaterApi* | [**pOSTMassUpdater**](docs/MassUpdaterApi.md#pOSTMassUpdater) | **POST** /v1/bulk | Perform mass action
*MassUpdaterApi* | [**pUTMassUpdater**](docs/MassUpdaterApi.md#pUTMassUpdater) | **PUT** /v1/bulk/{bulk-key}/stop | Stop mass action
*NotificationsApi* | [**dELETEDeleteEmailTemplate**](docs/NotificationsApi.md#dELETEDeleteEmailTemplate) | **DELETE** /notifications/email-templates/{id} | Delete an email template
*NotificationsApi* | [**dELETEDeleteNotificationDefinition**](docs/NotificationsApi.md#dELETEDeleteNotificationDefinition) | **DELETE** /notifications/notification-definitions/{id} | Delete a notification definition
*NotificationsApi* | [**gETCalloutHistory**](docs/NotificationsApi.md#gETCalloutHistory) | **GET** /v1/notification-history/callout | Get callout notification histories
*NotificationsApi* | [**gETEmailHistory**](docs/NotificationsApi.md#gETEmailHistory) | **GET** /v1/notification-history/email | Get email notification histories
*NotificationsApi* | [**gETGetEmailTemplate**](docs/NotificationsApi.md#gETGetEmailTemplate) | **GET** /notifications/email-templates/{id} | Get an email template
*NotificationsApi* | [**gETGetNotificationDefinition**](docs/NotificationsApi.md#gETGetNotificationDefinition) | **GET** /notifications/notification-definitions/{id} | Get a notification definition
*NotificationsApi* | [**gETQueryEmailTemplates**](docs/NotificationsApi.md#gETQueryEmailTemplates) | **GET** /notifications/email-templates | Query email templates
*NotificationsApi* | [**gETQueryNotificationDefinitions**](docs/NotificationsApi.md#gETQueryNotificationDefinitions) | **GET** /notifications/notification-definitions | Query notification definitions
*NotificationsApi* | [**pOSTCreateEmailTemplate**](docs/NotificationsApi.md#pOSTCreateEmailTemplate) | **POST** /notifications/email-templates | Create an email template
*NotificationsApi* | [**pOSTCreateNotificationDefinition**](docs/NotificationsApi.md#pOSTCreateNotificationDefinition) | **POST** /notifications/notification-definitions | Create a notification definition
*NotificationsApi* | [**pUTUpdateEmailTemplate**](docs/NotificationsApi.md#pUTUpdateEmailTemplate) | **PUT** /notifications/email-templates/{id} | Update an email template
*NotificationsApi* | [**pUTUpdateNotificationDefinition**](docs/NotificationsApi.md#pUTUpdateNotificationDefinition) | **PUT** /notifications/notification-definitions/{id} | Update a notification definition
*OAuthApi* | [**createToken**](docs/OAuthApi.md#createToken) | **POST** /oauth/token | Generate an OAuth token
*OperationsApi* | [**pOSTBillingPreview**](docs/OperationsApi.md#pOSTBillingPreview) | **POST** /v1/operations/billing-preview | Create billing preview
*OperationsApi* | [**pOSTTransactionInvoicePayment**](docs/OperationsApi.md#pOSTTransactionInvoicePayment) | **POST** /v1/operations/invoice-collect | Invoice and collect
*OrdersApi* | [**dELETEOrder**](docs/OrdersApi.md#dELETEOrder) | **DELETE** /v1/orders/{orderNumber} | Delete order
*OrdersApi* | [**gETAllOrders**](docs/OrdersApi.md#gETAllOrders) | **GET** /v1/orders | Get all orders
*OrdersApi* | [**gETBreakdownInvoiceByOrder**](docs/OrdersApi.md#gETBreakdownInvoiceByOrder) | **GET** /v1/invoices/{invoiceNumber}/amountBreakdownByOrder | Get breakdown of invoice by order
*OrdersApi* | [**gETOrder**](docs/OrdersApi.md#gETOrder) | **GET** /v1/orders/{orderNumber} | Get an order
*OrdersApi* | [**gETOrderBillingInfo**](docs/OrdersApi.md#gETOrderBillingInfo) | **GET** /v1/orders/{orderNumber}/billingInfo | Get billing information for order
*OrdersApi* | [**gETOrderMetricsforEvergreenSubscription**](docs/OrdersApi.md#gETOrderMetricsforEvergreenSubscription) | **GET** /v1/orders/{orderNumber}/evergreenMetrics/{subscriptionNumber} | Get order metrics for evergreen subscription
*OrdersApi* | [**gETOrderRatedResult**](docs/OrdersApi.md#gETOrderRatedResult) | **GET** /v1/orders/{orderNumber}/ratedResults | Get rated result for order
*OrdersApi* | [**gETOrdersByInvoiceOwner**](docs/OrdersApi.md#gETOrdersByInvoiceOwner) | **GET** /v1/orders/invoiceOwner/{accountNumber} | Get orders by invoice owner
*OrdersApi* | [**gETOrdersBySubscriptionNumber**](docs/OrdersApi.md#gETOrdersBySubscriptionNumber) | **GET** /v1/orders/subscription/{subscriptionNumber} | Get orders by subscription number
*OrdersApi* | [**gETOrdersBySubscriptionOwner**](docs/OrdersApi.md#gETOrdersBySubscriptionOwner) | **GET** /v1/orders/subscriptionOwner/{accountNumber} | Get orders by subscription owner
*OrdersApi* | [**gETSubscriptionTermInfo**](docs/OrdersApi.md#gETSubscriptionTermInfo) | **GET** /v1/orders/term/{subscriptionNumber} | Get term information for subscription
*OrdersApi* | [**pOSTOrder**](docs/OrdersApi.md#pOSTOrder) | **POST** /v1/orders | Create order
*OrdersApi* | [**pOSTPreviewOrder**](docs/OrdersApi.md#pOSTPreviewOrder) | **POST** /v1/orders/preview | Preview order
*OrdersApi* | [**pOSTRequestBreakdownInvoiceItemsByOrder**](docs/OrdersApi.md#pOSTRequestBreakdownInvoiceItemsByOrder) | **POST** /v1/invoices/items/amountBreakdownByOrder | Request breakdown of invoice items by order
*OrdersApi* | [**pUTOrderTriggerDates**](docs/OrdersApi.md#pUTOrderTriggerDates) | **PUT** /v1/orders/{orderNumber}/triggerDates | Update order action trigger dates
*OrdersApi* | [**pUTUpdateOrderCustomFields**](docs/OrdersApi.md#pUTUpdateOrderCustomFields) | **PUT** /v1/orders/{orderNumber}/customFields | Update order custom fields
*OrdersApi* | [**pUTUpdateSubscriptionCustomFields**](docs/OrdersApi.md#pUTUpdateSubscriptionCustomFields) | **PUT** /v1/subscriptions/{subscriptionNumber}/customFields | Update subscription custom fields
*PaymentGatewaysApi* | [**gETPaymentgateways**](docs/PaymentGatewaysApi.md#gETPaymentgateways) | **GET** /v1/paymentgateways | Get payment gateways
*PaymentMethodSnapshotsApi* | [**objectDELETEPaymentMethodSnapshot**](docs/PaymentMethodSnapshotsApi.md#objectDELETEPaymentMethodSnapshot) | **DELETE** /v1/object/payment-method-snapshot/{id} | CRUD: Delete PaymentMethodSnapshot
*PaymentMethodSnapshotsApi* | [**objectGETPaymentMethodSnapshot**](docs/PaymentMethodSnapshotsApi.md#objectGETPaymentMethodSnapshot) | **GET** /v1/object/payment-method-snapshot/{id} | CRUD: Retrieve PaymentMethodSnapshot
*PaymentMethodTransactionLogsApi* | [**objectGETPaymentMethodTransactionLog**](docs/PaymentMethodTransactionLogsApi.md#objectGETPaymentMethodTransactionLog) | **GET** /v1/object/payment-method-transaction-log/{id} | CRUD: Retrieve PaymentMethodTransactionLog
*PaymentMethodsApi* | [**dELETEPaymentMethods**](docs/PaymentMethodsApi.md#dELETEPaymentMethods) | **DELETE** /v1/payment-methods/{payment-method-id} | Delete payment method
*PaymentMethodsApi* | [**gETPaymentMethodsCreditCard**](docs/PaymentMethodsApi.md#gETPaymentMethodsCreditCard) | **GET** /v1/payment-methods/credit-cards/accounts/{account-key} | Get credit card payment methods for account
*PaymentMethodsApi* | [**objectDELETEPaymentMethod**](docs/PaymentMethodsApi.md#objectDELETEPaymentMethod) | **DELETE** /v1/object/payment-method/{id} | CRUD: Delete payment method
*PaymentMethodsApi* | [**objectGETPaymentMethod**](docs/PaymentMethodsApi.md#objectGETPaymentMethod) | **GET** /v1/object/payment-method/{id} | CRUD: Get payment method
*PaymentMethodsApi* | [**objectPOSTPaymentMethod**](docs/PaymentMethodsApi.md#objectPOSTPaymentMethod) | **POST** /v1/object/payment-method | CRUD: Create payment method
*PaymentMethodsApi* | [**objectPUTPaymentMethod**](docs/PaymentMethodsApi.md#objectPUTPaymentMethod) | **PUT** /v1/object/payment-method/{id} | CRUD: Update payment method
*PaymentMethodsApi* | [**pOSTCancelAuthorization**](docs/PaymentMethodsApi.md#pOSTCancelAuthorization) | **POST** /v1/payment-methods/{payment-method-id}/voidAuthorize | Cancel authorization
*PaymentMethodsApi* | [**pOSTCreateAuthorization**](docs/PaymentMethodsApi.md#pOSTCreateAuthorization) | **POST** /v1/payment-methods/{payment-method-id}/authorize | Create authorization
*PaymentMethodsApi* | [**pOSTPaymentMethods**](docs/PaymentMethodsApi.md#pOSTPaymentMethods) | **POST** /v1/payment-methods | Create payment method
*PaymentMethodsApi* | [**pOSTPaymentMethodsCreditCard**](docs/PaymentMethodsApi.md#pOSTPaymentMethodsCreditCard) | **POST** /v1/payment-methods/credit-cards | Create credit card payment method
*PaymentMethodsApi* | [**pOSTPaymentMethodsDecryption**](docs/PaymentMethodsApi.md#pOSTPaymentMethodsDecryption) | **POST** /v1/payment-methods/decryption | Create Apple Pay payment method
*PaymentMethodsApi* | [**pUTPaymentMethodsCreditCard**](docs/PaymentMethodsApi.md#pUTPaymentMethodsCreditCard) | **PUT** /v1/payment-methods/credit-cards/{payment-method-id} | Update credit card payment method
*PaymentMethodsApi* | [**pUTScrubPaymentMethods**](docs/PaymentMethodsApi.md#pUTScrubPaymentMethods) | **PUT** /v1/payment-methods/{payment-method-id}/scrub | Scrub payment method
*PaymentMethodsApi* | [**pUTVerifyPaymentMethods**](docs/PaymentMethodsApi.md#pUTVerifyPaymentMethods) | **PUT** /v1/payment-methods/{payment-method-id}/verify | Verify payment method
*PaymentRunsApi* | [**dELETEPaymentRun**](docs/PaymentRunsApi.md#dELETEPaymentRun) | **DELETE** /v1/payment-runs/{paymentRunId} | Delete payment run
*PaymentRunsApi* | [**gETPaymentRun**](docs/PaymentRunsApi.md#gETPaymentRun) | **GET** /v1/payment-runs/{paymentRunId} | Get payment run
*PaymentRunsApi* | [**gETPaymentRunSummary**](docs/PaymentRunsApi.md#gETPaymentRunSummary) | **GET** /v1/payment-runs/{paymentRunId}/summary | Get payment run summary
*PaymentRunsApi* | [**gETPaymentRuns**](docs/PaymentRunsApi.md#gETPaymentRuns) | **GET** /v1/payment-runs | Get payment runs
*PaymentRunsApi* | [**pOSTPaymentRun**](docs/PaymentRunsApi.md#pOSTPaymentRun) | **POST** /v1/payment-runs | Create payment run
*PaymentRunsApi* | [**pUTPaymentRun**](docs/PaymentRunsApi.md#pUTPaymentRun) | **PUT** /v1/payment-runs/{paymentRunId} | Update payment run
*PaymentTransactionLogsApi* | [**objectGETPaymentTransactionLog**](docs/PaymentTransactionLogsApi.md#objectGETPaymentTransactionLog) | **GET** /v1/object/payment-transaction-log/{id} | CRUD: Get payment transaction log
*PaymentsApi* | [**dELETEPayment**](docs/PaymentsApi.md#dELETEPayment) | **DELETE** /v1/payments/{paymentId} | Delete payment
*PaymentsApi* | [**gETPayment**](docs/PaymentsApi.md#gETPayment) | **GET** /v1/payments/{paymentId} | Get payment
*PaymentsApi* | [**gETPaymentItemPart**](docs/PaymentsApi.md#gETPaymentItemPart) | **GET** /v1/payments/{paymentId}/parts/{partid}/itemparts/{itempartid} | Get payment part item
*PaymentsApi* | [**gETPaymentItemParts**](docs/PaymentsApi.md#gETPaymentItemParts) | **GET** /v1/payments/{paymentId}/parts/{partid}/itemparts | Get payment part items
*PaymentsApi* | [**gETPaymentPart**](docs/PaymentsApi.md#gETPaymentPart) | **GET** /v1/payments/{paymentId}/parts/{partid} | Get payment part
*PaymentsApi* | [**gETPaymentParts**](docs/PaymentsApi.md#gETPaymentParts) | **GET** /v1/payments/{paymentId}/parts | Get payment parts
*PaymentsApi* | [**gETRetrieveAllPayments**](docs/PaymentsApi.md#gETRetrieveAllPayments) | **GET** /v1/payments | Get all payments
*PaymentsApi* | [**objectDELETEPayment**](docs/PaymentsApi.md#objectDELETEPayment) | **DELETE** /v1/object/payment/{id} | CRUD: Delete payment
*PaymentsApi* | [**objectGETPayment**](docs/PaymentsApi.md#objectGETPayment) | **GET** /v1/object/payment/{id} | CRUD: Get payment
*PaymentsApi* | [**objectPOSTPayment**](docs/PaymentsApi.md#objectPOSTPayment) | **POST** /v1/object/payment | CRUD: Create payment
*PaymentsApi* | [**objectPUTPayment**](docs/PaymentsApi.md#objectPUTPayment) | **PUT** /v1/object/payment/{id} | CRUD: Update payment
*PaymentsApi* | [**pOSTCreatePayment**](docs/PaymentsApi.md#pOSTCreatePayment) | **POST** /v1/payments | Create payment
*PaymentsApi* | [**pOSTRefundPayment**](docs/PaymentsApi.md#pOSTRefundPayment) | **POST** /v1/payments/{paymentId}/refunds | Refund payment
*PaymentsApi* | [**pUTApplyPayment**](docs/PaymentsApi.md#pUTApplyPayment) | **PUT** /v1/payments/{paymentId}/apply | Apply payment
*PaymentsApi* | [**pUTCancelPayment**](docs/PaymentsApi.md#pUTCancelPayment) | **PUT** /v1/payments/{paymentId}/cancel | Cancel payment
*PaymentsApi* | [**pUTTransferPayment**](docs/PaymentsApi.md#pUTTransferPayment) | **PUT** /v1/payments/{paymentId}/transfer | Transfer payment
*PaymentsApi* | [**pUTUnapplyPayment**](docs/PaymentsApi.md#pUTUnapplyPayment) | **PUT** /v1/payments/{paymentId}/unapply | Unapply payment
*PaymentsApi* | [**pUTUpdatePayment**](docs/PaymentsApi.md#pUTUpdatePayment) | **PUT** /v1/payments/{paymentId} | Update payment
*ProductFeaturesApi* | [**objectDELETEProductFeature**](docs/ProductFeaturesApi.md#objectDELETEProductFeature) | **DELETE** /v1/object/product-feature/{id} | CRUD: Delete ProductFeature
*ProductFeaturesApi* | [**objectGETProductFeature**](docs/ProductFeaturesApi.md#objectGETProductFeature) | **GET** /v1/object/product-feature/{id} | CRUD: Retrieve ProductFeature
*ProductRatePlanChargeTiersApi* | [**objectGETProductRatePlanChargeTier**](docs/ProductRatePlanChargeTiersApi.md#objectGETProductRatePlanChargeTier) | **GET** /v1/object/product-rate-plan-charge-tier/{id} | CRUD: Retrieve ProductRatePlanChargeTier
*ProductRatePlanChargesApi* | [**objectDELETEProductRatePlanCharge**](docs/ProductRatePlanChargesApi.md#objectDELETEProductRatePlanCharge) | **DELETE** /v1/object/product-rate-plan-charge/{id} | CRUD: Delete product rate plan charge
*ProductRatePlanChargesApi* | [**objectGETProductRatePlanCharge**](docs/ProductRatePlanChargesApi.md#objectGETProductRatePlanCharge) | **GET** /v1/object/product-rate-plan-charge/{id} | CRUD: Get product rate plan charge
*ProductRatePlanChargesApi* | [**objectPOSTProductRatePlanCharge**](docs/ProductRatePlanChargesApi.md#objectPOSTProductRatePlanCharge) | **POST** /v1/object/product-rate-plan-charge | CRUD: Create product rate plan charge
*ProductRatePlanChargesApi* | [**objectPUTProductRatePlanCharge**](docs/ProductRatePlanChargesApi.md#objectPUTProductRatePlanCharge) | **PUT** /v1/object/product-rate-plan-charge/{id} | CRUD: Update product rate plan charge
*ProductRatePlansApi* | [**gETProductRatePlans**](docs/ProductRatePlansApi.md#gETProductRatePlans) | **GET** /v1/rateplan/{product_id}/productRatePlan | Get product rate plans
*ProductRatePlansApi* | [**objectDELETEProductRatePlan**](docs/ProductRatePlansApi.md#objectDELETEProductRatePlan) | **DELETE** /v1/object/product-rate-plan/{id} | CRUD: Delete ProductRatePlan
*ProductRatePlansApi* | [**objectGETProductRatePlan**](docs/ProductRatePlansApi.md#objectGETProductRatePlan) | **GET** /v1/object/product-rate-plan/{id} | CRUD: Retrieve ProductRatePlan
*ProductRatePlansApi* | [**objectPOSTProductRatePlan**](docs/ProductRatePlansApi.md#objectPOSTProductRatePlan) | **POST** /v1/object/product-rate-plan | CRUD: Create ProductRatePlan
*ProductRatePlansApi* | [**objectPUTProductRatePlan**](docs/ProductRatePlansApi.md#objectPUTProductRatePlan) | **PUT** /v1/object/product-rate-plan/{id} | CRUD: Update ProductRatePlan
*ProductsApi* | [**objectDELETEProduct**](docs/ProductsApi.md#objectDELETEProduct) | **DELETE** /v1/object/product/{id} | CRUD: Delete Product
*ProductsApi* | [**objectGETProduct**](docs/ProductsApi.md#objectGETProduct) | **GET** /v1/object/product/{id} | CRUD: Retrieve Product
*ProductsApi* | [**objectPOSTProduct**](docs/ProductsApi.md#objectPOSTProduct) | **POST** /v1/object/product | CRUD: Create Product
*ProductsApi* | [**objectPUTProduct**](docs/ProductsApi.md#objectPUTProduct) | **PUT** /v1/object/product/{id} | CRUD: Update Product
*QuotesDocumentApi* | [**pOSTQuotesDocument**](docs/QuotesDocumentApi.md#pOSTQuotesDocument) | **POST** /v1/quotes/document | Generate quotes document
*RatePlanChargeTiersApi* | [**objectGETRatePlanChargeTier**](docs/RatePlanChargeTiersApi.md#objectGETRatePlanChargeTier) | **GET** /v1/object/rate-plan-charge-tier/{id} | CRUD: Retrieve RatePlanChargeTier
*RatePlanChargesApi* | [**objectGETRatePlanCharge**](docs/RatePlanChargesApi.md#objectGETRatePlanCharge) | **GET** /v1/object/rate-plan-charge/{id} | CRUD: Retrieve RatePlanCharge
*RatePlansApi* | [**objectGETRatePlan**](docs/RatePlansApi.md#objectGETRatePlan) | **GET** /v1/object/rate-plan/{id} | CRUD: Retrieve RatePlan
*RefundInvoicePaymentsApi* | [**objectGETRefundInvoicePayment**](docs/RefundInvoicePaymentsApi.md#objectGETRefundInvoicePayment) | **GET** /v1/object/refund-invoice-payment/{id} | CRUD: Retrieve RefundInvoicePayment
*RefundTransactionLogsApi* | [**objectGETRefundTransactionLog**](docs/RefundTransactionLogsApi.md#objectGETRefundTransactionLog) | **GET** /v1/object/refund-transaction-log/{id} | CRUD: Retrieve RefundTransactionLog
*RefundsApi* | [**dELETERefund**](docs/RefundsApi.md#dELETERefund) | **DELETE** /v1/refunds/{refundId} | Delete refund
*RefundsApi* | [**gETRefund**](docs/RefundsApi.md#gETRefund) | **GET** /v1/refunds/{refundId} | Get refund
*RefundsApi* | [**gETRefundItemPart**](docs/RefundsApi.md#gETRefundItemPart) | **GET** /v1/refunds/{refundId}/parts/{refundpartid}/itemparts/{itempartid} | Get refund part item
*RefundsApi* | [**gETRefundItemParts**](docs/RefundsApi.md#gETRefundItemParts) | **GET** /v1/refunds/{refundId}/parts/{refundpartid}/itemparts | Get refund part items
*RefundsApi* | [**gETRefundPart**](docs/RefundsApi.md#gETRefundPart) | **GET** /v1/refunds/{refundId}/parts/{refundpartid} | Get refund part
*RefundsApi* | [**gETRefundParts**](docs/RefundsApi.md#gETRefundParts) | **GET** /v1/refunds/{refundId}/parts | Get refund parts
*RefundsApi* | [**gETRefunds**](docs/RefundsApi.md#gETRefunds) | **GET** /v1/refunds | Get all refunds
*RefundsApi* | [**objectDELETERefund**](docs/RefundsApi.md#objectDELETERefund) | **DELETE** /v1/object/refund/{id} | CRUD: Delete refund
*RefundsApi* | [**objectGETRefund**](docs/RefundsApi.md#objectGETRefund) | **GET** /v1/object/refund/{id} | CRUD: Get refund
*RefundsApi* | [**objectPOSTRefund**](docs/RefundsApi.md#objectPOSTRefund) | **POST** /v1/object/refund | CRUD: Create refund
*RefundsApi* | [**objectPUTRefund**](docs/RefundsApi.md#objectPUTRefund) | **PUT** /v1/object/refund/{id} | CRUD: Update refund
*RefundsApi* | [**pUTCancelRefund**](docs/RefundsApi.md#pUTCancelRefund) | **PUT** /v1/refunds/{refundId}/cancel | Cancel refund
*RefundsApi* | [**pUTUpdateRefund**](docs/RefundsApi.md#pUTUpdateRefund) | **PUT** /v1/refunds/{refundId} | Update refund
*RevenueEventsApi* | [**gETRevenueEventDetails**](docs/RevenueEventsApi.md#gETRevenueEventDetails) | **GET** /v1/revenue-events/{event-number} | Get revenue event details
*RevenueEventsApi* | [**gETRevenueEventForRevenueSchedule**](docs/RevenueEventsApi.md#gETRevenueEventForRevenueSchedule) | **GET** /v1/revenue-events/revenue-schedules/{rs-number} | Get revenue events for a revenue schedule
*RevenueItemsApi* | [**gETRevenueItemsByChargeRevenueEventNumber**](docs/RevenueItemsApi.md#gETRevenueItemsByChargeRevenueEventNumber) | **GET** /v1/revenue-items/revenue-events/{event-number} | Get revenue items by revenue event number
*RevenueItemsApi* | [**gETRevenueItemsByChargeRevenueSummaryNumber**](docs/RevenueItemsApi.md#gETRevenueItemsByChargeRevenueSummaryNumber) | **GET** /v1/revenue-items/charge-revenue-summaries/{crs-number} | Get revenue items by charge revenue summary number
*RevenueItemsApi* | [**gETRevenueItemsByRevenueSchedule**](docs/RevenueItemsApi.md#gETRevenueItemsByRevenueSchedule) | **GET** /v1/revenue-items/revenue-schedules/{rs-number} | Get revenue items by revenue schedule
*RevenueItemsApi* | [**pUTCustomFieldsonRevenueItemsByRevenueEvent**](docs/RevenueItemsApi.md#pUTCustomFieldsonRevenueItemsByRevenueEvent) | **PUT** /v1/revenue-items/revenue-events/{event-number} | Update custom fields on revenue items by revenue event number
*RevenueItemsApi* | [**pUTCustomFieldsonRevenueItemsByRevenueSchedule**](docs/RevenueItemsApi.md#pUTCustomFieldsonRevenueItemsByRevenueSchedule) | **PUT** /v1/revenue-items/revenue-schedules/{rs-number} | Update custom fields on revenue items by revenue schedule number
*RevenueRulesApi* | [**gETRevenueRecRulebyProductRatePlanCharge**](docs/RevenueRulesApi.md#gETRevenueRecRulebyProductRatePlanCharge) | **GET** /v1/revenue-recognition-rules/product-charges/{charge-key} | Get revenue recognition rule by product rate plan charge
*RevenueRulesApi* | [**gETRevenueRecRules**](docs/RevenueRulesApi.md#gETRevenueRecRules) | **GET** /v1/revenue-recognition-rules/subscription-charges/{charge-key} | Get revenue recognition rule by subscription charge
*RevenueSchedulesApi* | [**dELETERS**](docs/RevenueSchedulesApi.md#dELETERS) | **DELETE** /v1/revenue-schedules/{rs-number} | Delete revenue schedule
*RevenueSchedulesApi* | [**gETRS**](docs/RevenueSchedulesApi.md#gETRS) | **GET** /v1/revenue-schedules/{rs-number} | Get revenue schedule details
*RevenueSchedulesApi* | [**gETRSbyCreditMemoItem**](docs/RevenueSchedulesApi.md#gETRSbyCreditMemoItem) | **GET** /v1/revenue-schedules/credit-memo-items/{cmi-id} | Get revenue schedule by credit memo item ID
*RevenueSchedulesApi* | [**gETRSbyDebitMemoItem**](docs/RevenueSchedulesApi.md#gETRSbyDebitMemoItem) | **GET** /v1/revenue-schedules/debit-memo-items/{dmi-id} | Get revenue schedule by debit memo item ID
*RevenueSchedulesApi* | [**gETRSbyInvoiceItem**](docs/RevenueSchedulesApi.md#gETRSbyInvoiceItem) | **GET** /v1/revenue-schedules/invoice-items/{invoice-item-id} | Get revenue schedule by invoice item ID
*RevenueSchedulesApi* | [**gETRSbyInvoiceItemAdjustment**](docs/RevenueSchedulesApi.md#gETRSbyInvoiceItemAdjustment) | **GET** /v1/revenue-schedules/invoice-item-adjustments/{invoice-item-adj-key} | Get revenue schedule by invoice item adjustment
*RevenueSchedulesApi* | [**gETRSbyProductChargeAndBillingAccount**](docs/RevenueSchedulesApi.md#gETRSbyProductChargeAndBillingAccount) | **GET** /v1/revenue-schedules/product-charges/{charge-key}/{account-key} | Get all revenue schedules of product charge by charge ID and billing account ID
*RevenueSchedulesApi* | [**gETRSforSubscCharge**](docs/RevenueSchedulesApi.md#gETRSforSubscCharge) | **GET** /v1/revenue-schedules/subscription-charges/{charge-key} | Get revenue schedule by subscription charge
*RevenueSchedulesApi* | [**pOSTRSforCreditMemoItemDistributeByDateRange**](docs/RevenueSchedulesApi.md#pOSTRSforCreditMemoItemDistributeByDateRange) | **POST** /v1/revenue-schedules/credit-memo-items/{cmi-id}/distribute-revenue-with-date-range | Create revenue schedule for credit memo item (distribute by date range)
*RevenueSchedulesApi* | [**pOSTRSforCreditMemoItemManualDistribution**](docs/RevenueSchedulesApi.md#pOSTRSforCreditMemoItemManualDistribution) | **POST** /v1/revenue-schedules/credit-memo-items/{cmi-id} | Create revenue schedule for credit memo item (manual distribution)
*RevenueSchedulesApi* | [**pOSTRSforDebitMemoItemDistributeByDateRange**](docs/RevenueSchedulesApi.md#pOSTRSforDebitMemoItemDistributeByDateRange) | **POST** /v1/revenue-schedules/debit-memo-items/{dmi-id}/distribute-revenue-with-date-range | Create revenue schedule for debit memo item (distribute by date range)
*RevenueSchedulesApi* | [**pOSTRSforDebitMemoItemManualDistribution**](docs/RevenueSchedulesApi.md#pOSTRSforDebitMemoItemManualDistribution) | **POST** /v1/revenue-schedules/debit-memo-items/{dmi-id} | Create revenue schedule for debit memo item (manual distribution)
*RevenueSchedulesApi* | [**pOSTRSforInvoiceItemAdjustmentDistributeByDateRange**](docs/RevenueSchedulesApi.md#pOSTRSforInvoiceItemAdjustmentDistributeByDateRange) | **POST** /v1/revenue-schedules/invoice-item-adjustments/{invoice-item-adj-key}/distribute-revenue-with-date-range | Create revenue schedule for Invoice Item Adjustment (distribute by date range)
*RevenueSchedulesApi* | [**pOSTRSforInvoiceItemAdjustmentManualDistribution**](docs/RevenueSchedulesApi.md#pOSTRSforInvoiceItemAdjustmentManualDistribution) | **POST** /v1/revenue-schedules/invoice-item-adjustments/{invoice-item-adj-key} | Create revenue schedule for Invoice Item Adjustment (manual distribution)
*RevenueSchedulesApi* | [**pOSTRSforInvoiceItemDistributeByDateRange**](docs/RevenueSchedulesApi.md#pOSTRSforInvoiceItemDistributeByDateRange) | **POST** /v1/revenue-schedules/invoice-items/{invoice-item-id}/distribute-revenue-with-date-range | Create revenue schedule for Invoice Item (distribute by date range)
*RevenueSchedulesApi* | [**pOSTRSforInvoiceItemManualDistribution**](docs/RevenueSchedulesApi.md#pOSTRSforInvoiceItemManualDistribution) | **POST** /v1/revenue-schedules/invoice-items/{invoice-item-id} | Create revenue schedule for Invoice Item (manual distribution)
*RevenueSchedulesApi* | [**pOSTRSforSubscCharge**](docs/RevenueSchedulesApi.md#pOSTRSforSubscCharge) | **POST** /v1/revenue-schedules/subscription-charges/{charge-key} | Create revenue schedule on subscription charge
*RevenueSchedulesApi* | [**pUTRSBasicInfo**](docs/RevenueSchedulesApi.md#pUTRSBasicInfo) | **PUT** /v1/revenue-schedules/{rs-number}/basic-information | Update revenue schedule basic information
*RevenueSchedulesApi* | [**pUTRevenueAcrossAP**](docs/RevenueSchedulesApi.md#pUTRevenueAcrossAP) | **PUT** /v1/revenue-schedules/{rs-number}/distribute-revenue-across-accounting-periods | Distribute revenue across accounting periods
*RevenueSchedulesApi* | [**pUTRevenueByRecognitionStartandEndDates**](docs/RevenueSchedulesApi.md#pUTRevenueByRecognitionStartandEndDates) | **PUT** /v1/revenue-schedules/{rs-number}/distribute-revenue-with-date-range | Distribute revenue by recognition start and end dates
*RevenueSchedulesApi* | [**pUTRevenueSpecificDate**](docs/RevenueSchedulesApi.md#pUTRevenueSpecificDate) | **PUT** /v1/revenue-schedules/{rs-number}/distribute-revenue-on-specific-date | Distribute revenue on specific date
*RsaSignaturesApi* | [**pOSTDecryptRSASignatures**](docs/RsaSignaturesApi.md#pOSTDecryptRSASignatures) | **POST** /v1/rsa-signatures/decrypt | Decrypt RSA signature
*RsaSignaturesApi* | [**pOSTRSASignatures**](docs/RsaSignaturesApi.md#pOSTRSASignatures) | **POST** /v1/rsa-signatures | Generate RSA signature
*SettingsApi* | [**gETRevenueAutomationStartDate**](docs/SettingsApi.md#gETRevenueAutomationStartDate) | **GET** /v1/settings/finance/revenue-automation-start-date | Get the revenue automation start date
*SubscriptionProductFeaturesApi* | [**objectGETSubscriptionProductFeature**](docs/SubscriptionProductFeaturesApi.md#objectGETSubscriptionProductFeature) | **GET** /v1/object/subscription-product-feature/{id} | CRUD: Retrieve SubscriptionProductFeature
*SubscriptionsApi* | [**gETSubscriptionsByAccount**](docs/SubscriptionsApi.md#gETSubscriptionsByAccount) | **GET** /v1/subscriptions/accounts/{account-key} | Get subscriptions by account
*SubscriptionsApi* | [**gETSubscriptionsByKey**](docs/SubscriptionsApi.md#gETSubscriptionsByKey) | **GET** /v1/subscriptions/{subscription-key} | Get subscriptions by key
*SubscriptionsApi* | [**gETSubscriptionsByKeyAndVersion**](docs/SubscriptionsApi.md#gETSubscriptionsByKeyAndVersion) | **GET** /v1/subscriptions/{subscription-key}/versions/{version} | Get subscriptions by key and version
*SubscriptionsApi* | [**objectDELETESubscription**](docs/SubscriptionsApi.md#objectDELETESubscription) | **DELETE** /v1/object/subscription/{id} | CRUD: Delete Subscription
*SubscriptionsApi* | [**objectGETSubscription**](docs/SubscriptionsApi.md#objectGETSubscription) | **GET** /v1/object/subscription/{id} | CRUD: Retrieve Subscription
*SubscriptionsApi* | [**objectPUTSubscription**](docs/SubscriptionsApi.md#objectPUTSubscription) | **PUT** /v1/object/subscription/{id} | CRUD: Update Subscription
*SubscriptionsApi* | [**pOSTPreviewSubscription**](docs/SubscriptionsApi.md#pOSTPreviewSubscription) | **POST** /v1/subscriptions/preview | Preview subscription
*SubscriptionsApi* | [**pOSTSubscription**](docs/SubscriptionsApi.md#pOSTSubscription) | **POST** /v1/subscriptions | Create subscription
*SubscriptionsApi* | [**pUTCancelSubscription**](docs/SubscriptionsApi.md#pUTCancelSubscription) | **PUT** /v1/subscriptions/{subscription-key}/cancel | Cancel subscription
*SubscriptionsApi* | [**pUTRenewSubscription**](docs/SubscriptionsApi.md#pUTRenewSubscription) | **PUT** /v1/subscriptions/{subscription-key}/renew | Renew subscription
*SubscriptionsApi* | [**pUTResumeSubscription**](docs/SubscriptionsApi.md#pUTResumeSubscription) | **PUT** /v1/subscriptions/{subscription-key}/resume | Resume subscription
*SubscriptionsApi* | [**pUTSubscription**](docs/SubscriptionsApi.md#pUTSubscription) | **PUT** /v1/subscriptions/{subscription-key} | Update subscription
*SubscriptionsApi* | [**pUTSuspendSubscription**](docs/SubscriptionsApi.md#pUTSuspendSubscription) | **PUT** /v1/subscriptions/{subscription-key}/suspend | Suspend subscription
*SummaryJournalEntriesApi* | [**dELETESummaryJournalEntry**](docs/SummaryJournalEntriesApi.md#dELETESummaryJournalEntry) | **DELETE** /v1/journal-entries/{je-number} | Delete summary journal entry
*SummaryJournalEntriesApi* | [**gETAllSummaryJournalEntries**](docs/SummaryJournalEntriesApi.md#gETAllSummaryJournalEntries) | **GET** /v1/journal-entries/journal-runs/{jr-number} | Get all summary journal entries in a journal run
*SummaryJournalEntriesApi* | [**gETSummaryJournalEntry**](docs/SummaryJournalEntriesApi.md#gETSummaryJournalEntry) | **GET** /v1/journal-entries/{je-number} | Get summary journal entry
*SummaryJournalEntriesApi* | [**pOSTSummaryJournalEntry**](docs/SummaryJournalEntriesApi.md#pOSTSummaryJournalEntry) | **POST** /v1/journal-entries | Create summary journal entry
*SummaryJournalEntriesApi* | [**pUTBasicSummaryJournalEntry**](docs/SummaryJournalEntriesApi.md#pUTBasicSummaryJournalEntry) | **PUT** /v1/journal-entries/{je-number}/basic-information | Update basic information of a summary journal entry
*SummaryJournalEntriesApi* | [**pUTSummaryJournalEntry**](docs/SummaryJournalEntriesApi.md#pUTSummaryJournalEntry) | **PUT** /v1/journal-entries/{je-number}/cancel | Cancel summary journal entry
*TaxationItemsApi* | [**dELETETaxationItem**](docs/TaxationItemsApi.md#dELETETaxationItem) | **DELETE** /v1/taxationitems/{id} | Delete taxation item
*TaxationItemsApi* | [**gETTaxationItem**](docs/TaxationItemsApi.md#gETTaxationItem) | **GET** /v1/taxationitems/{id} | Get taxation item
*TaxationItemsApi* | [**objectDELETETaxationItem**](docs/TaxationItemsApi.md#objectDELETETaxationItem) | **DELETE** /v1/object/taxation-item/{id} | CRUD: Delete TaxationItem
*TaxationItemsApi* | [**objectGETTaxationItem**](docs/TaxationItemsApi.md#objectGETTaxationItem) | **GET** /v1/object/taxation-item/{id} | CRUD: Retrieve TaxationItem
*TaxationItemsApi* | [**objectPOSTTaxationItem**](docs/TaxationItemsApi.md#objectPOSTTaxationItem) | **POST** /v1/object/taxation-item | CRUD: Create TaxationItem
*TaxationItemsApi* | [**objectPUTTaxationItem**](docs/TaxationItemsApi.md#objectPUTTaxationItem) | **PUT** /v1/object/taxation-item/{id} | CRUD: Update TaxationItem
*TaxationItemsApi* | [**pUTTaxationItem**](docs/TaxationItemsApi.md#pUTTaxationItem) | **PUT** /v1/taxationitems/{id} | Update taxation item
*TransactionsApi* | [**gETTransactionInvoice**](docs/TransactionsApi.md#gETTransactionInvoice) | **GET** /v1/transactions/invoices/accounts/{account-key} | Get invoices
*TransactionsApi* | [**gETTransactionPayment**](docs/TransactionsApi.md#gETTransactionPayment) | **GET** /v1/transactions/payments/accounts/{account-key} | Get payments
*UnitOfMeasureApi* | [**objectDELETEUnitOfMeasure**](docs/UnitOfMeasureApi.md#objectDELETEUnitOfMeasure) | **DELETE** /v1/object/unit-of-measure/{id} | CRUD: Delete UnitOfMeasure
*UnitOfMeasureApi* | [**objectGETUnitOfMeasure**](docs/UnitOfMeasureApi.md#objectGETUnitOfMeasure) | **GET** /v1/object/unit-of-measure/{id} | CRUD: Retrieve UnitOfMeasure
*UnitOfMeasureApi* | [**objectPOSTUnitOfMeasure**](docs/UnitOfMeasureApi.md#objectPOSTUnitOfMeasure) | **POST** /v1/object/unit-of-measure | CRUD: Create UnitOfMeasure
*UnitOfMeasureApi* | [**objectPUTUnitOfMeasure**](docs/UnitOfMeasureApi.md#objectPUTUnitOfMeasure) | **PUT** /v1/object/unit-of-measure/{id} | CRUD: Update UnitOfMeasure
*UsageApi* | [**gETUsage**](docs/UsageApi.md#gETUsage) | **GET** /v1/usage/accounts/{account-key} | Get usage
*UsageApi* | [**objectDELETEUsage**](docs/UsageApi.md#objectDELETEUsage) | **DELETE** /v1/object/usage/{id} | CRUD: Delete Usage
*UsageApi* | [**objectGETUsage**](docs/UsageApi.md#objectGETUsage) | **GET** /v1/object/usage/{id} | CRUD: Retrieve Usage
*UsageApi* | [**objectPOSTUsage**](docs/UsageApi.md#objectPOSTUsage) | **POST** /v1/object/usage | CRUD: Create Usage
*UsageApi* | [**objectPUTUsage**](docs/UsageApi.md#objectPUTUsage) | **PUT** /v1/object/usage/{id} | CRUD: Update Usage
*UsageApi* | [**pOSTUsage**](docs/UsageApi.md#pOSTUsage) | **POST** /v1/usage | Post usage
*UsersApi* | [**gETEntitiesUserAccessible**](docs/UsersApi.md#gETEntitiesUserAccessible) | **GET** /v1/users/{username}/accessible-entities | Multi-entity: Get entities that a user can access
*UsersApi* | [**pUTAcceptUserAccess**](docs/UsersApi.md#pUTAcceptUserAccess) | **PUT** /v1/users/{username}/accept-access | Multi-entity: Accept user access
*UsersApi* | [**pUTDenyUserAccess**](docs/UsersApi.md#pUTDenyUserAccess) | **PUT** /v1/users/{username}/deny-access | Multi-entity: Deny user access
*UsersApi* | [**pUTSendUserAccessRequests**](docs/UsersApi.md#pUTSendUserAccessRequests) | **PUT** /v1/users/{username}/request-access | Multi-entity: Send user access requests
## Documentation for Models
- [AccountCreditCardHolder](docs/AccountCreditCardHolder.md)
- [AccountObjectCustomFields](docs/AccountObjectCustomFields.md)
- [AccountObjectNSFields](docs/AccountObjectNSFields.md)
- [AccountingCodeObjectCustomFields](docs/AccountingCodeObjectCustomFields.md)
- [AccountingPeriodObjectCustomFields](docs/AccountingPeriodObjectCustomFields.md)
- [ActionsErrorResponse](docs/ActionsErrorResponse.md)
- [AmendRequest](docs/AmendRequest.md)
- [AmendRequestAmendOptions](docs/AmendRequestAmendOptions.md)
- [AmendRequestPreviewOptions](docs/AmendRequestPreviewOptions.md)
- [AmendResult](docs/AmendResult.md)
- [Amendment](docs/Amendment.md)
- [AmendmentObjectCustomFields](docs/AmendmentObjectCustomFields.md)
- [AmendmentRatePlanChargeData](docs/AmendmentRatePlanChargeData.md)
- [AmendmentRatePlanChargeTier](docs/AmendmentRatePlanChargeTier.md)
- [AmendmentRatePlanData](docs/AmendmentRatePlanData.md)
- [ApplyCreditMemoType](docs/ApplyCreditMemoType.md)
- [ApplyPaymentType](docs/ApplyPaymentType.md)
- [BatchDebitMemoType](docs/BatchDebitMemoType.md)
- [BatchInvoiceType](docs/BatchInvoiceType.md)
- [BillingDocumentQueryResponseElementType](docs/BillingDocumentQueryResponseElementType.md)
- [BillingOptions](docs/BillingOptions.md)
- [BillingPreviewResult](docs/BillingPreviewResult.md)
- [BillingUpdate](docs/BillingUpdate.md)
- [BreakdownDetail](docs/BreakdownDetail.md)
- [CalloutAuth](docs/CalloutAuth.md)
- [CalloutMergeFields](docs/CalloutMergeFields.md)
- [CancelSubscription](docs/CancelSubscription.md)
- [ChargeMetricsData](docs/ChargeMetricsData.md)
- [ChargeOverride](docs/ChargeOverride.md)
- [ChargeOverrideBilling](docs/ChargeOverrideBilling.md)
- [ChargeOverrideForEvergreen](docs/ChargeOverrideForEvergreen.md)
- [ChargeOverridePricing](docs/ChargeOverridePricing.md)
- [ChargePreviewMetrics](docs/ChargePreviewMetrics.md)
- [ChargePreviewMetricsCmrr](docs/ChargePreviewMetricsCmrr.md)
- [ChargePreviewMetricsTax](docs/ChargePreviewMetricsTax.md)
- [ChargePreviewMetricsTcb](docs/ChargePreviewMetricsTcb.md)
- [ChargePreviewMetricsTcv](docs/ChargePreviewMetricsTcv.md)
- [ChargeRatedResult](docs/ChargeRatedResult.md)
- [ChargeTier](docs/ChargeTier.md)
- [ChargeUpdate](docs/ChargeUpdate.md)
- [ChargeUpdateForEvergreen](docs/ChargeUpdateForEvergreen.md)
- [CommonResponseType](docs/CommonResponseType.md)
- [Contact](docs/Contact.md)
- [ContactObjectCustomFields](docs/ContactObjectCustomFields.md)
- [CreateEntityResponseType](docs/CreateEntityResponseType.md)
- [CreateEntityType](docs/CreateEntityType.md)
- [CreateOrderChargeOverride](docs/CreateOrderChargeOverride.md)
- [CreateOrderChargeUpdate](docs/CreateOrderChargeUpdate.md)
- [CreateOrderCreateSubscription](docs/CreateOrderCreateSubscription.md)
- [CreateOrderCreateSubscriptionTerms](docs/CreateOrderCreateSubscriptionTerms.md)
- [CreateOrderCreateSubscriptionTermsInitialTerm](docs/CreateOrderCreateSubscriptionTermsInitialTerm.md)
- [CreateOrderOrderAction](docs/CreateOrderOrderAction.md)
- [CreateOrderPricingUpdate](docs/CreateOrderPricingUpdate.md)
- [CreateOrderRatePlanOverride](docs/CreateOrderRatePlanOverride.md)
- [CreateOrderRatePlanUpdate](docs/CreateOrderRatePlanUpdate.md)
- [CreatePMPayPalECPayPalNativeEC](docs/CreatePMPayPalECPayPalNativeEC.md)
- [CreatePaymentMethodCommon](docs/CreatePaymentMethodCommon.md)
- [CreatePaymentMethodPayPalAdaptive](docs/CreatePaymentMethodPayPalAdaptive.md)
- [CreatePaymentTypeFinanceInformation](docs/CreatePaymentTypeFinanceInformation.md)
- [CreateSubscription](docs/CreateSubscription.md)
- [CreateSubscriptionForEvergreen](docs/CreateSubscriptionForEvergreen.md)
- [CreateSubscriptionNewSubscriptionOwnerAccount](docs/CreateSubscriptionNewSubscriptionOwnerAccount.md)
- [CreateSubscriptionTerms](docs/CreateSubscriptionTerms.md)
- [CreditBalanceAdjustmentObjectCustomFields](docs/CreditBalanceAdjustmentObjectCustomFields.md)
- [CreditBalanceAdjustmentObjectNSFields](docs/CreditBalanceAdjustmentObjectNSFields.md)
- [CreditCard](docs/CreditCard.md)
- [CreditMemoApplyDebitMemoItemRequestType](docs/CreditMemoApplyDebitMemoItemRequestType.md)
- [CreditMemoApplyDebitMemoRequestType](docs/CreditMemoApplyDebitMemoRequestType.md)
- [CreditMemoApplyInvoiceItemRequestType](docs/CreditMemoApplyInvoiceItemRequestType.md)
- [CreditMemoApplyInvoiceRequestType](docs/CreditMemoApplyInvoiceRequestType.md)
- [CreditMemoFromChargeDetailTypeFinanceInformation](docs/CreditMemoFromChargeDetailTypeFinanceInformation.md)
- [CreditMemoItemBreakdown](docs/CreditMemoItemBreakdown.md)
- [CreditMemoItemFromInvoiceItemTypeFinanceInformation](docs/CreditMemoItemFromInvoiceItemTypeFinanceInformation.md)
- [CreditMemoItemObjectCustomFields](docs/CreditMemoItemObjectCustomFields.md)
- [CreditMemoObjectCustomFields](docs/CreditMemoObjectCustomFields.md)
- [CreditMemoObjectNSFields](docs/CreditMemoObjectNSFields.md)
- [CreditMemoResponseType](docs/CreditMemoResponseType.md)
- [CreditMemoTaxItemFromInvoiceTaxItemType](docs/CreditMemoTaxItemFromInvoiceTaxItemType.md)
- [CreditMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation](docs/CreditMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation.md)
- [CreditMemoUnapplyDebitMemoItemRequestType](docs/CreditMemoUnapplyDebitMemoItemRequestType.md)
- [CreditMemoUnapplyDebitMemoRequestType](docs/CreditMemoUnapplyDebitMemoRequestType.md)
- [CreditMemoUnapplyInvoiceItemRequestType](docs/CreditMemoUnapplyInvoiceItemRequestType.md)
- [CreditMemoUnapplyInvoiceRequestType](docs/CreditMemoUnapplyInvoiceRequestType.md)
- [DELETEntityResponseType](docs/DELETEntityResponseType.md)
- [DataAccessControlField](docs/DataAccessControlField.md)
- [DebitMemoFromChargeDetailTypeFinanceInformation](docs/DebitMemoFromChargeDetailTypeFinanceInformation.md)
- [DebitMemoItemFromInvoiceItemTypeFinanceInformation](docs/DebitMemoItemFromInvoiceItemTypeFinanceInformation.md)
- [DebitMemoItemObjectCustomFields](docs/DebitMemoItemObjectCustomFields.md)
- [DebitMemoObjectCustomFields](docs/DebitMemoObjectCustomFields.md)
- [DebitMemoObjectNSFields](docs/DebitMemoObjectNSFields.md)
- [DebitMemoTaxItemFromInvoiceTaxItemType](docs/DebitMemoTaxItemFromInvoiceTaxItemType.md)
- [DebitMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation](docs/DebitMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation.md)
- [DeleteResult](docs/DeleteResult.md)
- [DiscountPricingOverride](docs/DiscountPricingOverride.md)
- [DiscountPricingUpdate](docs/DiscountPricingUpdate.md)
- [ElectronicPaymentOptions](docs/ElectronicPaymentOptions.md)
- [EndConditions](docs/EndConditions.md)
- [ErrorResponse](docs/ErrorResponse.md)
- [ErrorResponseReasons](docs/ErrorResponseReasons.md)
- [EventTrigger](docs/EventTrigger.md)
- [EventType](docs/EventType.md)
- [ExecuteResult](docs/ExecuteResult.md)
- [ExternalPaymentOptions](docs/ExternalPaymentOptions.md)
- [FeatureObjectCustomFields](docs/FeatureObjectCustomFields.md)
- [FilterRuleParameterDefinition](docs/FilterRuleParameterDefinition.md)
- [FilterRuleParameterDefinitions](docs/FilterRuleParameterDefinitions.md)
- [FilterRuleParameterValues](docs/FilterRuleParameterValues.md)
- [FinanceInformation](docs/FinanceInformation.md)
- [GETAPaymentGatwayResponse](docs/GETAPaymentGatwayResponse.md)
- [GETARPaymentTypeFinanceInformation](docs/GETARPaymentTypeFinanceInformation.md)
- [GETAccountSummaryInvoiceType](docs/GETAccountSummaryInvoiceType.md)
- [GETAccountSummaryPaymentInvoiceType](docs/GETAccountSummaryPaymentInvoiceType.md)
- [GETAccountSummaryPaymentType](docs/GETAccountSummaryPaymentType.md)
- [GETAccountSummarySubscriptionRatePlanType](docs/GETAccountSummarySubscriptionRatePlanType.md)
- [GETAccountSummaryType](docs/GETAccountSummaryType.md)
- [GETAccountSummaryTypeBasicInfoDefaultPaymentMethod](docs/GETAccountSummaryTypeBasicInfoDefaultPaymentMethod.md)
- [GETAccountSummaryTypeTaxInfo](docs/GETAccountSummaryTypeTaxInfo.md)
- [GETAccountSummaryUsageType](docs/GETAccountSummaryUsageType.md)
- [GETAccountType](docs/GETAccountType.md)
- [GETAccountTypeBillingAndPayment](docs/GETAccountTypeBillingAndPayment.md)
- [GETAccountTypeMetrics](docs/GETAccountTypeMetrics.md)
- [GETAccountingCodesType](docs/GETAccountingCodesType.md)
- [GETAccountingPeriodTypeFileIds](docs/GETAccountingPeriodTypeFileIds.md)
- [GETAccountingPeriodsType](docs/GETAccountingPeriodsType.md)
- [GETAmendmentType](docs/GETAmendmentType.md)
- [GETAttachmentResponseType](docs/GETAttachmentResponseType.md)
- [GETAttachmentResponseWithoutSuccessType](docs/GETAttachmentResponseWithoutSuccessType.md)
- [GETAttachmentsResponseType](docs/GETAttachmentsResponseType.md)
- [GETBillingDocumentFilesDeletionJobResponse](docs/GETBillingDocumentFilesDeletionJobResponse.md)
- [GETBillingDocumentsResponseType](docs/GETBillingDocumentsResponseType.md)
- [GETCMTaxItemType](docs/GETCMTaxItemType.md)
- [GETCMTaxItemTypeFinanceInformation](docs/GETCMTaxItemTypeFinanceInformation.md)
- [GETCalloutHistoryVOType](docs/GETCalloutHistoryVOType.md)
- [GETCalloutHistoryVOsType](docs/GETCalloutHistoryVOsType.md)
- [GETCatalogType](docs/GETCatalogType.md)
- [GETChargeRSDetailType](docs/GETChargeRSDetailType.md)
- [GETCreditMemoCollectionType](docs/GETCreditMemoCollectionType.md)
- [GETCreditMemoItemPartType](docs/GETCreditMemoItemPartType.md)
- [GETCreditMemoItemPartTypewithSuccess](docs/GETCreditMemoItemPartTypewithSuccess.md)
- [GETCreditMemoItemPartsCollectionType](docs/GETCreditMemoItemPartsCollectionType.md)
- [GETCreditMemoItemTypeFinanceInformation](docs/GETCreditMemoItemTypeFinanceInformation.md)
- [GETCreditMemoItemTypewithSuccessFinanceInformation](docs/GETCreditMemoItemTypewithSuccessFinanceInformation.md)
- [GETCreditMemoItemsListType](docs/GETCreditMemoItemsListType.md)
- [GETCreditMemoPartType](docs/GETCreditMemoPartType.md)
- [GETCreditMemoPartTypewithSuccess](docs/GETCreditMemoPartTypewithSuccess.md)
- [GETCreditMemoPartsCollectionType](docs/GETCreditMemoPartsCollectionType.md)
- [GETCustomExchangeRatesDataType](docs/GETCustomExchangeRatesDataType.md)
- [GETCustomExchangeRatesType](docs/GETCustomExchangeRatesType.md)
- [GETDMTaxItemType](docs/GETDMTaxItemType.md)
- [GETDMTaxItemTypeFinanceInformation](docs/GETDMTaxItemTypeFinanceInformation.md)
- [GETDebitMemoCollectionType](docs/GETDebitMemoCollectionType.md)
- [GETDebitMemoItemCollectionType](docs/GETDebitMemoItemCollectionType.md)
- [GETDebitMemoItemTypeFinanceInformation](docs/GETDebitMemoItemTypeFinanceInformation.md)
- [GETDiscountApplyDetailsType](docs/GETDiscountApplyDetailsType.md)
- [GETDocumentPropertiesResponseType](docs/GETDocumentPropertiesResponseType.md)
- [GETEmailHistoryVOType](docs/GETEmailHistoryVOType.md)
- [GETEmailHistoryVOsType](docs/GETEmailHistoryVOsType.md)
- [GETEntitiesResponseType](docs/GETEntitiesResponseType.md)
- [GETEntitiesResponseTypeWithId](docs/GETEntitiesResponseTypeWithId.md)
- [GETEntitiesType](docs/GETEntitiesType.md)
- [GETEntitiesUserAccessibleResponseType](docs/GETEntitiesUserAccessibleResponseType.md)
- [GETEntityConnectionsArrayItemsType](docs/GETEntityConnectionsArrayItemsType.md)
- [GETEntityConnectionsResponseType](docs/GETEntityConnectionsResponseType.md)
- [GETInvoiceFileWrapper](docs/GETInvoiceFileWrapper.md)
- [GETInvoiceFilesResponse](docs/GETInvoiceFilesResponse.md)
- [GETInvoiceItemsResponse](docs/GETInvoiceItemsResponse.md)
- [GETJournalEntriesInJournalRunType](docs/GETJournalEntriesInJournalRunType.md)
- [GETJournalEntrySegmentType](docs/GETJournalEntrySegmentType.md)
- [GETJournalRunTransactionType](docs/GETJournalRunTransactionType.md)
- [GETJournalRunType](docs/GETJournalRunType.md)
- [GETMassUpdateType](docs/GETMassUpdateType.md)
- [GETPaidInvoicesType](docs/GETPaidInvoicesType.md)
- [GETPaymentGatwaysResponse](docs/GETPaymentGatwaysResponse.md)
- [GETPaymentItemPartCollectionType](docs/GETPaymentItemPartCollectionType.md)
- [GETPaymentItemPartType](docs/GETPaymentItemPartType.md)
- [GETPaymentItemPartTypewithSuccess](docs/GETPaymentItemPartTypewithSuccess.md)
- [GETPaymentMethodType](docs/GETPaymentMethodType.md)
- [GETPaymentMethodTypeCardHolderInfo](docs/GETPaymentMethodTypeCardHolderInfo.md)
- [GETPaymentMethodsType](docs/GETPaymentMethodsType.md)
- [GETPaymentPartType](docs/GETPaymentPartType.md)
- [GETPaymentPartTypewithSuccess](docs/GETPaymentPartTypewithSuccess.md)
- [GETPaymentPartsCollectionType](docs/GETPaymentPartsCollectionType.md)
- [GETPaymentRunCollectionType](docs/GETPaymentRunCollectionType.md)
- [GETPaymentRunSummaryResponse](docs/GETPaymentRunSummaryResponse.md)
- [GETPaymentRunSummaryTotalValues](docs/GETPaymentRunSummaryTotalValues.md)
- [GETPaymentRunType](docs/GETPaymentRunType.md)
- [GETPaymentsType](docs/GETPaymentsType.md)
- [GETProductDiscountApplyDetailsType](docs/GETProductDiscountApplyDetailsType.md)
- [GETProductRatePlanChargePricingTierType](docs/GETProductRatePlanChargePricingTierType.md)
- [GETProductRatePlanChargePricingType](docs/GETProductRatePlanChargePricingType.md)
- [GETProductRatePlansResponse](docs/GETProductRatePlansResponse.md)
- [GETPublicEmailTemplateResponse](docs/GETPublicEmailTemplateResponse.md)
- [GETPublicNotificationDefinitionResponse](docs/GETPublicNotificationDefinitionResponse.md)
- [GETPublicNotificationDefinitionResponseCallout](docs/GETPublicNotificationDefinitionResponseCallout.md)
- [GETPublicNotificationDefinitionResponseFilterRule](docs/GETPublicNotificationDefinitionResponseFilterRule.md)
- [GETRSDetailsByChargeType](docs/GETRSDetailsByChargeType.md)
- [GETRSDetailsByProductChargeType](docs/GETRSDetailsByProductChargeType.md)
- [GETRefundCollectionType](docs/GETRefundCollectionType.md)
- [GETRefundCreditMemoTypeFinanceInformation](docs/GETRefundCreditMemoTypeFinanceInformation.md)
- [GETRefundItemPartCollectionType](docs/GETRefundItemPartCollectionType.md)
- [GETRefundItemPartType](docs/GETRefundItemPartType.md)
- [GETRefundItemPartTypewithSuccess](docs/GETRefundItemPartTypewithSuccess.md)
- [GETRefundPartCollectionType](docs/GETRefundPartCollectionType.md)
- [GETRevenueEventDetailsType](docs/GETRevenueEventDetailsType.md)
- [GETRevenueItemsType](docs/GETRevenueItemsType.md)
- [GETRevenueRecognitionRuleAssociationType](docs/GETRevenueRecognitionRuleAssociationType.md)
- [GETRevenueStartDateSettingType](docs/GETRevenueStartDateSettingType.md)
- [GETRsRevenueItemsType](docs/GETRsRevenueItemsType.md)
- [GETSubscriptionProductFeatureType](docs/GETSubscriptionProductFeatureType.md)
- [GETSubscriptionWrapper](docs/GETSubscriptionWrapper.md)
- [GETTaxationItemListType](docs/GETTaxationItemListType.md)
- [GETTaxationItemTypeFinanceInformation](docs/GETTaxationItemTypeFinanceInformation.md)
- [GETTierType](docs/GETTierType.md)
- [GETUsageWrapper](docs/GETUsageWrapper.md)
- [GatewayOption](docs/GatewayOption.md)
- [GenerateBillingDocumentResponseType](docs/GenerateBillingDocumentResponseType.md)
- [GetAllOrdersResponseType](docs/GetAllOrdersResponseType.md)
- [GetBillingPreviewRunResponse](docs/GetBillingPreviewRunResponse.md)
- [GetDebitMemoApplicationPartCollectionType](docs/GetDebitMemoApplicationPartCollectionType.md)
- [GetDebitMemoApplicationPartType](docs/GetDebitMemoApplicationPartType.md)
- [GetHostedPageType](docs/GetHostedPageType.md)
- [GetHostedPagesType](docs/GetHostedPagesType.md)
- [GetInvoiceApplicationPartCollectionType](docs/GetInvoiceApplicationPartCollectionType.md)
- [GetInvoiceApplicationPartType](docs/GetInvoiceApplicationPartType.md)
- [GetOrderBillingInfoResponseTypeBillingInfo](docs/GetOrderBillingInfoResponseTypeBillingInfo.md)
- [InlineResponse200](docs/InlineResponse200.md)
- [InlineResponse2001](docs/InlineResponse2001.md)
- [InlineResponse2002](docs/InlineResponse2002.md)
- [InlineResponse2003](docs/InlineResponse2003.md)
- [Invoice](docs/Invoice.md)
- [InvoiceAdjustmentObjectCustomFields](docs/InvoiceAdjustmentObjectCustomFields.md)
- [InvoiceData](docs/InvoiceData.md)
- [InvoiceFile](docs/InvoiceFile.md)
- [InvoiceItemAdjustmentObjectCustomFields](docs/InvoiceItemAdjustmentObjectCustomFields.md)
- [InvoiceItemAdjustmentObjectNSFields](docs/InvoiceItemAdjustmentObjectNSFields.md)
- [InvoiceItemBreakdown](docs/InvoiceItemBreakdown.md)
- [InvoiceItemObjectCustomFields](docs/InvoiceItemObjectCustomFields.md)
- [InvoiceItemObjectNSFields](docs/InvoiceItemObjectNSFields.md)
- [InvoiceItemPreviewResult](docs/InvoiceItemPreviewResult.md)
- [InvoiceItemPreviewResultAdditionalInfo](docs/InvoiceItemPreviewResultAdditionalInfo.md)
- [InvoiceObjectCustomFields](docs/InvoiceObjectCustomFields.md)
- [InvoiceObjectNSFields](docs/InvoiceObjectNSFields.md)
- [InvoicePayment](docs/InvoicePayment.md)
- [InvoicePaymentData](docs/InvoicePaymentData.md)
- [InvoiceProcessingOptions](docs/InvoiceProcessingOptions.md)
- [InvoiceResponseType](docs/InvoiceResponseType.md)
- [JournalEntryItemObjectCustomFields](docs/JournalEntryItemObjectCustomFields.md)
- [JournalEntryObjectCustomFields](docs/JournalEntryObjectCustomFields.md)
- [LastTerm](docs/LastTerm.md)
- [ListOfExchangeRates](docs/ListOfExchangeRates.md)
- [NewChargeMetrics](docs/NewChargeMetrics.md)
- [OneTimeFlatFeePricingOverride](docs/OneTimeFlatFeePricingOverride.md)
- [OneTimePerUnitPricingOverride](docs/OneTimePerUnitPricingOverride.md)
- [OneTimeTieredPricingOverride](docs/OneTimeTieredPricingOverride.md)
- [OneTimeVolumePricingOverride](docs/OneTimeVolumePricingOverride.md)
- [Order](docs/Order.md)
- [OrderAction](docs/OrderAction.md)
- [OrderActionForEvergreen](docs/OrderActionForEvergreen.md)
- [OrderActionObjectCustomFields](docs/OrderActionObjectCustomFields.md)
- [OrderForEvergreen](docs/OrderForEvergreen.md)
- [OrderForEvergreenSubscriptions](docs/OrderForEvergreenSubscriptions.md)
- [OrderItem](docs/OrderItem.md)
- [OrderMetric](docs/OrderMetric.md)
- [OrderMetricsForEvergreen](docs/OrderMetricsForEvergreen.md)
- [OrderObjectCustomFields](docs/OrderObjectCustomFields.md)
- [OrderRatedResult](docs/OrderRatedResult.md)
- [OrderSubscriptions](docs/OrderSubscriptions.md)
- [OwnerTransfer](docs/OwnerTransfer.md)
- [POSTAccountResponseType](docs/POSTAccountResponseType.md)
- [POSTAccountTypeCreditCard](docs/POSTAccountTypeCreditCard.md)
- [POSTAccountTypeCreditCardCardHolderInfo](docs/POSTAccountTypeCreditCardCardHolderInfo.md)
- [POSTAccountTypeTaxInfo](docs/POSTAccountTypeTaxInfo.md)
- [POSTAccountingCodeResponseType](docs/POSTAccountingCodeResponseType.md)
- [POSTAccountingPeriodResponseType](docs/POSTAccountingPeriodResponseType.md)
- [POSTAttachmentResponseType](docs/POSTAttachmentResponseType.md)
- [POSTAuthorizeResponse](docs/POSTAuthorizeResponse.md)
- [POSTBillingDocumentFilesDeletionJobRequest](docs/POSTBillingDocumentFilesDeletionJobRequest.md)
- [POSTBillingDocumentFilesDeletionJobResponse](docs/POSTBillingDocumentFilesDeletionJobResponse.md)
- [POSTBillingPreviewCreditMemoItem](docs/POSTBillingPreviewCreditMemoItem.md)
- [POSTBillingPreviewInvoiceItem](docs/POSTBillingPreviewInvoiceItem.md)
- [POSTCatalogType](docs/POSTCatalogType.md)
- [POSTCreditMemoItemsForOrderBreakdown](docs/POSTCreditMemoItemsForOrderBreakdown.md)
- [POSTDecryptResponseType](docs/POSTDecryptResponseType.md)
- [POSTDecryptionType](docs/POSTDecryptionType.md)
- [POSTDelayAuthorizeCapture](docs/POSTDelayAuthorizeCapture.md)
- [POSTDistributionItemType](docs/POSTDistributionItemType.md)
- [POSTDocumentPropertiesType](docs/POSTDocumentPropertiesType.md)
- [POSTEmailBillingDocfromBillRunType](docs/POSTEmailBillingDocfromBillRunType.md)
- [POSTEntityConnectionsResponseType](docs/POSTEntityConnectionsResponseType.md)
- [POSTEntityConnectionsType](docs/POSTEntityConnectionsType.md)
- [POSTHMACSignatureResponseType](docs/POSTHMACSignatureResponseType.md)
- [POSTHMACSignatureType](docs/POSTHMACSignatureType.md)
- [POSTInvoiceCollectCreditMemosType](docs/POSTInvoiceCollectCreditMemosType.md)
- [POSTInvoiceCollectInvoicesType](docs/POSTInvoiceCollectInvoicesType.md)
- [POSTInvoiceCollectResponseType](docs/POSTInvoiceCollectResponseType.md)
- [POSTInvoiceCollectType](docs/POSTInvoiceCollectType.md)
- [POSTInvoiceItemsForOrderBreakdown](docs/POSTInvoiceItemsForOrderBreakdown.md)
- [POSTJournalEntryResponseType](docs/POSTJournalEntryResponseType.md)
- [POSTJournalEntrySegmentType](docs/POSTJournalEntrySegmentType.md)
- [POSTJournalRunResponseType](docs/POSTJournalRunResponseType.md)
- [POSTJournalRunTransactionType](docs/POSTJournalRunTransactionType.md)
- [POSTJournalRunType](docs/POSTJournalRunType.md)
- [POSTMassUpdateResponseType](docs/POSTMassUpdateResponseType.md)
- [POSTMemoPdfResponse](docs/POSTMemoPdfResponse.md)
- [POSTOrderPreviewRequestType](docs/POSTOrderPreviewRequestType.md)
- [POSTOrderPreviewRequestTypeSubscriptions](docs/POSTOrderPreviewRequestTypeSubscriptions.md)
- [POSTOrderRequestType](docs/POSTOrderRequestType.md)
- [POSTOrderRequestTypeSubscriptions](docs/POSTOrderRequestTypeSubscriptions.md)
- [POSTPaymentMethodDecryption](docs/POSTPaymentMethodDecryption.md)
- [POSTPaymentMethodDecryptionCardHolderInfo](docs/POSTPaymentMethodDecryptionCardHolderInfo.md)
- [POSTPaymentMethodResponseDecryption](docs/POSTPaymentMethodResponseDecryption.md)
- [POSTPaymentMethodResponseReasons](docs/POSTPaymentMethodResponseReasons.md)
- [POSTPaymentMethodResponseType](docs/POSTPaymentMethodResponseType.md)
- [POSTPaymentMethodType](docs/POSTPaymentMethodType.md)
- [POSTPaymentMethodTypeCardHolderInfo](docs/POSTPaymentMethodTypeCardHolderInfo.md)
- [POSTPaymentRunRequest](docs/POSTPaymentRunRequest.md)
- [POSTPublicEmailTemplateRequest](docs/POSTPublicEmailTemplateRequest.md)
- [POSTPublicNotificationDefinitionRequest](docs/POSTPublicNotificationDefinitionRequest.md)
- [POSTPublicNotificationDefinitionRequestCallout](docs/POSTPublicNotificationDefinitionRequestCallout.md)
- [POSTPublicNotificationDefinitionRequestFilterRule](docs/POSTPublicNotificationDefinitionRequestFilterRule.md)
- [POSTQuoteDocResponseType](docs/POSTQuoteDocResponseType.md)
- [POSTQuoteDocType](docs/POSTQuoteDocType.md)
- [POSTRSASignatureResponseType](docs/POSTRSASignatureResponseType.md)
- [POSTRSASignatureType](docs/POSTRSASignatureType.md)
- [POSTRevenueScheduleByChargeResponseType](docs/POSTRevenueScheduleByChargeResponseType.md)
- [POSTRevenueScheduleByTransactionResponseType](docs/POSTRevenueScheduleByTransactionResponseType.md)
- [POSTSubscriptionCancellationResponseType](docs/POSTSubscriptionCancellationResponseType.md)
- [POSTSubscriptionCancellationType](docs/POSTSubscriptionCancellationType.md)
- [POSTSubscriptionPreviewCreditMemoItemsType](docs/POSTSubscriptionPreviewCreditMemoItemsType.md)
- [POSTSubscriptionPreviewInvoiceItemsType](docs/POSTSubscriptionPreviewInvoiceItemsType.md)
- [POSTSubscriptionPreviewResponseType](docs/POSTSubscriptionPreviewResponseType.md)
- [POSTSubscriptionPreviewResponseTypeChargeMetrics](docs/POSTSubscriptionPreviewResponseTypeChargeMetrics.md)
- [POSTSubscriptionPreviewResponseTypeCreditMemo](docs/POSTSubscriptionPreviewResponseTypeCreditMemo.md)
- [POSTSubscriptionPreviewTypePreviewAccountInfoBillToContact](docs/POSTSubscriptionPreviewTypePreviewAccountInfoBillToContact.md)
- [POSTSubscriptionResponseType](docs/POSTSubscriptionResponseType.md)
- [POSTTaxationItemForCMTypeFinanceInformation](docs/POSTTaxationItemForCMTypeFinanceInformation.md)
- [POSTTaxationItemForDMTypeFinanceInformation](docs/POSTTaxationItemForDMTypeFinanceInformation.md)
- [POSTTaxationItemListForCMType](docs/POSTTaxationItemListForCMType.md)
- [POSTTaxationItemListForDMType](docs/POSTTaxationItemListForDMType.md)
- [POSTTierType](docs/POSTTierType.md)
- [POSTUsageResponseType](docs/POSTUsageResponseType.md)
- [POSTVoidAuthorize](docs/POSTVoidAuthorize.md)
- [POSTVoidAuthorizeResponse](docs/POSTVoidAuthorizeResponse.md)
- [PUTAcceptUserAccessResponseType](docs/PUTAcceptUserAccessResponseType.md)
- [PUTAttachmentType](docs/PUTAttachmentType.md)
- [PUTBatchDebitMemosRequest](docs/PUTBatchDebitMemosRequest.md)
- [PUTCreditMemoItemTypeFinanceInformation](docs/PUTCreditMemoItemTypeFinanceInformation.md)
- [PUTDebitMemoItemTypeFinanceInformation](docs/PUTDebitMemoItemTypeFinanceInformation.md)
- [PUTDenyUserAccessResponseType](docs/PUTDenyUserAccessResponseType.md)
- [PUTDocumentPropertiesType](docs/PUTDocumentPropertiesType.md)
- [PUTEntityConnectionsAcceptResponseType](docs/PUTEntityConnectionsAcceptResponseType.md)
- [PUTEntityConnectionsDenyResponseType](docs/PUTEntityConnectionsDenyResponseType.md)
- [PUTEntityConnectionsDisconnectResponseType](docs/PUTEntityConnectionsDisconnectResponseType.md)
- [PUTEventRIDetailType](docs/PUTEventRIDetailType.md)
- [PUTOrderActionTriggerDatesRequestType](docs/PUTOrderActionTriggerDatesRequestType.md)
- [PUTOrderActionTriggerDatesRequestTypeCharges](docs/PUTOrderActionTriggerDatesRequestTypeCharges.md)
- [PUTOrderActionTriggerDatesRequestTypeOrderActions](docs/PUTOrderActionTriggerDatesRequestTypeOrderActions.md)
- [PUTOrderActionTriggerDatesRequestTypeSubscriptions](docs/PUTOrderActionTriggerDatesRequestTypeSubscriptions.md)
- [PUTOrderActionTriggerDatesRequestTypeTriggerDates](docs/PUTOrderActionTriggerDatesRequestTypeTriggerDates.md)
- [PUTOrderPatchRequestType](docs/PUTOrderPatchRequestType.md)
- [PUTOrderPatchRequestTypeOrderActions](docs/PUTOrderPatchRequestTypeOrderActions.md)
- [PUTOrderPatchRequestTypeSubscriptions](docs/PUTOrderPatchRequestTypeSubscriptions.md)
- [PUTOrderTriggerDatesResponseTypeSubscriptions](docs/PUTOrderTriggerDatesResponseTypeSubscriptions.md)
- [PUTPaymentMethodResponseType](docs/PUTPaymentMethodResponseType.md)
- [PUTPaymentMethodType](docs/PUTPaymentMethodType.md)
- [PUTPaymentRunRequest](docs/PUTPaymentRunRequest.md)
- [PUTPublicCalloutOptionsRequest](docs/PUTPublicCalloutOptionsRequest.md)
- [PUTPublicEmailTemplateRequest](docs/PUTPublicEmailTemplateRequest.md)
- [PUTPublicNotificationDefinitionRequest](docs/PUTPublicNotificationDefinitionRequest.md)
- [PUTPublicNotificationDefinitionRequestCallout](docs/PUTPublicNotificationDefinitionRequestCallout.md)
- [PUTPublicNotificationDefinitionRequestFilterRule](docs/PUTPublicNotificationDefinitionRequestFilterRule.md)
- [PUTRefundTypeFinanceInformation](docs/PUTRefundTypeFinanceInformation.md)
- [PUTRenewSubscriptionResponseType](docs/PUTRenewSubscriptionResponseType.md)
- [PUTRenewSubscriptionType](docs/PUTRenewSubscriptionType.md)
- [PUTRevenueScheduleResponseType](docs/PUTRevenueScheduleResponseType.md)
- [PUTScheduleRIDetailType](docs/PUTScheduleRIDetailType.md)
- [PUTSendUserAccessRequestResponseType](docs/PUTSendUserAccessRequestResponseType.md)
- [PUTSendUserAccessRequestType](docs/PUTSendUserAccessRequestType.md)
- [PUTSrpRemoveType](docs/PUTSrpRemoveType.md)
- [PUTSubscriptionPatchRequestType](docs/PUTSubscriptionPatchRequestType.md)
- [PUTSubscriptionPatchRequestTypeCharges](docs/PUTSubscriptionPatchRequestTypeCharges.md)
- [PUTSubscriptionPatchRequestTypeRatePlans](docs/PUTSubscriptionPatchRequestTypeRatePlans.md)
- [PUTSubscriptionPreviewInvoiceItemsType](docs/PUTSubscriptionPreviewInvoiceItemsType.md)
- [PUTSubscriptionResponseType](docs/PUTSubscriptionResponseType.md)
- [PUTSubscriptionResponseTypeChargeMetrics](docs/PUTSubscriptionResponseTypeChargeMetrics.md)
- [PUTSubscriptionResponseTypeCreditMemo](docs/PUTSubscriptionResponseTypeCreditMemo.md)
- [PUTSubscriptionResumeResponseType](docs/PUTSubscriptionResumeResponseType.md)
- [PUTSubscriptionResumeType](docs/PUTSubscriptionResumeType.md)
- [PUTSubscriptionSuspendResponseType](docs/PUTSubscriptionSuspendResponseType.md)
- [PUTSubscriptionSuspendType](docs/PUTSubscriptionSuspendType.md)
- [PUTVerifyPaymentMethodResponseType](docs/PUTVerifyPaymentMethodResponseType.md)
- [PUTVerifyPaymentMethodType](docs/PUTVerifyPaymentMethodType.md)
- [PUTVerifyPaymentMethodTypeGatewayOptions](docs/PUTVerifyPaymentMethodTypeGatewayOptions.md)
- [PUTWriteOffInvoiceRequest](docs/PUTWriteOffInvoiceRequest.md)
- [PUTWriteOffInvoiceResponse](docs/PUTWriteOffInvoiceResponse.md)
- [PUTWriteOffInvoiceResponseCreditMemo](docs/PUTWriteOffInvoiceResponseCreditMemo.md)
- [PaymentCollectionResponseType](docs/PaymentCollectionResponseType.md)
- [PaymentDebitMemoApplicationApplyRequestType](docs/PaymentDebitMemoApplicationApplyRequestType.md)
- [PaymentDebitMemoApplicationCreateRequestType](docs/PaymentDebitMemoApplicationCreateRequestType.md)
- [PaymentDebitMemoApplicationItemApplyRequestType](docs/PaymentDebitMemoApplicationItemApplyRequestType.md)
- [PaymentDebitMemoApplicationItemCreateRequestType](docs/PaymentDebitMemoApplicationItemCreateRequestType.md)
- [PaymentDebitMemoApplicationItemUnapplyRequestType](docs/PaymentDebitMemoApplicationItemUnapplyRequestType.md)
- [PaymentDebitMemoApplicationUnapplyRequestType](docs/PaymentDebitMemoApplicationUnapplyRequestType.md)
- [PaymentInvoiceApplicationApplyRequestType](docs/PaymentInvoiceApplicationApplyRequestType.md)
- [PaymentInvoiceApplicationCreateRequestType](docs/PaymentInvoiceApplicationCreateRequestType.md)
- [PaymentInvoiceApplicationItemApplyRequestType](docs/PaymentInvoiceApplicationItemApplyRequestType.md)
- [PaymentInvoiceApplicationItemCreateRequestType](docs/PaymentInvoiceApplicationItemCreateRequestType.md)
- [PaymentInvoiceApplicationItemUnapplyRequestType](docs/PaymentInvoiceApplicationItemUnapplyRequestType.md)
- [PaymentInvoiceApplicationUnapplyRequestType](docs/PaymentInvoiceApplicationUnapplyRequestType.md)
- [PaymentObjectCustomFields](docs/PaymentObjectCustomFields.md)
- [PaymentObjectNSFields](docs/PaymentObjectNSFields.md)
- [PostBillingPreviewParam](docs/PostBillingPreviewParam.md)
- [PostBillingPreviewRunParam](docs/PostBillingPreviewRunParam.md)
- [PostCreditMemoEmailRequestType](docs/PostCreditMemoEmailRequestType.md)
- [PostDebitMemoEmailType](docs/PostDebitMemoEmailType.md)
- [PostEventTriggerRequest](docs/PostEventTriggerRequest.md)
- [PostGenerateBillingDocumentType](docs/PostGenerateBillingDocumentType.md)
- [PostInvoiceEmailRequestType](docs/PostInvoiceEmailRequestType.md)
- [PostNonRefRefundTypeFinanceInformation](docs/PostNonRefRefundTypeFinanceInformation.md)
- [PostOrderResponseTypeSubscriptions](docs/PostOrderResponseTypeSubscriptions.md)
- [PostRefundTypeFinanceInformation](docs/PostRefundTypeFinanceInformation.md)
- [PreviewAccountInfo](docs/PreviewAccountInfo.md)
- [PreviewContactInfo](docs/PreviewContactInfo.md)
- [PreviewOptions](docs/PreviewOptions.md)
- [PreviewOrderChargeOverride](docs/PreviewOrderChargeOverride.md)
- [PreviewOrderChargeUpdate](docs/PreviewOrderChargeUpdate.md)
- [PreviewOrderCreateSubscription](docs/PreviewOrderCreateSubscription.md)
- [PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount](docs/PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount.md)
- [PreviewOrderOrderAction](docs/PreviewOrderOrderAction.md)
- [PreviewOrderPricingUpdate](docs/PreviewOrderPricingUpdate.md)
- [PreviewOrderRatePlanOverride](docs/PreviewOrderRatePlanOverride.md)
- [PreviewOrderRatePlanUpdate](docs/PreviewOrderRatePlanUpdate.md)
- [PreviewResult](docs/PreviewResult.md)
- [PreviewResultChargeMetrics](docs/PreviewResultChargeMetrics.md)
- [PreviewResultCreditMemos](docs/PreviewResultCreditMemos.md)
- [PreviewResultInvoices](docs/PreviewResultInvoices.md)
- [PreviewResultOrderActions](docs/PreviewResultOrderActions.md)
- [PreviewResultOrderMetrics](docs/PreviewResultOrderMetrics.md)
- [PriceChangeParams](docs/PriceChangeParams.md)
- [PricingUpdate](docs/PricingUpdate.md)
- [PricingUpdateForEvergreen](docs/PricingUpdateForEvergreen.md)
- [ProcessingOptions](docs/ProcessingOptions.md)
- [ProcessingOptionsElectronicPaymentOptions](docs/ProcessingOptionsElectronicPaymentOptions.md)
- [ProductFeatureObjectCustomFields](docs/ProductFeatureObjectCustomFields.md)
- [ProductObjectCustomFields](docs/ProductObjectCustomFields.md)
- [ProductObjectNSFields](docs/ProductObjectNSFields.md)
- [ProductRatePlanChargeObjectCustomFields](docs/ProductRatePlanChargeObjectCustomFields.md)
- [ProductRatePlanChargeObjectNSFields](docs/ProductRatePlanChargeObjectNSFields.md)
- [ProductRatePlanObjectCustomFields](docs/ProductRatePlanObjectCustomFields.md)
- [ProductRatePlanObjectNSFields](docs/ProductRatePlanObjectNSFields.md)
- [ProvisionEntityResponseType](docs/ProvisionEntityResponseType.md)
- [ProxyActionamendRequest](docs/ProxyActionamendRequest.md)
- [ProxyActionamendResponse](docs/ProxyActionamendResponse.md)
- [ProxyActioncreateRequest](docs/ProxyActioncreateRequest.md)
- [ProxyActiondeleteRequest](docs/ProxyActiondeleteRequest.md)
- [ProxyActionexecuteRequest](docs/ProxyActionexecuteRequest.md)
- [ProxyActiongenerateRequest](docs/ProxyActiongenerateRequest.md)
- [ProxyActionqueryMoreRequest](docs/ProxyActionqueryMoreRequest.md)
- [ProxyActionqueryMoreResponse](docs/ProxyActionqueryMoreResponse.md)
- [ProxyActionqueryRequest](docs/ProxyActionqueryRequest.md)
- [ProxyActionqueryRequestConf](docs/ProxyActionqueryRequestConf.md)
- [ProxyActionqueryResponse](docs/ProxyActionqueryResponse.md)
- [ProxyActionsubscribeRequest](docs/ProxyActionsubscribeRequest.md)
- [ProxyActionupdateRequest](docs/ProxyActionupdateRequest.md)
- [ProxyBadRequestResponse](docs/ProxyBadRequestResponse.md)
- [ProxyBadRequestResponseErrors](docs/ProxyBadRequestResponseErrors.md)
- [ProxyCreateBillRun](docs/ProxyCreateBillRun.md)
- [ProxyCreateExport](docs/ProxyCreateExport.md)
- [ProxyCreateInvoicePayment](docs/ProxyCreateInvoicePayment.md)
- [ProxyCreateOrModifyResponse](docs/ProxyCreateOrModifyResponse.md)
- [ProxyCreatePaymentGatewayOptionData](docs/ProxyCreatePaymentGatewayOptionData.md)
- [ProxyCreatePaymentMethod](docs/ProxyCreatePaymentMethod.md)
- [ProxyCreateRefundRefundInvoicePaymentData](docs/ProxyCreateRefundRefundInvoicePaymentData.md)
- [ProxyCreateUnitOfMeasure](docs/ProxyCreateUnitOfMeasure.md)
- [ProxyDeleteResponse](docs/ProxyDeleteResponse.md)
- [ProxyGetBillRun](docs/ProxyGetBillRun.md)
- [ProxyGetCommunicationProfile](docs/ProxyGetCommunicationProfile.md)
- [ProxyGetExport](docs/ProxyGetExport.md)
- [ProxyGetImport](docs/ProxyGetImport.md)
- [ProxyGetInvoicePayment](docs/ProxyGetInvoicePayment.md)
- [ProxyGetInvoiceSplit](docs/ProxyGetInvoiceSplit.md)
- [ProxyGetInvoiceSplitItem](docs/ProxyGetInvoiceSplitItem.md)
- [ProxyGetPaymentMethod](docs/ProxyGetPaymentMethod.md)
- [ProxyGetPaymentMethodSnapshot](docs/ProxyGetPaymentMethodSnapshot.md)
- [ProxyGetPaymentMethodTransactionLog](docs/ProxyGetPaymentMethodTransactionLog.md)
- [ProxyGetPaymentTransactionLog](docs/ProxyGetPaymentTransactionLog.md)
- [ProxyGetProductRatePlanChargeTier](docs/ProxyGetProductRatePlanChargeTier.md)
- [ProxyGetRatePlanChargeTier](docs/ProxyGetRatePlanChargeTier.md)
- [ProxyGetRefundInvoicePayment](docs/ProxyGetRefundInvoicePayment.md)
- [ProxyGetRefundTransactionLog](docs/ProxyGetRefundTransactionLog.md)
- [ProxyGetUnitOfMeasure](docs/ProxyGetUnitOfMeasure.md)
- [ProxyModifyBillRun](docs/ProxyModifyBillRun.md)
- [ProxyModifyInvoicePayment](docs/ProxyModifyInvoicePayment.md)
- [ProxyModifyPaymentMethod](docs/ProxyModifyPaymentMethod.md)
- [ProxyModifyUnitOfMeasure](docs/ProxyModifyUnitOfMeasure.md)
- [ProxyNoDataResponse](docs/ProxyNoDataResponse.md)
- [ProxyPostImport](docs/ProxyPostImport.md)
- [ProxyUnauthorizedResponse](docs/ProxyUnauthorizedResponse.md)
- [PutBatchInvoiceType](docs/PutBatchInvoiceType.md)
- [PutCreditMemoTaxItemType](docs/PutCreditMemoTaxItemType.md)
- [PutCreditMemoTaxItemTypeFinanceInformation](docs/PutCreditMemoTaxItemTypeFinanceInformation.md)
- [PutDebitMemoTaxItemType](docs/PutDebitMemoTaxItemType.md)
- [PutDebitMemoTaxItemTypeFinanceInformation](docs/PutDebitMemoTaxItemTypeFinanceInformation.md)
- [PutEventTriggerRequest](docs/PutEventTriggerRequest.md)
- [PutEventTriggerRequestEventType](docs/PutEventTriggerRequestEventType.md)
- [PutInvoiceType](docs/PutInvoiceType.md)
- [PutReverseInvoiceResponseType](docs/PutReverseInvoiceResponseType.md)
- [PutReverseInvoiceResponseTypeCreditMemo](docs/PutReverseInvoiceResponseTypeCreditMemo.md)
- [PutReverseInvoiceType](docs/PutReverseInvoiceType.md)
- [RatePlan](docs/RatePlan.md)
- [RatePlanChargeData](docs/RatePlanChargeData.md)
- [RatePlanChargeDataInRatePlanData](docs/RatePlanChargeDataInRatePlanData.md)
- [RatePlanChargeDataInRatePlanDataRatePlanCharge](docs/RatePlanChargeDataInRatePlanDataRatePlanCharge.md)
- [RatePlanChargeObjectCustomFields](docs/RatePlanChargeObjectCustomFields.md)
- [RatePlanChargeTier](docs/RatePlanChargeTier.md)
- [RatePlanData](docs/RatePlanData.md)
- [RatePlanDataSubscriptionProductFeatureList](docs/RatePlanDataSubscriptionProductFeatureList.md)
- [RatePlanObjectCustomFields](docs/RatePlanObjectCustomFields.md)
- [RatePlanOverride](docs/RatePlanOverride.md)
- [RatePlanOverrideForEvergreen](docs/RatePlanOverrideForEvergreen.md)
- [RatePlanUpdate](docs/RatePlanUpdate.md)
- [RatePlanUpdateForEvergreen](docs/RatePlanUpdateForEvergreen.md)
- [RatedItem](docs/RatedItem.md)
- [RefundCreditMemoItemType](docs/RefundCreditMemoItemType.md)
- [RefundInvoicePayment](docs/RefundInvoicePayment.md)
- [RefundObjectCustomFields](docs/RefundObjectCustomFields.md)
- [RefundObjectNSFields](docs/RefundObjectNSFields.md)
- [RefundPartResponseType](docs/RefundPartResponseType.md)
- [RefundPartResponseTypewithSuccess](docs/RefundPartResponseTypewithSuccess.md)
- [RemoveProduct](docs/RemoveProduct.md)
- [RenewalTerm](docs/RenewalTerm.md)
- [RevenueEventItemObjectCustomFields](docs/RevenueEventItemObjectCustomFields.md)
- [RevenueEventObjectCustomFields](docs/RevenueEventObjectCustomFields.md)
- [RevenueScheduleItemObjectCustomFields](docs/RevenueScheduleItemObjectCustomFields.md)
- [RevenueScheduleObjectCustomFields](docs/RevenueScheduleObjectCustomFields.md)
- [SaveResult](docs/SaveResult.md)
- [SubscribeRequest](docs/SubscribeRequest.md)
- [SubscribeRequestPaymentMethod](docs/SubscribeRequestPaymentMethod.md)
- [SubscribeRequestPaymentMethodGatewayOptionData](docs/SubscribeRequestPaymentMethodGatewayOptionData.md)
- [SubscribeRequestPreviewOptions](docs/SubscribeRequestPreviewOptions.md)
- [SubscribeRequestSubscribeOptions](docs/SubscribeRequestSubscribeOptions.md)
- [SubscribeRequestSubscribeOptionsElectronicPaymentOptions](docs/SubscribeRequestSubscribeOptionsElectronicPaymentOptions.md)
- [SubscribeRequestSubscribeOptionsExternalPaymentOptions](docs/SubscribeRequestSubscribeOptionsExternalPaymentOptions.md)
- [SubscribeRequestSubscribeOptionsSubscribeInvoiceProcessingOptions](docs/SubscribeRequestSubscribeOptionsSubscribeInvoiceProcessingOptions.md)
- [SubscribeRequestSubscriptionData](docs/SubscribeRequestSubscriptionData.md)
- [SubscribeResult](docs/SubscribeResult.md)
- [SubscribeResultChargeMetricsData](docs/SubscribeResultChargeMetricsData.md)
- [SubscribeResultInvoiceResult](docs/SubscribeResultInvoiceResult.md)
- [SubscribeResultInvoiceResultInvoice](docs/SubscribeResultInvoiceResultInvoice.md)
- [SubscriptionObjectCustomFields](docs/SubscriptionObjectCustomFields.md)
- [SubscriptionObjectNSFields](docs/SubscriptionObjectNSFields.md)
- [SubscriptionObjectQTFields](docs/SubscriptionObjectQTFields.md)
- [SubscriptionProductFeatureList](docs/SubscriptionProductFeatureList.md)
- [SubscriptionProductFeatureObjectCustomFields](docs/SubscriptionProductFeatureObjectCustomFields.md)
- [SubscriptionRatedResult](docs/SubscriptionRatedResult.md)
- [TaxInfo](docs/TaxInfo.md)
- [TaxationItemObjectCustomFields](docs/TaxationItemObjectCustomFields.md)
- [Term](docs/Term.md)
- [TermsAndConditions](docs/TermsAndConditions.md)
- [TimeSlicedElpNetMetrics](docs/TimeSlicedElpNetMetrics.md)
- [TimeSlicedMetrics](docs/TimeSlicedMetrics.md)
- [TimeSlicedMetricsForEvergreen](docs/TimeSlicedMetricsForEvergreen.md)
- [TimeSlicedNetMetrics](docs/TimeSlicedNetMetrics.md)
- [TimeSlicedNetMetricsForEvergreen](docs/TimeSlicedNetMetricsForEvergreen.md)
- [TimeSlicedTcbNetMetrics](docs/TimeSlicedTcbNetMetrics.md)
- [TimeSlicedTcbNetMetricsForEvergreen](docs/TimeSlicedTcbNetMetricsForEvergreen.md)
- [TokenResponse](docs/TokenResponse.md)
- [TransferPaymentType](docs/TransferPaymentType.md)
- [TriggerDate](docs/TriggerDate.md)
- [TriggerParams](docs/TriggerParams.md)
- [UnapplyCreditMemoType](docs/UnapplyCreditMemoType.md)
- [UnapplyPaymentType](docs/UnapplyPaymentType.md)
- [UpdateEntityResponseType](docs/UpdateEntityResponseType.md)
- [UpdateEntityType](docs/UpdateEntityType.md)
- [UsageObjectCustomFields](docs/UsageObjectCustomFields.md)
- [ZObject](docs/ZObject.md)
- [Account](docs/Account.md)
- [AmendmentRatePlanChargeDataRatePlanCharge](docs/AmendmentRatePlanChargeDataRatePlanCharge.md)
- [BillToContact](docs/BillToContact.md)
- [CreateOrderCreateSubscriptionNewSubscriptionOwnerAccount](docs/CreateOrderCreateSubscriptionNewSubscriptionOwnerAccount.md)
- [CreatePaymentType](docs/CreatePaymentType.md)
- [CreditMemoFromChargeDetailType](docs/CreditMemoFromChargeDetailType.md)
- [CreditMemoFromChargeType](docs/CreditMemoFromChargeType.md)
- [CreditMemoFromInvoiceType](docs/CreditMemoFromInvoiceType.md)
- [CreditMemoItemFromInvoiceItemType](docs/CreditMemoItemFromInvoiceItemType.md)
- [DebitMemoFromChargeDetailType](docs/DebitMemoFromChargeDetailType.md)
- [DebitMemoFromChargeType](docs/DebitMemoFromChargeType.md)
- [DebitMemoFromInvoiceType](docs/DebitMemoFromInvoiceType.md)
- [DebitMemoItemFromInvoiceItemType](docs/DebitMemoItemFromInvoiceItemType.md)
- [EventRevenueItemType](docs/EventRevenueItemType.md)
- [GETARPaymentType](docs/GETARPaymentType.md)
- [GETARPaymentTypewithSuccess](docs/GETARPaymentTypewithSuccess.md)
- [GETAccountSummarySubscriptionType](docs/GETAccountSummarySubscriptionType.md)
- [GETAccountSummaryTypeBasicInfo](docs/GETAccountSummaryTypeBasicInfo.md)
- [GETAccountSummaryTypeBillToContact](docs/GETAccountSummaryTypeBillToContact.md)
- [GETAccountSummaryTypeSoldToContact](docs/GETAccountSummaryTypeSoldToContact.md)
- [GETAccountTypeBasicInfo](docs/GETAccountTypeBasicInfo.md)
- [GETAccountTypeBillToContact](docs/GETAccountTypeBillToContact.md)
- [GETAccountTypeSoldToContact](docs/GETAccountTypeSoldToContact.md)
- [GETAccountingCodeItemType](docs/GETAccountingCodeItemType.md)
- [GETAccountingCodeItemWithoutSuccessType](docs/GETAccountingCodeItemWithoutSuccessType.md)
- [GETAccountingPeriodType](docs/GETAccountingPeriodType.md)
- [GETAccountingPeriodWithoutSuccessType](docs/GETAccountingPeriodWithoutSuccessType.md)
- [GETCreditMemoItemType](docs/GETCreditMemoItemType.md)
- [GETCreditMemoItemTypewithSuccess](docs/GETCreditMemoItemTypewithSuccess.md)
- [GETCreditMemoType](docs/GETCreditMemoType.md)
- [GETCreditMemoTypewithSuccess](docs/GETCreditMemoTypewithSuccess.md)
- [GETDebitMemoItemType](docs/GETDebitMemoItemType.md)
- [GETDebitMemoItemTypewithSuccess](docs/GETDebitMemoItemTypewithSuccess.md)
- [GETDebitMemoType](docs/GETDebitMemoType.md)
- [GETDebitMemoTypewithSuccess](docs/GETDebitMemoTypewithSuccess.md)
- [GETInvoiceType](docs/GETInvoiceType.md)
- [GETJournalEntryDetailType](docs/GETJournalEntryDetailType.md)
- [GETJournalEntryDetailTypeWithoutSuccess](docs/GETJournalEntryDetailTypeWithoutSuccess.md)
- [GETJournalEntryItemType](docs/GETJournalEntryItemType.md)
- [GETPaymentType](docs/GETPaymentType.md)
- [GETProductRatePlanChargeType](docs/GETProductRatePlanChargeType.md)
- [GETProductRatePlanType](docs/GETProductRatePlanType.md)
- [GETProductType](docs/GETProductType.md)
- [GETRSDetailForProductChargeType](docs/GETRSDetailForProductChargeType.md)
- [GETRSDetailType](docs/GETRSDetailType.md)
- [GETRSDetailWithoutSuccessType](docs/GETRSDetailWithoutSuccessType.md)
- [GETRefundCreditMemoType](docs/GETRefundCreditMemoType.md)
- [GETRefundPaymentType](docs/GETRefundPaymentType.md)
- [GETRefundType](docs/GETRefundType.md)
- [GETRefundTypewithSuccess](docs/GETRefundTypewithSuccess.md)
- [GETRevenueEventDetailType](docs/GETRevenueEventDetailType.md)
- [GETRevenueEventDetailWithoutSuccessType](docs/GETRevenueEventDetailWithoutSuccessType.md)
- [GETRevenueItemType](docs/GETRevenueItemType.md)
- [GETRsRevenueItemType](docs/GETRsRevenueItemType.md)
- [GETSubscriptionRatePlanChargesType](docs/GETSubscriptionRatePlanChargesType.md)
- [GETSubscriptionRatePlanType](docs/GETSubscriptionRatePlanType.md)
- [GETSubscriptionType](docs/GETSubscriptionType.md)
- [GETSubscriptionTypeWithSuccess](docs/GETSubscriptionTypeWithSuccess.md)
- [GETTaxationItemType](docs/GETTaxationItemType.md)
- [GETTaxationItemTypewithSuccess](docs/GETTaxationItemTypewithSuccess.md)
- [GETUsageType](docs/GETUsageType.md)
- [GetCreditMemoAmountBreakdownByOrderResponse](docs/GetCreditMemoAmountBreakdownByOrderResponse.md)
- [GetInvoiceAmountBreakdownByOrderResponse](docs/GetInvoiceAmountBreakdownByOrderResponse.md)
- [GetOrderBillingInfoResponseType](docs/GetOrderBillingInfoResponseType.md)
- [GetOrderRatedResultResponseType](docs/GetOrderRatedResultResponseType.md)
- [GetOrderResponse](docs/GetOrderResponse.md)
- [GetOrderResponseForEvergreen](docs/GetOrderResponseForEvergreen.md)
- [GetOrdersResponse](docs/GetOrdersResponse.md)
- [GetProductFeatureType](docs/GetProductFeatureType.md)
- [GetSubscriptionTermInfoResponseType](docs/GetSubscriptionTermInfoResponseType.md)
- [InvoiceDataInvoice](docs/InvoiceDataInvoice.md)
- [InvoiceItem](docs/InvoiceItem.md)
- [POSTAccountType](docs/POSTAccountType.md)
- [POSTAccountTypeBillToContact](docs/POSTAccountTypeBillToContact.md)
- [POSTAccountTypeSoldToContact](docs/POSTAccountTypeSoldToContact.md)
- [POSTAccountTypeSubscription](docs/POSTAccountTypeSubscription.md)
- [POSTAccountingCodeType](docs/POSTAccountingCodeType.md)
- [POSTAccountingPeriodType](docs/POSTAccountingPeriodType.md)
- [POSTJournalEntryItemType](docs/POSTJournalEntryItemType.md)
- [POSTJournalEntryType](docs/POSTJournalEntryType.md)
- [POSTPaymentMethodRequest](docs/POSTPaymentMethodRequest.md)
- [POSTPaymentMethodResponse](docs/POSTPaymentMethodResponse.md)
- [POSTRevenueScheduleByChargeType](docs/POSTRevenueScheduleByChargeType.md)
- [POSTRevenueScheduleByChargeTypeRevenueEvent](docs/POSTRevenueScheduleByChargeTypeRevenueEvent.md)
- [POSTRevenueScheduleByDateRangeType](docs/POSTRevenueScheduleByDateRangeType.md)
- [POSTRevenueScheduleByDateRangeTypeRevenueEvent](docs/POSTRevenueScheduleByDateRangeTypeRevenueEvent.md)
- [POSTRevenueScheduleByTransactionRatablyType](docs/POSTRevenueScheduleByTransactionRatablyType.md)
- [POSTRevenueScheduleByTransactionRatablyTypeRevenueEvent](docs/POSTRevenueScheduleByTransactionRatablyTypeRevenueEvent.md)
- [POSTRevenueScheduleByTransactionType](docs/POSTRevenueScheduleByTransactionType.md)
- [POSTRevenueScheduleByTransactionTypeRevenueEvent](docs/POSTRevenueScheduleByTransactionTypeRevenueEvent.md)
- [POSTScCreateType](docs/POSTScCreateType.md)
- [POSTSrpCreateType](docs/POSTSrpCreateType.md)
- [POSTSubscriptionPreviewType](docs/POSTSubscriptionPreviewType.md)
- [POSTSubscriptionPreviewTypePreviewAccountInfo](docs/POSTSubscriptionPreviewTypePreviewAccountInfo.md)
- [POSTSubscriptionType](docs/POSTSubscriptionType.md)
- [POSTTaxationItemForCMType](docs/POSTTaxationItemForCMType.md)
- [POSTTaxationItemForDMType](docs/POSTTaxationItemForDMType.md)
- [PUTAccountType](docs/PUTAccountType.md)
- [PUTAccountTypeBillToContact](docs/PUTAccountTypeBillToContact.md)
- [PUTAccountTypeSoldToContact](docs/PUTAccountTypeSoldToContact.md)
- [PUTAccountingCodeType](docs/PUTAccountingCodeType.md)
- [PUTAccountingPeriodType](docs/PUTAccountingPeriodType.md)
- [PUTAllocateManuallyType](docs/PUTAllocateManuallyType.md)
- [PUTBasicSummaryJournalEntryType](docs/PUTBasicSummaryJournalEntryType.md)
- [PUTCreditMemoItemType](docs/PUTCreditMemoItemType.md)
- [PUTCreditMemoType](docs/PUTCreditMemoType.md)
- [PUTDebitMemoItemType](docs/PUTDebitMemoItemType.md)
- [PUTDebitMemoType](docs/PUTDebitMemoType.md)
- [PUTJournalEntryItemType](docs/PUTJournalEntryItemType.md)
- [PUTOrderTriggerDatesResponseType](docs/PUTOrderTriggerDatesResponseType.md)
- [PUTRSBasicInfoType](docs/PUTRSBasicInfoType.md)
- [PUTRSTermType](docs/PUTRSTermType.md)
- [PUTRefundType](docs/PUTRefundType.md)
- [PUTScAddType](docs/PUTScAddType.md)
- [PUTScUpdateType](docs/PUTScUpdateType.md)
- [PUTSpecificDateAllocationType](docs/PUTSpecificDateAllocationType.md)
- [PUTSrpAddType](docs/PUTSrpAddType.md)
- [PUTSrpUpdateType](docs/PUTSrpUpdateType.md)
- [PUTSubscriptionType](docs/PUTSubscriptionType.md)
- [PUTTaxationItemType](docs/PUTTaxationItemType.md)
- [PostNonRefRefundType](docs/PostNonRefRefundType.md)
- [PostOrderPreviewResponseType](docs/PostOrderPreviewResponseType.md)
- [PostOrderResponseType](docs/PostOrderResponseType.md)
- [PostRefundType](docs/PostRefundType.md)
- [ProxyCreateAccount](docs/ProxyCreateAccount.md)
- [ProxyCreateContact](docs/ProxyCreateContact.md)
- [ProxyCreateInvoiceAdjustment](docs/ProxyCreateInvoiceAdjustment.md)
- [ProxyCreatePayment](docs/ProxyCreatePayment.md)
- [ProxyCreateProduct](docs/ProxyCreateProduct.md)
- [ProxyCreateProductRatePlan](docs/ProxyCreateProductRatePlan.md)
- [ProxyCreateProductRatePlanCharge](docs/ProxyCreateProductRatePlanCharge.md)
- [ProxyCreateRefund](docs/ProxyCreateRefund.md)
- [ProxyCreateTaxationItem](docs/ProxyCreateTaxationItem.md)
- [ProxyCreateUsage](docs/ProxyCreateUsage.md)
- [ProxyGetAccount](docs/ProxyGetAccount.md)
- [ProxyGetAmendment](docs/ProxyGetAmendment.md)
- [ProxyGetContact](docs/ProxyGetContact.md)
- [ProxyGetCreditBalanceAdjustment](docs/ProxyGetCreditBalanceAdjustment.md)
- [ProxyGetFeature](docs/ProxyGetFeature.md)
- [ProxyGetInvoice](docs/ProxyGetInvoice.md)
- [ProxyGetInvoiceAdjustment](docs/ProxyGetInvoiceAdjustment.md)
- [ProxyGetInvoiceItem](docs/ProxyGetInvoiceItem.md)
- [ProxyGetInvoiceItemAdjustment](docs/ProxyGetInvoiceItemAdjustment.md)
- [ProxyGetPayment](docs/ProxyGetPayment.md)
- [ProxyGetProduct](docs/ProxyGetProduct.md)
- [ProxyGetProductFeature](docs/ProxyGetProductFeature.md)
- [ProxyGetProductRatePlan](docs/ProxyGetProductRatePlan.md)
- [ProxyGetProductRatePlanCharge](docs/ProxyGetProductRatePlanCharge.md)
- [ProxyGetRatePlan](docs/ProxyGetRatePlan.md)
- [ProxyGetRatePlanCharge](docs/ProxyGetRatePlanCharge.md)
- [ProxyGetRefund](docs/ProxyGetRefund.md)
- [ProxyGetSubscription](docs/ProxyGetSubscription.md)
- [ProxyGetSubscriptionProductFeature](docs/ProxyGetSubscriptionProductFeature.md)
- [ProxyGetTaxationItem](docs/ProxyGetTaxationItem.md)
- [ProxyGetUsage](docs/ProxyGetUsage.md)
- [ProxyModifyAccount](docs/ProxyModifyAccount.md)
- [ProxyModifyAmendment](docs/ProxyModifyAmendment.md)
- [ProxyModifyContact](docs/ProxyModifyContact.md)
- [ProxyModifyInvoice](docs/ProxyModifyInvoice.md)
- [ProxyModifyInvoiceAdjustment](docs/ProxyModifyInvoiceAdjustment.md)
- [ProxyModifyPayment](docs/ProxyModifyPayment.md)
- [ProxyModifyProduct](docs/ProxyModifyProduct.md)
- [ProxyModifyProductRatePlan](docs/ProxyModifyProductRatePlan.md)
- [ProxyModifyProductRatePlanCharge](docs/ProxyModifyProductRatePlanCharge.md)
- [ProxyModifyRefund](docs/ProxyModifyRefund.md)
- [ProxyModifySubscription](docs/ProxyModifySubscription.md)
- [ProxyModifyTaxationItem](docs/ProxyModifyTaxationItem.md)
- [ProxyModifyUsage](docs/ProxyModifyUsage.md)
- [PutInvoiceResponseType](docs/PutInvoiceResponseType.md)
- [RatePlanChargeDataRatePlanCharge](docs/RatePlanChargeDataRatePlanCharge.md)
- [RatePlanDataRatePlan](docs/RatePlanDataRatePlan.md)
- [RecurringFlatFeePricingOverride](docs/RecurringFlatFeePricingOverride.md)
- [RecurringFlatFeePricingUpdate](docs/RecurringFlatFeePricingUpdate.md)
- [RecurringPerUnitPricingOverride](docs/RecurringPerUnitPricingOverride.md)
- [RecurringPerUnitPricingUpdate](docs/RecurringPerUnitPricingUpdate.md)
- [RecurringTieredPricingOverride](docs/RecurringTieredPricingOverride.md)
- [RecurringTieredPricingUpdate](docs/RecurringTieredPricingUpdate.md)
- [RecurringVolumePricingOverride](docs/RecurringVolumePricingOverride.md)
- [RecurringVolumePricingUpdate](docs/RecurringVolumePricingUpdate.md)
- [RevenueScheduleItemType](docs/RevenueScheduleItemType.md)
- [SoldToContact](docs/SoldToContact.md)
- [SubscribeRequestAccount](docs/SubscribeRequestAccount.md)
- [SubscribeRequestBillToContact](docs/SubscribeRequestBillToContact.md)
- [SubscribeRequestSoldToContact](docs/SubscribeRequestSoldToContact.md)
- [SubscribeRequestSubscriptionDataSubscription](docs/SubscribeRequestSubscriptionDataSubscription.md)
- [SubscriptionProductFeature](docs/SubscriptionProductFeature.md)
- [UpdatePaymentType](docs/UpdatePaymentType.md)
- [UsageFlatFeePricingOverride](docs/UsageFlatFeePricingOverride.md)
- [UsageFlatFeePricingUpdate](docs/UsageFlatFeePricingUpdate.md)
- [UsageOveragePricingOverride](docs/UsageOveragePricingOverride.md)
- [UsageOveragePricingUpdate](docs/UsageOveragePricingUpdate.md)
- [UsagePerUnitPricingOverride](docs/UsagePerUnitPricingOverride.md)
- [UsagePerUnitPricingUpdate](docs/UsagePerUnitPricingUpdate.md)
- [UsageTieredPricingOverride](docs/UsageTieredPricingOverride.md)
- [UsageTieredPricingUpdate](docs/UsageTieredPricingUpdate.md)
- [UsageTieredWithOveragePricingOverride](docs/UsageTieredWithOveragePricingOverride.md)
- [UsageTieredWithOveragePricingUpdate](docs/UsageTieredWithOveragePricingUpdate.md)
- [UsageVolumePricingOverride](docs/UsageVolumePricingOverride.md)
- [UsageVolumePricingUpdate](docs/UsageVolumePricingUpdate.md)
- [ZObjectUpdate](docs/ZObjectUpdate.md)
## Documentation for Authorization
All endpoints do not require authorization.
Authentication schemes defined for the API:
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
## Author
<EMAIL>
<file_sep>
# GetOrderResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**order** | [**Order**](Order.md) | | [optional]
<file_sep>
# GETSubscriptionRatePlanType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **String** | Rate plan ID. | [optional]
**lastChangeType** | **String** | The last amendment on the rate plan. Possible Values: * `Add` * `Update` * `Remove` | [optional]
**productId** | **String** | | [optional]
**productName** | **String** | | [optional]
**productRatePlanId** | **String** | | [optional]
**productSku** | **String** | The unique SKU for the product. | [optional]
**ratePlanCharges** | [**List<GETSubscriptionRatePlanChargesType>**](GETSubscriptionRatePlanChargesType.md) | Container for one or more charges. | [optional]
**ratePlanName** | **String** | Name of the rate plan. | [optional]
**subscriptionProductFeatures** | [**List<GETSubscriptionProductFeatureType>**](GETSubscriptionProductFeatureType.md) | Container for one or more features. Only available when the following settings are enabled: * The Entitlements feature in your tenant. * The Enable Feature Specification in Product and Subscriptions setting in Zuora Billing Settings | [optional]
<file_sep>
# GETDiscountApplyDetailsType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**appliedProductRatePlanChargeId** | **String** | The ID of the product rate plan charge that the discount rate plan charge applies to. | [optional]
**appliedProductRatePlanId** | **String** | The ID of the product rate plan that the discount rate plan charge applies to. | [optional]
<file_sep># TransactionsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETTransactionInvoice**](TransactionsApi.md#gETTransactionInvoice) | **GET** /v1/transactions/invoices/accounts/{account-key} | Get invoices
[**gETTransactionPayment**](TransactionsApi.md#gETTransactionPayment) | **GET** /v1/transactions/payments/accounts/{account-key} | Get payments
<a name="gETTransactionInvoice"></a>
# **gETTransactionInvoice**
> GETInvoiceFileWrapper gETTransactionInvoice(accountKey, zuoraEntityIds, pageSize)
Get invoices
Retrieves invoices for a specified account. Invoices are returned in reverse chronological order by **updatedDate**.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TransactionsApi;
TransactionsApi apiInstance = new TransactionsApi();
String accountKey = "accountKey_example"; // String | Account number or account ID.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETInvoiceFileWrapper result = apiInstance.gETTransactionInvoice(accountKey, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TransactionsApi#gETTransactionInvoice");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Account number or account ID. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETInvoiceFileWrapper**](GETInvoiceFileWrapper.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETTransactionPayment"></a>
# **gETTransactionPayment**
> GETPaymentsType gETTransactionPayment(accountKey, zuoraEntityIds, pageSize)
Get payments
Retrieves payments for a specified account. Payments are returned in reverse chronological order by **updatedDate**.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TransactionsApi;
TransactionsApi apiInstance = new TransactionsApi();
String accountKey = "accountKey_example"; // String | Account number or account ID.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETPaymentsType result = apiInstance.gETTransactionPayment(accountKey, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TransactionsApi#gETTransactionPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Account number or account ID. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETPaymentsType**](GETPaymentsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># RevenueItemsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETRevenueItemsByChargeRevenueEventNumber**](RevenueItemsApi.md#gETRevenueItemsByChargeRevenueEventNumber) | **GET** /v1/revenue-items/revenue-events/{event-number} | Get revenue items by revenue event number
[**gETRevenueItemsByChargeRevenueSummaryNumber**](RevenueItemsApi.md#gETRevenueItemsByChargeRevenueSummaryNumber) | **GET** /v1/revenue-items/charge-revenue-summaries/{crs-number} | Get revenue items by charge revenue summary number
[**gETRevenueItemsByRevenueSchedule**](RevenueItemsApi.md#gETRevenueItemsByRevenueSchedule) | **GET** /v1/revenue-items/revenue-schedules/{rs-number} | Get revenue items by revenue schedule
[**pUTCustomFieldsonRevenueItemsByRevenueEvent**](RevenueItemsApi.md#pUTCustomFieldsonRevenueItemsByRevenueEvent) | **PUT** /v1/revenue-items/revenue-events/{event-number} | Update custom fields on revenue items by revenue event number
[**pUTCustomFieldsonRevenueItemsByRevenueSchedule**](RevenueItemsApi.md#pUTCustomFieldsonRevenueItemsByRevenueSchedule) | **PUT** /v1/revenue-items/revenue-schedules/{rs-number} | Update custom fields on revenue items by revenue schedule number
<a name="gETRevenueItemsByChargeRevenueEventNumber"></a>
# **gETRevenueItemsByChargeRevenueEventNumber**
> GETRevenueItemsType gETRevenueItemsByChargeRevenueEventNumber(eventNumber, zuoraEntityIds, pageSize)
Get revenue items by revenue event number
This REST API reference describes how to get the details of each revenue item in a revenue event by specifying the revenue event number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueItemsApi;
RevenueItemsApi apiInstance = new RevenueItemsApi();
String eventNumber = "eventNumber_example"; // String | The number associated with the revenue event.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 300; // Integer | Number of rows returned per page.
try {
GETRevenueItemsType result = apiInstance.gETRevenueItemsByChargeRevenueEventNumber(eventNumber, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueItemsApi#gETRevenueItemsByChargeRevenueEventNumber");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**eventNumber** | **String**| The number associated with the revenue event. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 300]
### Return type
[**GETRevenueItemsType**](GETRevenueItemsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRevenueItemsByChargeRevenueSummaryNumber"></a>
# **gETRevenueItemsByChargeRevenueSummaryNumber**
> GETRevenueItemsType gETRevenueItemsByChargeRevenueSummaryNumber(crsNumber, zuoraEntityIds, pageSize)
Get revenue items by charge revenue summary number
This REST API reference describes how to get the details for each revenue item in a charge revenue summary by specifying the charge revenue summary number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueItemsApi;
RevenueItemsApi apiInstance = new RevenueItemsApi();
String crsNumber = "crsNumber_example"; // String | The charge revenue summary number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 300; // Integer | Number of rows returned per page.
try {
GETRevenueItemsType result = apiInstance.gETRevenueItemsByChargeRevenueSummaryNumber(crsNumber, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueItemsApi#gETRevenueItemsByChargeRevenueSummaryNumber");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**crsNumber** | **String**| The charge revenue summary number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 300]
### Return type
[**GETRevenueItemsType**](GETRevenueItemsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRevenueItemsByRevenueSchedule"></a>
# **gETRevenueItemsByRevenueSchedule**
> GETRsRevenueItemsType gETRevenueItemsByRevenueSchedule(rsNumber, zuoraEntityIds, pageSize)
Get revenue items by revenue schedule
This REST API reference describes how to get the details for each revenue items in a revenue schedule by specifying the revenue schedule number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueItemsApi;
RevenueItemsApi apiInstance = new RevenueItemsApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 300; // Integer | Number of rows returned per page.
try {
GETRsRevenueItemsType result = apiInstance.gETRevenueItemsByRevenueSchedule(rsNumber, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueItemsApi#gETRevenueItemsByRevenueSchedule");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 300]
### Return type
[**GETRsRevenueItemsType**](GETRsRevenueItemsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTCustomFieldsonRevenueItemsByRevenueEvent"></a>
# **pUTCustomFieldsonRevenueItemsByRevenueEvent**
> CommonResponseType pUTCustomFieldsonRevenueItemsByRevenueEvent(eventNumber, request, zuoraEntityIds)
Update custom fields on revenue items by revenue event number
This REST API reference describes how to update custom fields on revenue items by specifying the revenue event number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueItemsApi;
RevenueItemsApi apiInstance = new RevenueItemsApi();
String eventNumber = "eventNumber_example"; // String | The number associated with the revenue event.
PUTEventRIDetailType request = new PUTEventRIDetailType(); // PUTEventRIDetailType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTCustomFieldsonRevenueItemsByRevenueEvent(eventNumber, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueItemsApi#pUTCustomFieldsonRevenueItemsByRevenueEvent");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**eventNumber** | **String**| The number associated with the revenue event. |
**request** | [**PUTEventRIDetailType**](PUTEventRIDetailType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTCustomFieldsonRevenueItemsByRevenueSchedule"></a>
# **pUTCustomFieldsonRevenueItemsByRevenueSchedule**
> CommonResponseType pUTCustomFieldsonRevenueItemsByRevenueSchedule(rsNumber, request, zuoraEntityIds)
Update custom fields on revenue items by revenue schedule number
This REST API reference describes how to update custom fields on revenue Items by specifying the revenue schedule number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueItemsApi;
RevenueItemsApi apiInstance = new RevenueItemsApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
PUTScheduleRIDetailType request = new PUTScheduleRIDetailType(); // PUTScheduleRIDetailType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTCustomFieldsonRevenueItemsByRevenueSchedule(rsNumber, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueItemsApi#pUTCustomFieldsonRevenueItemsByRevenueSchedule");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**request** | [**PUTScheduleRIDetailType**](PUTScheduleRIDetailType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# Account
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountNumber** | **String** | | [optional]
**autoPay** | **Boolean** | Specifies whether future payments are to be automatically billed when they are due. Possible values are `true`, `false`. | [optional]
**batch** | **String** | | [optional]
**billCycleDay** | **Integer** | Day of the month that the account prefers billing periods to begin on. If set to 0, the bill cycle day will be set as \"AutoSet\". |
**billToContact** | [**BillToContact**](BillToContact.md) | |
**communicationProfileId** | **String** | | [optional]
**creditCard** | [**CreditCard**](CreditCard.md) | | [optional]
**creditMemoTemplateId** | **String** | **Note**: This field is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). The unique ID of the credit memo template, configured in **Billing Settings** > **Manage Billing Document Configuration** through the Zuora UI. For example, 2c92c08a6246fdf101626b1b3fe0144b. | [optional]
**crmId** | **String** | | [optional]
**currency** | **String** | 3 uppercase character currency code |
**customFields** | [**AccountObjectCustomFields**](AccountObjectCustomFields.md) | | [optional]
**debitMemoTemplateId** | **String** | **Note**: This field is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). The unique ID of the debit memo template, configured in **Billing Settings** > **Manage Billing Document Configuration** through the Zuora UI. For example, 2c92c08d62470a8501626b19d24f19e2. | [optional]
**hpmCreditCardPaymentMethodId** | **String** | | [optional]
**invoiceDeliveryPrefsEmail** | **Boolean** | Specifies whether to turn on the invoice delivery method 'Email' for the new account. Values are: * `true` (default). Turn on the invoice delivery method 'Email' for the new account. * `false`. Turn off the invoice delivery method 'Email' for the new account. | [optional]
**invoiceDeliveryPrefsPrint** | **Boolean** | Specifies whether to turn on the invoice delivery method 'Print' for the new account. Values are: * `true`. Turn on the invoice delivery method 'Print' for the new account. * `false` (default). Turn off the invoice delivery method 'Print' for the new account. | [optional]
**invoiceTemplateId** | **String** | | [optional]
**name** | **String** | |
**notes** | **String** | | [optional]
**parentId** | **String** | Identifier of the parent customer account for this Account object. Use this field if you have customer hierarchy enabled. | [optional]
**paymentGateway** | **String** | | [optional]
**paymentTerm** | **String** | | [optional]
**soldToContact** | [**SoldToContact**](SoldToContact.md) | | [optional]
**taxInfo** | [**TaxInfo**](TaxInfo.md) | | [optional]
<file_sep>
# PUTOrderActionTriggerDatesRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**subscriptions** | [**List<PUTOrderActionTriggerDatesRequestTypeSubscriptions>**](PUTOrderActionTriggerDatesRequestTypeSubscriptions.md) | | [optional]
<file_sep>
# GetSubscriptionTermInfoResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**nextPage** | **String** | The URL of the next page of terms. | [optional]
**terms** | [**List<Term>**](Term.md) | | [optional]
<file_sep>
# DebitMemoFromChargeDetailType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The amount of the debit memo item. This field is in Zuora REST API version control. Supported minor versions are `224.0` and later. To use this field in the method, you must set the `zuora-version` parameter to the request header. | [optional]
**chargeId** | **String** | The ID of the product rate plan charge that the debit memo is created from. |
**comment** | **String** | Comments about the product rate plan charge. | [optional]
**financeInformation** | [**DebitMemoFromChargeDetailTypeFinanceInformation**](DebitMemoFromChargeDetailTypeFinanceInformation.md) | | [optional]
**memoItemAmount** | **Double** | The amount of the debit memo item. This field is in Zuora REST API version control. Supported minor versions are `223.0` and earlier. | [optional]
<file_sep>
# RevenueScheduleItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountingPeriodName** | **String** | Name of the accounting period. The open-ended accounting period is named `Open-Ended`. |
<file_sep>
# TimeSlicedNetMetrics
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**discountChargeNumber** | **String** | | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | | [optional]
**generatedReason** | [**GeneratedReasonEnum**](#GeneratedReasonEnum) | Specify the reason why the metrics are generated by the certain order action. | [optional]
**invoiceOwner** | **String** | The acount number of the billing account that is billed for the subscription. | [optional]
**orderItemId** | **String** | The ID of the order item referenced by the order metrics. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | | [optional]
**subscriptionOwner** | **String** | The acount number of the billing account that owns the subscription. | [optional]
**termNumber** | [**BigDecimal**](BigDecimal.md) | | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Indicates whether this metrics is for a regular charge or a discount charge. | [optional]
<a name="GeneratedReasonEnum"></a>
## Enum: GeneratedReasonEnum
Name | Value
---- | -----
INCREASEQUANTITY | "IncreaseQuantity"
DECREASEQUANTITY | "DecreaseQuantity"
CHANGEPRICE | "ChangePrice"
EXTENSION | "Extension"
CONTRACTION | "Contraction"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
REGULAR | "Regular"
DISCOUNT | "Discount"
<file_sep>
# POSTOrderPreviewRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFields** | [**OrderObjectCustomFields**](OrderObjectCustomFields.md) | | [optional]
**existingAccountNumber** | **String** | The account number that this order will be created under. It can be either the accountNumber or the account info. It will return an error if both are specified. Note that invoice owner account of the subscriptions included in this order should be the same with the account of the order. | [optional]
**orderDate** | [**LocalDate**](LocalDate.md) | The date when the order is signed. All of the order actions under this order will use this order date as the contract effective date. |
**orderNumber** | **String** | The order number of this order. | [optional]
**previewAccountInfo** | [**PreviewAccountInfo**](PreviewAccountInfo.md) | | [optional]
**previewOptions** | [**PreviewOptions**](PreviewOptions.md) | |
**subscriptions** | [**List<POSTOrderPreviewRequestTypeSubscriptions>**](POSTOrderPreviewRequestTypeSubscriptions.md) | Each item includes a set of order actions, which will be applied to the same base subscription. |
<file_sep>
# OneTimeTieredPricingOverride
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**quantity** | [**BigDecimal**](BigDecimal.md) | Number of units purchased. | [optional]
**tiers** | [**List<ChargeTier>**](ChargeTier.md) | List of cumulative pricing tiers in the charge. | [optional]
<file_sep>
# GETTaxationItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**createdById** | **String** | The ID of the Zuora user who created the taxation item. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the taxation item was created in the Zuora system, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**exemptAmount** | **Double** | The amount of taxes or VAT for which the customer has an exemption. | [optional]
**financeInformation** | [**GETTaxationItemTypeFinanceInformation**](GETTaxationItemTypeFinanceInformation.md) | | [optional]
**id** | **String** | The ID of the taxation item. | [optional]
**jurisdiction** | **String** | The jurisdiction that applies the tax or VAT. This value is typically a state, province, county, or city. | [optional]
**locationCode** | **String** | The identifier for the location based on the value of the `taxCode` field. | [optional]
**memoItemId** | **String** | The ID of the credit or debit memo associated with the taxation item. | [optional]
**name** | **String** | The name of the taxation item. | [optional]
**sourceTaxItemId** | **String** | The ID of the taxation item of the invoice, which the credit or debit memo is created from. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**taxAmount** | **Double** | The amount of the tax applied to the credit or debit memo. | [optional]
**taxCode** | **String** | The tax code identifies which tax rules and tax rates to apply to a specific credit or debit memo. | [optional]
**taxCodeDescription** | **String** | The description of the tax code. | [optional]
**taxDate** | [**LocalDate**](LocalDate.md) | The date when the tax is applied to the credit or debit memo. | [optional]
**taxRate** | **Double** | The tax rate applied to the credit or debit memo. | [optional]
**taxRateDescription** | **String** | The description of the tax rate. | [optional]
**taxRateType** | [**TaxRateTypeEnum**](#TaxRateTypeEnum) | The type of the tax rate applied to the credit or debit memo. | [optional]
**updatedById** | **String** | The ID of the Zuora user who last updated the taxation item. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the taxation item was last updated, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
<a name="TaxRateTypeEnum"></a>
## Enum: TaxRateTypeEnum
Name | Value
---- | -----
PERCENTAGE | "Percentage"
FLATFEE | "FlatFee"
<file_sep>
# AmendRequestAmendOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**applyCreditBalance** | **Boolean** | | [optional]
**electronicPaymentOptions** | [**ElectronicPaymentOptions**](ElectronicPaymentOptions.md) | | [optional]
**externalPaymentOptions** | [**ExternalPaymentOptions**](ExternalPaymentOptions.md) | | [optional]
**generateInvoice** | **Boolean** | | [optional]
**invoiceProcessingOptions** | [**InvoiceProcessingOptions**](InvoiceProcessingOptions.md) | | [optional]
**processPayments** | **Boolean** | | [optional]
<file_sep>
# FilterRuleParameterDefinition
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**description** | **String** | | [optional]
**displayName** | **String** | The display name of the parameter. | [optional]
**options** | **List<String>** | The option values of the parameter. | [optional]
**valueType** | [**ValueTypeEnum**](#ValueTypeEnum) | The type of the value. | [optional]
<a name="ValueTypeEnum"></a>
## Enum: ValueTypeEnum
Name | Value
---- | -----
STRING | "STRING"
BYTE | "BYTE"
SHORT | "SHORT"
CHARACTER | "CHARACTER"
INTEGER | "INTEGER"
LONG | "LONG"
FLOAT | "FLOAT"
DOUBLE | "DOUBLE"
BOOLEAN | "BOOLEAN"
BIG_INTEGER | "BIG_INTEGER"
BIG_DECIMAL | "BIG_DECIMAL"
LOCAL_DATE | "LOCAL_DATE"
LOCAL_DATE_TIME | "LOCAL_DATE_TIME"
TIMESTAMP | "TIMESTAMP"
BYTE_ARRAY | "BYTE_ARRAY"
SHORT_ARRAY | "SHORT_ARRAY"
CHARACTER_ARRAY | "CHARACTER_ARRAY"
INTEGER_ARRAY | "INTEGER_ARRAY"
FLOAT_ARRAY | "FLOAT_ARRAY"
DOUBLE_ARRAY | "DOUBLE_ARRAY"
BOOLEAN_ARRAY | "BOOLEAN_ARRAY"
STRING_ARRAY | "STRING_ARRAY"
BIG_INTEGER_ARRAY | "BIG_INTEGER_ARRAY"
BIG_DECIMAL_ARRAY | "BIG_DECIMAL_ARRAY"
LOCAL_DATE_ARRAY | "LOCAL_DATE_ARRAY"
LOCAL_DATE_TIME_ARRAY | "LOCAL_DATE_TIME_ARRAY"
TIMESTAMP_ARRAY | "TIMESTAMP_ARRAY"
<file_sep>
# GetOrderBillingInfoResponseTypeBillingInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**billedAmount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**currency** | **String** | Currency code. | [optional]
**tcb** | [**BigDecimal**](BigDecimal.md) | Total contracted billing of this order. | [optional]
**unbilledAmount** | [**BigDecimal**](BigDecimal.md) | | [optional]
<file_sep>
# GETCreditMemoType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the credit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the credit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The ID of the customer account associated with the credit memo. | [optional]
**amount** | **Double** | The total amount of the credit memo. | [optional]
**appliedAmount** | **Double** | The applied amount of the credit memo. | [optional]
**autoApplyUponPosting** | **Boolean** | Whether the credit memo automatically applies to the invoice upon posting. | [optional]
**cancelledById** | **String** | The ID of the Zuora user who cancelled the credit memo. | [optional]
**cancelledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the credit memo was cancelled, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**comment** | **String** | Comments about the credit memo. | [optional]
**createdById** | **String** | The ID of the Zuora user who created the credit memo. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the credit memo was created, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 15:31:10. | [optional]
**creditMemoDate** | [**LocalDate**](LocalDate.md) | The date when the credit memo takes effect, in `yyyy-mm-dd` format. For example, 2017-05-20. | [optional]
**currency** | **String** | A currency defined in the web-based UI administrative settings. | [optional]
**excludeFromAutoApplyRules** | **Boolean** | Whether the credit memo is excluded from the rule of automatically applying credit memos to invoices. | [optional]
**id** | **String** | The unique ID of the credit memo. | [optional]
**latestPDFFileId** | **String** | The ID of the latest PDF file generated for the credit memo. | [optional]
**number** | **String** | The unique identification number of the credit memo. | [optional]
**postedById** | **String** | The ID of the Zuora user who posted the credit memo. | [optional]
**postedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the credit memo was posted, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. | [optional]
**referredInvoiceId** | **String** | The ID of a referred invoice. | [optional]
**refundAmount** | **Double** | The amount of the refund on the credit memo. | [optional]
**source** | **String** | The source of the credit memo. Possible values: - `BillRun`: The credit memo is generated by a bill run. - `API`: The credit memo is created by calling the [Invoice and collect](https://www.zuora.com/developer/api-reference/#operation/POST_TransactionInvoicePayment) operation. - `ApiSubscribe`: The credit memo is created by calling the [Create subscription](https://www.zuora.com/developer/api-reference/#operation/POST_Subscription) and [Create account](https://www.zuora.com/developer/api-reference/#operation/POST_Account) operation. - `ApiAmend`: The credit memo is created by calling the [Update subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription) operation. - `AdhocFromPrpc`: The credit memo is created from a product rate plan charge through the Zuora UI or by calling the [Create credit memo from charge](https://www.zuora.com/developer/api-reference/#operation/POST_CreditMemoFromPrpc) operation. - `AdhocFromInvoice`: The credit memo is created from an invoice or created by reversing an invoice. You can create a credit memo from an invoice through the Zuora UI or by calling the [Create credit memo from invoice](https://www.zuora.com/developer/api-reference/#operation/POST_CreditMemoFromInvoice) operation. You can create a credit memo by reversing an invoice through the Zuora UI or by calling the [Reverse invoice](https://www.zuora.com/developer/api-reference/#operation/PUT_ReverseInvoice) operation. | [optional]
**sourceId** | **String** | The ID of the credit memo source. If a credit memo is generated from a bill run, the value is the number of the corresponding bill run. Otherwise, the value is `null`. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the credit memo. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | The target date for the credit memo, in `yyyy-mm-dd` format. For example, 2017-07-20. | [optional]
**taxAmount** | **Double** | The amount of taxation. | [optional]
**totalTaxExemptAmount** | **Double** | The total amount of taxes or VAT for which the customer has an exemption. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the credit memo was transferred to an external accounting system. Use this field for integration with accounting systems, such as NetSuite. | [optional]
**unappliedAmount** | **Double** | The unapplied amount of the credit memo. | [optional]
**updatedById** | **String** | The ID of the Zuora user who last updated the credit memo. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the credit memo was last updated, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 15:36:10. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
DRAFT | "Draft"
POSTED | "Posted"
CANCELED | "Canceled"
ERROR | "Error"
PENDINGFORTAX | "PendingForTax"
GENERATING | "Generating"
CANCELINPROGRESS | "CancelInProgress"
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
NO | "No"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# EventTrigger
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**active** | **Boolean** | The status of the trigger. | [optional]
**baseObject** | **String** | The base object that the trigger rule is defined upon. Should be specified in the pattern: ^[A-Z][\\\\w\\\\-]*$ | [optional]
**condition** | **String** | The JEXL expression to be evaluated against object changes. See above for more information and an example. | [optional]
**description** | **String** | The description of the trigger. | [optional]
**eventType** | [**EventType**](EventType.md) | | [optional]
**id** | [**UUID**](UUID.md) | | [optional]
<file_sep>
# ProxyUnauthorizedResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**message** | **String** | Error message. If the error message is \"Authentication error\", ensure that the `Authorization` request header contains valid authentication credentials, then retry the request. See [Authentication](https://www.zuora.com/developer/api-reference/#section/Authentication) for more information. If the error message is \"Failed to get user info\", retry the request. | [optional]
<file_sep>
# PreviewOrderPricingUpdate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**discount** | [**DiscountPricingUpdate**](DiscountPricingUpdate.md) | | [optional]
**recurringFlatFee** | [**RecurringFlatFeePricingUpdate**](RecurringFlatFeePricingUpdate.md) | | [optional]
**recurringPerUnit** | [**RecurringPerUnitPricingUpdate**](RecurringPerUnitPricingUpdate.md) | | [optional]
**recurringTiered** | [**RecurringTieredPricingUpdate**](RecurringTieredPricingUpdate.md) | | [optional]
**recurringVolume** | [**RecurringVolumePricingUpdate**](RecurringVolumePricingUpdate.md) | | [optional]
**usageFlatFee** | [**UsageFlatFeePricingUpdate**](UsageFlatFeePricingUpdate.md) | | [optional]
**usageOverage** | [**UsageOveragePricingUpdate**](UsageOveragePricingUpdate.md) | | [optional]
**usagePerUnit** | [**UsagePerUnitPricingUpdate**](UsagePerUnitPricingUpdate.md) | | [optional]
**usageTiered** | [**UsageTieredPricingUpdate**](UsageTieredPricingUpdate.md) | | [optional]
**usageTieredWithOverage** | [**UsageTieredWithOveragePricingUpdate**](UsageTieredWithOveragePricingUpdate.md) | | [optional]
**usageVolume** | [**UsageVolumePricingUpdate**](UsageVolumePricingUpdate.md) | | [optional]
<file_sep>
# Amendment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**autoRenew** | **Boolean** | Determines whether the subscription is automatically renewed, or whether it expires at the end of the term and needs to be manually renewed. For amendment of type `TermsAndConditions`, this field is only required if you change the automatic renewal status of a subscription. **Values**: true, false | [optional]
**code** | **String** | A unique alphanumeric string that identifies the amendment. **Character limit**: 50 **Values**: one of the following: - `null` generates a value automatically - A string | [optional]
**contractEffectiveDate** | [**LocalDate**](LocalDate.md) | The date when the amendment's changes become effective for billing purposes. |
**createdById** | **String** | The user ID of the person who created the amendment. **Character limit**: 32 **Values**: automatically generated | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the amendment was created. **Values**: automatically generated | [optional]
**currentTerm** | **Long** | The length of the period for the current subscription term. This field can be updated when Status is `Draft`. This field is only required if the `Type` field is set to `TermsAndConditions` and `TermType` is set to `TERMED`. This field is not required if `TermType` is set to `EVERGREEN`. **Values**: a valid number | [optional]
**currentTermPeriodType** | **String** | The period type for the current subscription term. This field is only required if the `Type` field is set to `TermsAndConditions` and `TermType` is set to `TERMED`. This field is not required if `TermType` is set to `EVERGREEN`. **Values**: - `Month` (default) - `Year` - `Day` - `Week` **Note**: - This field can be updated when Status is `Draft`. - This field is used with the CurrentTerm field to specify the current subscription term. | [optional]
**customerAcceptanceDate** | [**LocalDate**](LocalDate.md) | The date when the customer accepts the amendment's changes to the subscription. Use this field if [Zuora is configured to require customer acceptance in Z-Billing](https://knowledgecenter.zuora.com/CB_Billing/W_Billing_and_Payments_Settings/Define_Default_Subscription_Settings). This field is only required if the `Status` field is set to `PendingAcceptance`. | [optional]
**description** | **String** | A description of the amendment. **Character limit**: 500 **Values**: maximum 500 characters | [optional]
**destinationAccountId** | **String** | The ID of the account that the subscription is being transferred to. **Character limit**: 32 **Values**: a valid account ID | [optional]
**destinationInvoiceOwnerId** | **String** | The ID of the invoice that the subscription is being transferred to. **Character limit**: 32 **Values**: a valid invoice ID | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the amendment's changes take effective. This field validates that the amendment's changes are within valid ranges of products and product rate plans. This field is only required if the `Type` field is set to `Cancellation`. | [optional]
**name** | **String** | The name of the amendment. **Character limit**: 100 **Values**: a string of 100 characters or fewer |
**ratePlanData** | [**AmendmentRatePlanData**](AmendmentRatePlanData.md) | | [optional]
**renewalSetting** | **String** | Specifies whether a termed subscription will remain termed or change to evergreen when it is renewed. This field is only required if the `TermType` field is set to `Termed`. **Values**: RENEW_WITH_SPECIFIC_TERM (default), RENEW_TO_EVERGREEN | [optional]
**renewalTerm** | **Long** | The term of renewal for the amended subscription. This field can be updated when Status is `Draft`. This field is only required if the `Type` field is set to `TermsAndConditions`. **Values:** a valid number | [optional]
**renewalTermPeriodType** | **String** | The period type for the subscription renewal term. This field can be updated when Status is `Draft`. **Required**: Only if the value of the Type field is set to `TermsAndConditions`. This field is used with the RenewalTerm field to specify the subscription renewal term. **Values**: - `Month` (default) - `Year` - `Day` - `Week` | [optional]
**serviceActivationDate** | [**LocalDate**](LocalDate.md) | The date when service is activated. Use this field if [Zuora is configured to require service activation in Z-Billing](https://knowledgecenter.zuora.com/CB_Billing/W_Billing_and_Payments_Settings/Define_Default_Subscription_Settings). This field is only required if the `Status` field is set to `PendingActivation`. | [optional]
**specificUpdateDate** | [**LocalDate**](LocalDate.md) | The date when the UpdateProduct amendment takes effect. This field is only applicable if there is already a future-dated UpdateProduct amendment on the subscription. For the UpdateProduct amendments, this field is only required if there is already a future-dated UpdateProduct amendment on the subscription. | [optional]
**status** | **String** | The status of the amendment. Type: string (enum) **Values**: one of the following: - Draft (default, if left null) - Pending Activation - Pending Acceptance - Completed | [optional]
**subscriptionId** | **String** | The ID of the subscription that the amendment changes. **Character limit**: 32 **Values**: a valid subscription ID |
**termStartDate** | [**LocalDate**](LocalDate.md) | The date when the new terms and conditions take effect. This field is only required if the `Type` field is set to `TermsAndConditions`. | [optional]
**termType** | **String** | Indicates if the subscription isTERMED or EVERGREEN. - A TERMED subscription has an expiration date, and must be manually renewed. - An EVERGREEN subscription doesn't have an expiration date, and must be manually ended. When as part of an amendment of type `TermsAndConditions`, this field is required to change the term type of a subscription. **Character limit**: 9 **Values**: TERMED, EVERGREEN | [optional]
**type** | **String** | The type of amendment. **Character limit**: 18 **Values**: one of the following: - Cancellation - NewProduct - OwnerTransfer - RemoveProduct - Renewal - UpdateProduct - TermsAndConditions - SuspendSubscription (This value is in **Limited Availability**.) - ResumeSubscription (This value is in **Limited Availability**.) |
**updatedById** | **String** | The ID of the user who last updated the amendment. **Character limit**: 32 **Values**: automatically generated | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the amendment was last updated. **Values**: automatically generated | [optional]
<file_sep>
# Term
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**endDate** | [**LocalDate**](LocalDate.md) | The end date of the term. | [optional]
**isEvergreen** | **Boolean** | Indicates whether the term is evergreen. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The start date of the term. | [optional]
**termNumber** | [**BigDecimal**](BigDecimal.md) | The term number. | [optional]
<file_sep>
# CancelSubscription
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cancellationEffectiveDate** | [**LocalDate**](LocalDate.md) | | [optional]
**cancellationPolicy** | [**CancellationPolicyEnum**](#CancellationPolicyEnum) | |
<a name="CancellationPolicyEnum"></a>
## Enum: CancellationPolicyEnum
Name | Value
---- | -----
ENDOFCURRENTTERM | "EndOfCurrentTerm"
ENDOFLASTINVOICEPERIOD | "EndOfLastInvoicePeriod"
SPECIFICDATE | "SpecificDate"
<file_sep>
# POSTDocumentPropertiesType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFileName** | **String** | The custom file name to use to generate new Word or PDF files for the billing document. | [optional]
**documentId** | **String** | The unique ID of a billing document that you want to create document properties for. | [optional]
**documentType** | [**DocumentTypeEnum**](#DocumentTypeEnum) | The type of the billing document. | [optional]
<a name="DocumentTypeEnum"></a>
## Enum: DocumentTypeEnum
Name | Value
---- | -----
INVOICE | "Invoice"
CREDITMEMO | "CreditMemo"
DEBITMEMO | "DebitMemo"
<file_sep># PaymentGatewaysApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETPaymentgateways**](PaymentGatewaysApi.md#gETPaymentgateways) | **GET** /v1/paymentgateways | Get payment gateways
<a name="gETPaymentgateways"></a>
# **gETPaymentgateways**
> GETPaymentGatwaysResponse gETPaymentgateways(zuoraEntityIds)
Get payment gateways
Retrieves the basic information about all the payment gateways.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentGatewaysApi;
PaymentGatewaysApi apiInstance = new PaymentGatewaysApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPaymentGatwaysResponse result = apiInstance.gETPaymentgateways(zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentGatewaysApi#gETPaymentgateways");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPaymentGatwaysResponse**](GETPaymentGatwaysResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# POSTBillingDocumentFilesDeletionJobRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountIds** | **List<String>** | Container for the IDs of the accounts that you want to create the billing document files deletion job for. | [optional]
<file_sep>
# ErrorResponseReasons
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**code** | **String** | The error code of response. | [optional]
**message** | **String** | The detail information of the error response | [optional]
<file_sep>
# SubscriptionRatedResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeRatedResults** | [**List<ChargeRatedResult>**](ChargeRatedResult.md) | The amount changes per regular charge, or per regular charge and the discount charge if there is discount charge. | [optional]
**subscriptionNumber** | **String** | | [optional]
<file_sep>
# PUTOrderTriggerDatesResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**accountNumber** | **String** | The account number for the order. | [optional]
**orderNumber** | **String** | The order number of the order updated. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | Status of the order. `Pending` is only applicable for an order that contains a `CreateSubscription` order action. | [optional]
**subscriptions** | [**List<PUTOrderTriggerDatesResponseTypeSubscriptions>**](PUTOrderTriggerDatesResponseTypeSubscriptions.md) | The subscriptions updated. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
COMPLETED | "Completed"
PENDING | "Pending"
<file_sep># MassUpdaterApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETMassUpdater**](MassUpdaterApi.md#gETMassUpdater) | **GET** /v1/bulk/{bulk-key} | Get mass action result
[**pOSTMassUpdater**](MassUpdaterApi.md#pOSTMassUpdater) | **POST** /v1/bulk | Perform mass action
[**pUTMassUpdater**](MassUpdaterApi.md#pUTMassUpdater) | **PUT** /v1/bulk/{bulk-key}/stop | Stop mass action
<a name="gETMassUpdater"></a>
# **gETMassUpdater**
> GETMassUpdateType gETMassUpdater(bulkKey, zuoraEntityIds)
Get mass action result
This reference describes how to get information about the result of a mass action through the REST API.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.MassUpdaterApi;
MassUpdaterApi apiInstance = new MassUpdaterApi();
String bulkKey = "bulkKey_example"; // String | String of 32 characters that identifies a mass action. You get the bulk-key after performing a mass action through the REST API.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETMassUpdateType result = apiInstance.gETMassUpdater(bulkKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling MassUpdaterApi#gETMassUpdater");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**bulkKey** | **String**| String of 32 characters that identifies a mass action. You get the bulk-key after performing a mass action through the REST API. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETMassUpdateType**](GETMassUpdateType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTMassUpdater"></a>
# **pOSTMassUpdater**
> POSTMassUpdateResponseType pOSTMassUpdater(file, params, zuoraEntityIds)
Perform mass action
This reference describes how to perform a mass action through the REST API. Using this API method, you send a multipart/form-data request containing a `.csv` file with data about the mass action you want to perform. Zuora returns a key and then asynchronously processes the mass action. You can use the key to get details about the result of the mass action.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.MassUpdaterApi;
MassUpdaterApi apiInstance = new MassUpdaterApi();
File file = new File("/path/to/file.txt"); // File | File containing data about the mass action you want to perform. The file requirements are the same as when uploading a file through the Mass Updater in the Zuora UI. The file must be a .csv file or a zipped .csv file. The maximum file size is 4 MB. The data in the file must be formatted according to the mass action type you want to perform.
String params = "params_example"; // String | Container for the following fields. You must format this parameter as a JSON object. * `actionType` (string, **Required**) - Type of mass action you want to perform. The following mass actions are supported: `UpdateAccountingCode`, `CreateRevenueSchedule`, `UpdateRevenueSchedule`, `DeleteRevenueSchedule`, `ImportFXRate`, and `MPU`. * `checksum` (string) - An MD5 checksum that is used to validate the integrity of the uploaded file. The checksum is a 32-character string.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTMassUpdateResponseType result = apiInstance.pOSTMassUpdater(file, params, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling MassUpdaterApi#pOSTMassUpdater");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**file** | **File**| File containing data about the mass action you want to perform. The file requirements are the same as when uploading a file through the Mass Updater in the Zuora UI. The file must be a .csv file or a zipped .csv file. The maximum file size is 4 MB. The data in the file must be formatted according to the mass action type you want to perform. |
**params** | **String**| Container for the following fields. You must format this parameter as a JSON object. * `actionType` (string, **Required**) - Type of mass action you want to perform. The following mass actions are supported: `UpdateAccountingCode`, `CreateRevenueSchedule`, `UpdateRevenueSchedule`, `DeleteRevenueSchedule`, `ImportFXRate`, and `MPU`. * `checksum` (string) - An MD5 checksum that is used to validate the integrity of the uploaded file. The checksum is a 32-character string. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTMassUpdateResponseType**](POSTMassUpdateResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json; charset=utf-8
<a name="pUTMassUpdater"></a>
# **pUTMassUpdater**
> CommonResponseType pUTMassUpdater(bulkKey, zuoraEntityIds)
Stop mass action
This reference describes how to stop a mass action through the REST API. You can stop a mass action when its status is Pending or Processing. After you have stopped a mass action, you can get the mass action result to see details of the mass action. - If you stop a mass action when its status is Pending, no response file is generated because no records have been processed. - If you stop a mass action when its status is Processing, a response file is generated. You can check the response file to see which records have been processed and which have not. In the response file, the **Success** column has the value `Y` (successful) or `N` (failed) for processed records, and a blank value for unprocessed records. Records that have already been processed when a mass action is stopped are not rolled back.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.MassUpdaterApi;
MassUpdaterApi apiInstance = new MassUpdaterApi();
String bulkKey = "bulkKey_example"; // String | String of 32 characters that identifies a mass action. You get the bulk-key after performing a mass action through the REST API.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTMassUpdater(bulkKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling MassUpdaterApi#pUTMassUpdater");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**bulkKey** | **String**| String of 32 characters that identifies a mass action. You get the bulk-key after performing a mass action through the REST API. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# SubscribeRequestSubscribeOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**applyCreditBalance** | **Boolean** | | [optional]
**electronicPaymentOptions** | [**SubscribeRequestSubscribeOptionsElectronicPaymentOptions**](SubscribeRequestSubscribeOptionsElectronicPaymentOptions.md) | | [optional]
**externalPaymentOptions** | [**SubscribeRequestSubscribeOptionsExternalPaymentOptions**](SubscribeRequestSubscribeOptionsExternalPaymentOptions.md) | | [optional]
**generateInvoice** | **Boolean** | |
**processPayments** | **Boolean** | |
**subscribeInvoiceProcessingOptions** | [**SubscribeRequestSubscribeOptionsSubscribeInvoiceProcessingOptions**](SubscribeRequestSubscribeOptionsSubscribeInvoiceProcessingOptions.md) | | [optional]
<file_sep>
# GETRefundPartCollectionType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**parts** | [**List<RefundPartResponseTypewithSuccess>**](RefundPartResponseTypewithSuccess.md) | Container for refund parts. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<file_sep>
# GETAccountTypeBasicInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**classNS** | **String** | Value of the Class field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**customerTypeNS** | [**CustomerTypeNSEnum**](#CustomerTypeNSEnum) | Value of the Customer Type field for the corresponding customer account in NetSuite. The Customer Type field is used when the customer account is created in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Value of the Department field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the account's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Value of the Location field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Value of the Subsidiary field for the corresponding customer account in NetSuite. The Subsidiary field is required if you use NetSuite OneWorld. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the account was sychronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | [**SynctoNetSuiteNSEnum**](#SynctoNetSuiteNSEnum) | Specifies whether the account should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountNumber** | **String** | Account number. | [optional]
**batch** | **String** | The alias name given to a batch. A string of 50 characters or less. | [optional]
**communicationProfileId** | **String** | ID of a communication profile. | [optional]
**creditMemoTemplateId** | **String** | **Note**: This field is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). The unique ID of the credit memo template, configured in **Billing Settings** > **Manage Billing Document Configuration** through the Zuora UI. For example, 2c92c08a6246fdf101626b1b3fe0144b. | [optional]
**crmId** | **String** | CRM account ID for the account, up to 100 characters. | [optional]
**currency** | **String** | A currency as defined in Billing Settings in the Zuora UI. | [optional]
**debitMemoTemplateId** | **String** | **Note**: This field is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). The unique ID of the debit memo template, configured in **Billing Settings** > **Manage Billing Document Configuration** through the Zuora UI. For example, 2c92c08d62470a8501626b19d24f19e2. | [optional]
**id** | **String** | Account ID. | [optional]
**invoiceTemplateId** | **String** | Invoice template ID, configured in Billing Settings in the Zuora UI. | [optional]
**name** | **String** | Account name. | [optional]
**notes** | **String** | Notes associated with the account, up to 65,535 characters. | [optional]
**parentId** | **String** | Identifier of the parent customer account for this Account object. The length is 32 characters. Use this field if you have customer hierarchy enabled. | [optional]
**salesRep** | **String** | The name of the sales representative associated with this account, if applicable. Maximum of 50 characters. | [optional]
**status** | **String** | Account status; possible values are: `Active`, `Draft`, `Canceled`. | [optional]
**tags** | **String** | | [optional]
<a name="CustomerTypeNSEnum"></a>
## Enum: CustomerTypeNSEnum
Name | Value
---- | -----
COMPANY | "Company"
INDIVIDUAL | "Individual"
<a name="SynctoNetSuiteNSEnum"></a>
## Enum: SynctoNetSuiteNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<file_sep>
# POSTCatalogType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**toEntityIds** | **List<String>** | The entity that you want to share the product with. |
<file_sep># ChargeRevenueSummariesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETCRSByCRSNumber**](ChargeRevenueSummariesApi.md#gETCRSByCRSNumber) | **GET** /v1/charge-revenue-summaries/{crs-number} | Get charge summary details by CRS number
[**gETCRSByChargeID**](ChargeRevenueSummariesApi.md#gETCRSByChargeID) | **GET** /v1/charge-revenue-summaries/subscription-charges/{charge-key} | Get charge summary details by charge ID
<a name="gETCRSByCRSNumber"></a>
# **gETCRSByCRSNumber**
> GETChargeRSDetailType gETCRSByCRSNumber(crsNumber, zuoraEntityIds)
Get charge summary details by CRS number
This REST API reference describes how to retrieve the details of a charge revenue summary by specifying the charge revenue summary number. The response includes all revenue items associated with the charge revenue summary.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ChargeRevenueSummariesApi;
ChargeRevenueSummariesApi apiInstance = new ChargeRevenueSummariesApi();
String crsNumber = "crsNumber_example"; // String | The charge revenue summary number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETChargeRSDetailType result = apiInstance.gETCRSByCRSNumber(crsNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ChargeRevenueSummariesApi#gETCRSByCRSNumber");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**crsNumber** | **String**| The charge revenue summary number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETChargeRSDetailType**](GETChargeRSDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETCRSByChargeID"></a>
# **gETCRSByChargeID**
> GETChargeRSDetailType gETCRSByChargeID(chargeKey, zuoraEntityIds)
Get charge summary details by charge ID
This REST API reference describes how to retrieve the details of a charge revenue summary by specifying the subscription charge ID. This response retrieves all revenue items associated with a charge revenue summary.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ChargeRevenueSummariesApi;
ChargeRevenueSummariesApi apiInstance = new ChargeRevenueSummariesApi();
String chargeKey = "chargeKey_example"; // String | ID of the subscription rate plan charge; for example, 402892793e173340013e173b81000012.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETChargeRSDetailType result = apiInstance.gETCRSByChargeID(chargeKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ChargeRevenueSummariesApi#gETCRSByChargeID");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**chargeKey** | **String**| ID of the subscription rate plan charge; for example, 402892793e173340013e173b81000012. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETChargeRSDetailType**](GETChargeRSDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# CreateOrderCreateSubscriptionTermsInitialTerm
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**period** | **Integer** | Duration of the first term in months, years, days, or weeks, depending on the value of the `periodType` field. Only applicable if the value of the `termType` field is `TERMED`. The duration of the first term cannot be greater than 10 years. | [optional]
**periodType** | [**PeriodTypeEnum**](#PeriodTypeEnum) | Unit of time that the first term is measured in. Only applicable if the value of the `termType` field is `TERMED`. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | Start date of the first term, in YYYY-MM-DD format. | [optional]
**termType** | [**TermTypeEnum**](#TermTypeEnum) | Type of the first term. If the value of this field is `TERMED`, the first term has a predefined duration based on the value of the `period` field. If the value of this field is `EVERGREEN`, the first term does not have a predefined duration. |
<a name="PeriodTypeEnum"></a>
## Enum: PeriodTypeEnum
Name | Value
---- | -----
MONTH | "Month"
YEAR | "Year"
DAY | "Day"
WEEK | "Week"
<a name="TermTypeEnum"></a>
## Enum: TermTypeEnum
Name | Value
---- | -----
TERMED | "TERMED"
EVERGREEN | "EVERGREEN"
<file_sep>
# POSTSubscriptionPreviewCreditMemoItemsType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amountWithoutTax** | **Double** | The credit memo item amount excluding tax. | [optional]
**chargeAmount** | **Double** | The amount of the credit memo item. For tax-inclusive credit memo items, the amount indicates the credit memo item amount including tax. For tax-exclusive credit memo items, the amount indicates the credit memo item amount excluding tax | [optional]
**chargeDescription** | **String** | Description of this credit memo item. | [optional]
**chargeName** | **String** | Name of this credit memo item. | [optional]
**productName** | **String** | Name of the product associated with this credit memo item. | [optional]
**productRatePlanChargeId** | **String** | ID of the product rate plan charge associated with this credit memo item. | [optional]
**quantity** | **Integer** | Quantity of the charge associated with this credit memo item. | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | End date of the service period for this credit memo item, as yyyy-mm-dd. | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | Service start date of this credit memo item, as yyyy-mm-dd. | [optional]
**unitOfMeasure** | **String** | Unit used to measure consumption. | [optional]
<file_sep>
# ProxyModifyPayment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the payment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the payment was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The unique account ID for the customer that the payment is for. | [optional]
**accountingCode** | **String** | The aacccounting code for the payment. Accounting codes group transactions that contain similar accounting attributes. | [optional]
**amount** | **Double** | The amount of the payment. | [optional]
**comment** | **String** | Additional information related to the payment. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the payment takes effect. | [optional]
**paymentMethodId** | **String** | The ID of the payment method used for the payment. | [optional]
**referenceId** | **String** | The transaction ID returned by the payment gateway. Use this field to reconcile payments between your gateway and Zuora Payments. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the payment in Zuora. The value depends on the type of payment. For electronic payments, the status can be `Processed`, `Error`, or `Voided`. For external payments, the status can be `Processed` or `Canceled`. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the refund was transferred to an external accounting system. Use this field for integration with accounting systems, such as NetSuite. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | The type of the payment, whether the payment is external or electronic. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PROCESSED | "Processed"
ERROR | "Error"
VOIDED | "Voided"
CANCELED | "Canceled"
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
ERROR | "Error"
IGNORE | "Ignore"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
EXTERNAL | "External"
ELECTRONIC | "Electronic"
<file_sep>
# ProxyModifyProductRatePlan
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**billingPeriodNS** | [**BillingPeriodNSEnum**](#BillingPeriodNSEnum) | Billing period associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**classNS** | **String** | Class associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Department associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**includeChildrenNS** | [**IncludeChildrenNSEnum**](#IncludeChildrenNSEnum) | Specifies whether the corresponding item in NetSuite is visible under child subsidiaries. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the product rate plan's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**itemTypeNS** | [**ItemTypeNSEnum**](#ItemTypeNSEnum) | Type of item that is created in NetSuite for the product rate plan. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Location associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**multiCurrencyPriceNS** | **String** | Multi-currency price associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**priceNS** | **String** | Price associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Subsidiary associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the product rate plan was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**description** | **String** | A description of the product rate plan. **Character limit**: 500 **Values**: a string of 500 characters or fewer | [optional]
**effectiveEndDate** | [**LocalDate**](LocalDate.md) | The date when the product rate plan expires and can't be subscribed to, in `yyyy-mm-dd` format. **Character limit**: 29 | [optional]
**effectiveStartDate** | [**LocalDate**](LocalDate.md) | The date when the product rate plan becomes available and can be subscribed to, in `yyyy-mm-dd` format. **Character limit**: 29 | [optional]
**name** | **String** | The name of the product rate plan. The name doesn't have to be unique in a Product Catalog, but the name has to be unique within a product. **Character limit**: 100 **Values**: a string of 100 characters or fewer | [optional]
**productId** | **String** | The ID of the product that contains the product rate plan. **Character limit**: 32 **Values**: a string of 32 characters or fewer | [optional]
<a name="BillingPeriodNSEnum"></a>
## Enum: BillingPeriodNSEnum
Name | Value
---- | -----
MONTHLY | "Monthly"
QUARTERLY | "Quarterly"
ANNUAL | "Annual"
SEMI_ANNUAL | "Semi-Annual"
<a name="IncludeChildrenNSEnum"></a>
## Enum: IncludeChildrenNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<a name="ItemTypeNSEnum"></a>
## Enum: ItemTypeNSEnum
Name | Value
---- | -----
INVENTORY | "Inventory"
NON_INVENTORY | "Non Inventory"
SERVICE | "Service"
<file_sep># CustomExchangeRatesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETCustomExchangeRates**](CustomExchangeRatesApi.md#gETCustomExchangeRates) | **GET** /v1/custom-exchange-rates/{currency} | Get custom foreign currency exchange rates
<a name="gETCustomExchangeRates"></a>
# **gETCustomExchangeRates**
> GETCustomExchangeRatesType gETCustomExchangeRates(currency, startDate, endDate, zuoraEntityIds)
Get custom foreign currency exchange rates
This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). This reference describes how to query custom foreign exchange rates from Zuora. You can use this API method to query exchange rates only if you use a custom exchange rate provider and upload rates with the Import Foreign Exchange Rates mass action.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.CustomExchangeRatesApi;
CustomExchangeRatesApi apiInstance = new CustomExchangeRatesApi();
String currency = "currency_example"; // String | The target base currency of the tenant. The exchange rates in the response are calculated in relation to the target currency. The value must be a three-letter currency code, for example, USD.
String startDate = "startDate_example"; // String | Start date of the date range for which you want to get exchange rates. The date must be in yyyy-mm-dd format, for example, 2016-01-15. The start date cannot be later than the end date.
String endDate = "endDate_example"; // String | End date of the date range for which you want to get exchange rates. The date must be in yyyy-mm-dd format, for example, 2016-01-16. The end date can be a maximum of 90 days after the start date.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETCustomExchangeRatesType result = apiInstance.gETCustomExchangeRates(currency, startDate, endDate, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling CustomExchangeRatesApi#gETCustomExchangeRates");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**currency** | **String**| The target base currency of the tenant. The exchange rates in the response are calculated in relation to the target currency. The value must be a three-letter currency code, for example, USD. |
**startDate** | **String**| Start date of the date range for which you want to get exchange rates. The date must be in yyyy-mm-dd format, for example, 2016-01-15. The start date cannot be later than the end date. |
**endDate** | **String**| End date of the date range for which you want to get exchange rates. The date must be in yyyy-mm-dd format, for example, 2016-01-16. The end date can be a maximum of 90 days after the start date. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETCustomExchangeRatesType**](GETCustomExchangeRatesType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# BreakdownDetail
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | The end date of the overlap period of the InvoiceDetail and the certain orderMetrics. | [optional]
**generatedReason** | [**GeneratedReasonEnum**](#GeneratedReasonEnum) | Specify the generatedReason of the referenced order metrics. | [optional]
**orderActionId** | **String** | Specify the order action that generated the referenced order metrics. | [optional]
**orderItemId** | **String** | The ID of the order item. | [optional]
**orderNumber** | **String** | | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The start date of the overlap period of the InvoiceDetail and the certain orderMetrics. | [optional]
**termNumber** | [**BigDecimal**](BigDecimal.md) | | [optional]
<a name="GeneratedReasonEnum"></a>
## Enum: GeneratedReasonEnum
Name | Value
---- | -----
INCREASEQUANTITY | "IncreaseQuantity"
DECREASEQUANTITY | "DecreaseQuantity"
CHANGEPRICE | "ChangePrice"
EXTENSION | "Extension"
CONTRACTION | "Contraction"
<file_sep>
# POSTRevenueScheduleByChargeTypeRevenueEvent
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**eventType** | [**EventTypeEnum**](#EventTypeEnum) | Label of the revenue event type. Revenue event type labels can be duplicated. You can configure your revenue event type labels by navigating to **Settings > Finance > Configure Revenue Event Types** in the Zuora UI. Note that `Credit Memo Posted` and `Debit Memo Posted` are only available if you enable the Invoice Settlement feature. |
**eventTypeSystemId** | **String** | System ID of the revenue event type. Each eventType has a unique system ID. You can configure your revenue event type system IDs by navigating to **Settings > Finance > Configure Revenue Event Types** in the Zuora UI. |
**notes** | **String** | Additional information about this record. | [optional]
<a name="EventTypeEnum"></a>
## Enum: EventTypeEnum
Name | Value
---- | -----
INVOICE_POSTED | "Invoice Posted"
INVOICE_ITEM_ADJUSTMENT_CREATED | "Invoice Item Adjustment Created"
INVOICE_CANCELED | "Invoice Canceled"
INVOICE_ITEM_ADJUSTMENT_CANCELED | "Invoice Item Adjustment Canceled"
REVENUE_DISTRIBUTED | "Revenue Distributed"
CREDIT_MEMO_POSTED | "Credit Memo Posted"
DEBIT_MEMO_POSTED | "Debit Memo Posted"
<file_sep>
# InvoiceItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the invoice item's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the invoice item was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**chargeAmount** | **String** | The amount of the charge. This amount does not include taxes regardless if the charge's tax mode is inclusive or exclusive. | [optional]
**chargeDescription** | **String** | Description of the charge. | [optional]
**chargeId** | **String** | ID of the charge. | [optional]
**chargeName** | **String** | Name of the charge. | [optional]
**id** | **String** | Item ID. | [optional]
**productName** | **String** | Name of the product associated with this item. | [optional]
**quantity** | **String** | Quantity of this item, in the configured unit of measure for the charge. | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | End date of the service period for this item, i.e., the last day of the service period, as _yyyy-mm-dd_. | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | Start date of the service period for this item, as _yyyy-mm-dd_. For a one-time fee item, the date of the charge. | [optional]
**subscriptionId** | **String** | ID of the subscription for this item. | [optional]
**subscriptionName** | **String** | Name of the subscription for this item. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**taxAmount** | **String** | Tax applied to the charge. | [optional]
**unitOfMeasure** | **String** | Unit used to measure consumption. | [optional]
<file_sep>
# OrderForEvergreen
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**createdBy** | **String** | The ID of the user who created this order. | [optional]
**createdDate** | **String** | The time that the order gets created in the system, in the `YYYY-MM-DD HH:MM:SS` format. | [optional]
**currency** | **String** | Currency code. | [optional]
**customFields** | [**OrderObjectCustomFields**](OrderObjectCustomFields.md) | | [optional]
**existingAccountNumber** | **String** | The account number that this order has been created under. This is also the invoice owner of the subscriptions included in this order. | [optional]
**orderDate** | **String** | The date when the order is signed. All the order actions under this order will use this order date as the contract effective date if no additinal contractEffectiveDate is provided. | [optional]
**orderNumber** | **String** | The order number of the order. | [optional]
**status** | **String** | The status of the order. | [optional]
**subscriptions** | [**List<OrderForEvergreenSubscriptions>**](OrderForEvergreenSubscriptions.md) | Represents a processed subscription, including the origin request (order actions) that create this version of subscription and the processing result (order metrics). The reference part in the request will be overridden with the info in the new subscription version. | [optional]
**updatedBy** | **String** | The ID of the user who updated this order. | [optional]
**updatedDate** | **String** | The time that the order gets updated in the system (for example, an order description update), in the `YYYY-MM-DD HH:MM:SS` format. | [optional]
<file_sep>
# RatePlanOverride
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeOverrides** | [**List<ChargeOverride>**](ChargeOverride.md) | List of charges associated with the rate plan. | [optional]
**customFields** | [**RatePlanObjectCustomFields**](RatePlanObjectCustomFields.md) | | [optional]
**newRatePlanId** | **String** | Internal identifier of the rate plan. | [optional]
**productRatePlanId** | **String** | Internal identifier of the product rate plan that the rate plan is based on. |
**uniqueToken** | **String** | Unique identifier for the rate plan. This identifier enables you to refer to the rate plan before the rate plan has an internal identifier in Zuora. For instance, suppose that you want to use a single order to add a product to a subscription and later update the same product. When you add the product, you can set a unique identifier for the rate plan. Then when you update the product, you can use the same unique identifier to specify which rate plan to modify. | [optional]
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.CommonResponseType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.ConnectionsApi")
public class ConnectionsApi {
private ApiClient apiClient;
public ConnectionsApi() {
this(new ApiClient());
}
@Autowired
public ConnectionsApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Establish connection to Zuora REST API service
* Establishes a connection to the Zuora REST API service based on a valid user credentials. **Note:**This is a legacy REST API. Zuora recommends you to use [OAuth](https://www.zuora.com/developer/api-reference/#section/Authentication/OAuth-v2.0) for authentication instead. This call authenticates the user and returns an API session cookie that's used to authorize subsequent calls to the REST API. The credentials must belong to a user account that has permission to access the API service. As noted elsewhere, it's strongly recommended that an account used for Zuora API activity is never used to log into the Zuora UI. Once an account is used to log into the UI, it may be subject to periodic forced password changes, which may eventually lead to authentication failures when using the API.
* <p><b>200</b> -
* @param apiAccessKeyId Account username
* @param apiSecretAccessKey Account password
* @param contentType2 Must be set to \"application/json\"
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return CommonResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public CommonResponseType pOSTConnections(String apiAccessKeyId, String apiSecretAccessKey, String contentType2, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'apiAccessKeyId' is set
if (apiAccessKeyId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'apiAccessKeyId' when calling pOSTConnections");
}
// verify the required parameter 'apiSecretAccessKey' is set
if (apiSecretAccessKey == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'apiSecretAccessKey' when calling pOSTConnections");
}
// verify the required parameter 'contentType2' is set
if (contentType2 == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'contentType2' when calling pOSTConnections");
}
String path = UriComponentsBuilder.fromPath("/v1/connections").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
if (apiAccessKeyId != null)
headerParams.add("apiAccessKeyId", apiClient.parameterToString(apiAccessKeyId));
if (apiSecretAccessKey != null)
headerParams.add("apiSecretAccessKey", apiClient.parameterToString(apiSecretAccessKey));
if (contentType2 != null)
headerParams.add("Content-Type", apiClient.parameterToString(contentType2));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<CommonResponseType> returnType = new ParameterizedTypeReference<CommonResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep>
# PUTWriteOffInvoiceResponseCreditMemo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **String** | The ID of the credit memo that is created when the invoice is written off. | [optional]
<file_sep>
# GETUsageType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | **String** | Customer account ID. | [optional]
**accountName** | **String** | Customer account name. | [optional]
**accountNumber** | **String** | Customer account number. | [optional]
**chargeNumber** | **String** | Number of the rate-plan charge that pays for this usage. | [optional]
**id** | **String** | Unique ID for the usage item. | [optional]
**quantity** | **String** | Number of units used. | [optional]
**sourceName** | **String** | Source of the usage data. Possible values are: `Import`, `API`. | [optional]
**startDateTime** | [**OffsetDateTime**](OffsetDateTime.md) | Start date of the time period in which usage is tracked. Zuora uses this field value to determine the usage date. | [optional]
**status** | **String** | Possible values are: `Importing`, `Pending`, `Processed`. | [optional]
**submissionDateTime** | [**OffsetDateTime**](OffsetDateTime.md) | Date when usage was submitted. | [optional]
**subscriptionNumber** | **String** | Number of the subscription covering this usage. | [optional]
**unitOfMeasure** | **String** | Unit used to measure consumption. | [optional]
<file_sep>
# PreviewResultOrderActions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**orderItems** | [**List<OrderItem>**](OrderItem.md) | | [optional]
**orderMetrics** | [**List<OrderMetric>**](OrderMetric.md) | | [optional]
**sequence** | **String** | | [optional]
**type** | **String** | | [optional]
<file_sep>
# OrderMetric
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeNumber** | **String** | | [optional]
**elp** | [**List<TimeSlicedElpNetMetrics>**](TimeSlicedElpNetMetrics.md) | The extended list price which is calculated by the original product catalog list price multiplied by the delta quantity. | [optional]
**mrr** | [**List<TimeSlicedNetMetrics>**](TimeSlicedNetMetrics.md) | | [optional]
**originRatePlanId** | **String** | | [optional]
**productRatePlanChargeId** | **String** | | [optional]
**productRatePlanId** | **String** | | [optional]
**quantity** | [**List<TimeSlicedMetrics>**](TimeSlicedMetrics.md) | | [optional]
**tcb** | [**List<TimeSlicedTcbNetMetrics>**](TimeSlicedTcbNetMetrics.md) | Total contracted billing which is the forecast value for the total invoice amount. | [optional]
**tcv** | [**List<TimeSlicedNetMetrics>**](TimeSlicedNetMetrics.md) | Total contracted value. | [optional]
<file_sep>
# ProxyActionamendRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**requests** | [**List<AmendRequest>**](AmendRequest.md) | The value of this field must be an array that contains a single AmendRequest object. To specify multiple Amendment objects, use the `Amendments` field of the AmendRequest object. | [optional]
<file_sep>
# PUTSubscriptionPatchRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFields** | [**SubscriptionObjectCustomFields**](SubscriptionObjectCustomFields.md) | | [optional]
**ratePlans** | [**List<PUTSubscriptionPatchRequestTypeRatePlans>**](PUTSubscriptionPatchRequestTypeRatePlans.md) | | [optional]
<file_sep>
# GETRevenueEventDetailType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | **String** | An account ID. | [optional]
**createdOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the record was created in YYYY-MM-DD HH:MM:SS format. | [optional]
**currency** | **String** | The type of currency used. | [optional]
**eventType** | [**EventTypeEnum**](#EventTypeEnum) | Label of the revenue event type. Revenue event type labels can be duplicated. You can configure your revenue event type labels by navigating to **Settings > Finance > Configure Revenue Event Types** in the Zuora UI. Note that `Credit Memo Posted` and `Debit Memo Posted` are only available if you enable the Invoice Settlement feature. | [optional]
**notes** | **String** | Additional information about this record. | [optional]
**number** | **String** | The revenue event number created when a revenue event occurs. | [optional]
**recognitionEnd** | [**LocalDate**](LocalDate.md) | The end date of a recognition period in YYYY-MM-DD format. The maximum difference of the recognitionStart and recognitionEnd date fields is equal to 250 multiplied by the length of an accounting period. | [optional]
**recognitionStart** | [**LocalDate**](LocalDate.md) | The start date of a recognition period in YYYY-MM-DD format. | [optional]
**revenueItems** | [**List<GETRevenueItemType>**](GETRevenueItemType.md) | Revenue items are listed in ascending order by the accounting period start date. | [optional]
**subscriptionChargeId** | **String** | The original subscription charge ID. | [optional]
**subscriptionId** | **String** | The original subscription ID. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<a name="EventTypeEnum"></a>
## Enum: EventTypeEnum
Name | Value
---- | -----
INVOICE_POSTED | "Invoice Posted"
INVOICE_ITEM_ADJUSTMENT_CREATED | "Invoice Item Adjustment Created"
INVOICE_CANCELED | "Invoice Canceled"
INVOICE_ITEM_ADJUSTMENT_CANCELED | "Invoice Item Adjustment Canceled"
REVENUE_DISTRIBUTED | "Revenue Distributed"
CREDIT_MEMO_POSTED | "Credit Memo Posted"
DEBIT_MEMO_POSTED | "Debit Memo Posted"
<file_sep># EntitiesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEEntities**](EntitiesApi.md#dELETEEntities) | **DELETE** /v1/entities/{id} | Multi-entity: Delete entity
[**gETEntities**](EntitiesApi.md#gETEntities) | **GET** /v1/entities | Multi-entity: Get entities
[**gETEntityById**](EntitiesApi.md#gETEntityById) | **GET** /v1/entities/{id} | Multi-entity: Get entity by Id
[**pOSTEntities**](EntitiesApi.md#pOSTEntities) | **POST** /v1/entities | Multi-entity: Create entity
[**pUTEntities**](EntitiesApi.md#pUTEntities) | **PUT** /v1/entities/{id} | Multi-entity: Update entity
[**pUTProvisionEntity**](EntitiesApi.md#pUTProvisionEntity) | **PUT** /v1/entities/{id}/provision | Multi-entity: Provision entity
<a name="dELETEEntities"></a>
# **dELETEEntities**
> DELETEntityResponseType dELETEEntities(id, zuoraEntityIds)
Multi-entity: Delete entity
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Removes an entity and its sub-entities from a multi-entity hierarchy. You can only remove unprovisioned entities. An error occurred when you remove a provisioned entity. ## User Access Permission You must make the call as a global entity administrator.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EntitiesApi;
EntitiesApi apiInstance = new EntitiesApi();
String id = "id_example"; // String | Specify the Id of the entity that you want to delete. You can get the entity Id from the GET Entities call.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
DELETEntityResponseType result = apiInstance.dELETEEntities(id, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EntitiesApi#dELETEEntities");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Specify the Id of the entity that you want to delete. You can get the entity Id from the GET Entities call. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**DELETEntityResponseType**](DELETEntityResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETEntities"></a>
# **gETEntities**
> GETEntitiesResponseType gETEntities(zuoraEntityIds, provisioned)
Multi-entity: Get entities
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves detailed information of certain entities in a multi-entity hierarchy. You can retrieve: - Provisioned entities - Unprovisioned entities - Both provisioned and unprovisioned entities ## User Access Permission You can make the call as any entity user.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EntitiesApi;
EntitiesApi apiInstance = new EntitiesApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String provisioned = "provisioned_example"; // String | Specify whether to retrieve provisioned or unprovisioned entities: - `true`: Provisioned entities - `false`: Unprovisioned entities If you do not specify this field in the request, both the provisioned and unprovisioned entities are returned.
try {
GETEntitiesResponseType result = apiInstance.gETEntities(zuoraEntityIds, provisioned);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EntitiesApi#gETEntities");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**provisioned** | **String**| Specify whether to retrieve provisioned or unprovisioned entities: - `true`: Provisioned entities - `false`: Unprovisioned entities If you do not specify this field in the request, both the provisioned and unprovisioned entities are returned. | [optional]
### Return type
[**GETEntitiesResponseType**](GETEntitiesResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETEntityById"></a>
# **gETEntityById**
> GETEntitiesResponseTypeWithId gETEntityById(id, zuoraEntityIds)
Multi-entity: Get entity by Id
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves detailed information about a specified entity. ## User Access Permission You can make the call as any entity user.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EntitiesApi;
EntitiesApi apiInstance = new EntitiesApi();
String id = "id_example"; // String | Specify the Id of the entity that you want to retrieve. You can get the entity Id from the GET Entities call.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETEntitiesResponseTypeWithId result = apiInstance.gETEntityById(id, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EntitiesApi#gETEntityById");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Specify the Id of the entity that you want to retrieve. You can get the entity Id from the GET Entities call. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETEntitiesResponseTypeWithId**](GETEntitiesResponseTypeWithId.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTEntities"></a>
# **pOSTEntities**
> CreateEntityResponseType pOSTEntities(request, zuoraEntityIds)
Multi-entity: Create entity
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates an entity in a multi-entity hierarchy. ## User Access Permission You must make the call as a global entity administrator. ## Notes * We recommend that you assign only one administrator to manage the entity hierarchy, because an administrator of the global entity by default can only access to the entities that are created by themselves.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EntitiesApi;
EntitiesApi apiInstance = new EntitiesApi();
CreateEntityType request = new CreateEntityType(); // CreateEntityType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CreateEntityResponseType result = apiInstance.pOSTEntities(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EntitiesApi#pOSTEntities");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**CreateEntityType**](CreateEntityType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CreateEntityResponseType**](CreateEntityResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTEntities"></a>
# **pUTEntities**
> UpdateEntityResponseType pUTEntities(id, request, zuoraEntityIds)
Multi-entity: Update entity
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Edits the following information about an unprovisioned entity: - Name - Display name - Locale - Timezone ## User Access Permission You must make the call as a global entity administrator. ## Notes * You are not allowed to edit the locale and time zone of the provisioned entities through the REST API. * You are not allowed to edit the display name of the global entity.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EntitiesApi;
EntitiesApi apiInstance = new EntitiesApi();
String id = "id_example"; // String | The Id of the entity that you want to edit. You can get the entity Id from the GET Entities call.
UpdateEntityType request = new UpdateEntityType(); // UpdateEntityType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
UpdateEntityResponseType result = apiInstance.pUTEntities(id, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EntitiesApi#pUTEntities");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The Id of the entity that you want to edit. You can get the entity Id from the GET Entities call. |
**request** | [**UpdateEntityType**](UpdateEntityType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**UpdateEntityResponseType**](UpdateEntityResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTProvisionEntity"></a>
# **pUTProvisionEntity**
> ProvisionEntityResponseType pUTProvisionEntity(id, zuoraEntityIds)
Multi-entity: Provision entity
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Provisions an entity. You can only provision an entity if its parent entity is provisioned. ## User Access Permission You must make the call as a global entity administrator. ## Notes * Zuora does not allow you to remove a provisioned entity from the multi-entity hierarchy. So before you provision an entity, make sure that you put the entity in the correct place in the multi-entity hierarchy.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EntitiesApi;
EntitiesApi apiInstance = new EntitiesApi();
String id = "id_example"; // String | Specify the Id of the entity that you want to provision. You can get the entity Id from the GET Entities call.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
ProvisionEntityResponseType result = apiInstance.pUTProvisionEntity(id, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EntitiesApi#pUTProvisionEntity");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Specify the Id of the entity that you want to provision. You can get the entity Id from the GET Entities call. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**ProvisionEntityResponseType**](ProvisionEntityResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# TokenResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accessToken** | **String** | The generated token. | [optional]
**expiresIn** | [**BigDecimal**](BigDecimal.md) | The number of seconds until the token expires. | [optional]
**jti** | **String** | A globally unique identifier for the token. | [optional]
**scope** | **String** | A space-delimited list of scopes that the token can be used to access. | [optional]
**tokenType** | **String** | The type of token that was generated, i.e., `bearer`. | [optional]
<file_sep>
# GETProductDiscountApplyDetailsType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**appliedProductRatePlanChargeId** | **String** | The ID of the product rate plan charge that the discount product rate plan charge applies to. | [optional]
**appliedProductRatePlanId** | **String** | The ID of the product rate plan that the discount product rate plan charge applies to. | [optional]
<file_sep>
# PUTSubscriptionPatchRequestTypeRatePlans
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**charges** | [**List<PUTSubscriptionPatchRequestTypeCharges>**](PUTSubscriptionPatchRequestTypeCharges.md) | | [optional]
**customFields** | [**RatePlanObjectCustomFields**](RatePlanObjectCustomFields.md) | | [optional]
**ratePlanId** | **String** | The rate plan id in any version of the subscription. This will be linked to the only one rate plan in the current version. | [optional]
<file_sep>
# RenewalTerm
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**period** | **Integer** | Duration of the renewal term in months, years, days, or weeks, depending on the value of the `periodType` field. | [optional]
**periodType** | [**PeriodTypeEnum**](#PeriodTypeEnum) | Unit of time that the renewal term is measured in. | [optional]
<a name="PeriodTypeEnum"></a>
## Enum: PeriodTypeEnum
Name | Value
---- | -----
MONTH | "Month"
YEAR | "Year"
DAY | "Day"
WEEK | "Week"
<file_sep>
# PostRefundType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the refund's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the refund was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | **String** | Specifies whether the refund should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**comment** | **String** | Comments about the refund. | [optional]
**financeInformation** | [**PostRefundTypeFinanceInformation**](PostRefundTypeFinanceInformation.md) | | [optional]
**methodType** | [**MethodTypeEnum**](#MethodTypeEnum) | How an external refund was issued to a customer. This field is required for an external refund and must be left empty for an electronic refund. You can issue an external refund on an electronic payment. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. | [optional]
**referenceId** | **String** | The transaction ID returned by the payment gateway for an electronic refund. Use this field to reconcile refunds between your gateway and Zuora Payments. | [optional]
**refundDate** | [**LocalDate**](LocalDate.md) | The date when the refund takes effect, in `yyyy-mm-dd` format. The date of the refund cannot be before the payment date. Specify this field only for external refunds. Zuora automatically generates this field for electronic refunds. | [optional]
**secondRefundReferenceId** | **String** | The transaction ID returned by the payment gateway if there is an additional transaction for the refund. Use this field to reconcile payments between your gateway and Zuora Payments. | [optional]
**totalAmount** | **Double** | The total amount of the refund. The amount cannot exceed the unapplied amount of the associated payment. If the original payment was applied to one or more invoices or debit memos, you have to unapply a full or partial payment from the invoices or debit memos, and then refund the full or partial unapplied payment to your customers. |
**type** | [**TypeEnum**](#TypeEnum) | The type of the refund. |
<a name="MethodTypeEnum"></a>
## Enum: MethodTypeEnum
Name | Value
---- | -----
ACH | "ACH"
CASH | "Cash"
CHECK | "Check"
CREDITCARD | "CreditCard"
PAYPAL | "PayPal"
WIRETRANSFER | "WireTransfer"
DEBITCARD | "DebitCard"
CREDITCARDREFERENCETRANSACTION | "CreditCardReferenceTransaction"
BANKTRANSFER | "BankTransfer"
OTHER | "Other"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
EXTERNAL | "External"
ELECTRONIC | "Electronic"
<file_sep>
# GETTaxationItemListType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**taxationItems** | [**List<GETTaxationItemTypewithSuccess>**](GETTaxationItemTypewithSuccess.md) | Container for taxation items. | [optional]
<file_sep>
# ProxyGetFeature
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**createdById** | **String** | Internal Zuora ID of the user who created the feature **Character limit**: 32 | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time when the feature was created **Character limit**: 29 | [optional]
**description** | **String** | Description of the feature **Character limit**: 1000 | [optional]
**featureCode** | **String** | Unique code of the feature **Character limit**: 255 | [optional]
**id** | **String** | Object identifier. | [optional]
**name** | **String** | Name of the feature **Character limit**: 255 | [optional]
**status** | **String** | Status of the feature, Active or Inactive **Character limit**: 8 | [optional]
**updatedById** | **String** | Internal Zuora ID of the user who last updated the feature **Character limit**: 32 | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time when the feature was last updated **Character limit**: 29 | [optional]
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.GETEntitiesUserAccessibleResponseType;
import de.keylight.zuora.client.model.PUTAcceptUserAccessResponseType;
import de.keylight.zuora.client.model.PUTDenyUserAccessResponseType;
import de.keylight.zuora.client.model.PUTSendUserAccessRequestResponseType;
import de.keylight.zuora.client.model.PUTSendUserAccessRequestType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.UsersApi")
public class UsersApi {
private ApiClient apiClient;
public UsersApi() {
this(new ApiClient());
}
@Autowired
public UsersApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Multi-entity: Get entities that a user can access
* **Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves detailed information about all the entities that a user has permission to access. ## User Access Permission You can make the call as any entity user.
* <p><b>200</b> -
* @param username Specify the login user name that you want to retrieve.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return GETEntitiesUserAccessibleResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GETEntitiesUserAccessibleResponseType gETEntitiesUserAccessible(String username, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling gETEntitiesUserAccessible");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = UriComponentsBuilder.fromPath("/v1/users/{username}/accessible-entities").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GETEntitiesUserAccessibleResponseType> returnType = new ParameterizedTypeReference<GETEntitiesUserAccessibleResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Multi-entity: Accept user access
* **Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Accepts user access to an entity. ## User Access Permission You must make the calls as an administrator of the entity that you want to accept the user access to.
* <p><b>200</b> -
* @param username Specify the login name of the user that you want to accept the access request for.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return PUTAcceptUserAccessResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public PUTAcceptUserAccessResponseType pUTAcceptUserAccess(String username, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling pUTAcceptUserAccess");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = UriComponentsBuilder.fromPath("/v1/users/{username}/accept-access").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<PUTAcceptUserAccessResponseType> returnType = new ParameterizedTypeReference<PUTAcceptUserAccessResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Multi-entity: Deny user access
* **Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Denies a user access to an entity. ## User Access Permission You must make the calls as an administrator of the entity that you want to deny the user access to.
* <p><b>200</b> -
* @param username Specify the login name of the user that you want to deny the access.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return PUTDenyUserAccessResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public PUTDenyUserAccessResponseType pUTDenyUserAccess(String username, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling pUTDenyUserAccess");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = UriComponentsBuilder.fromPath("/v1/users/{username}/deny-access").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<PUTDenyUserAccessResponseType> returnType = new ParameterizedTypeReference<PUTDenyUserAccessResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Multi-entity: Send user access requests
* **Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Sends access requests to the entities that a user wants to access. ## User Access Permission You must make the call as an administrator of the entity, in which the request user is created. Also, this administrator must have the permission to access the entities that the request user wants to access.
* <p><b>200</b> -
* @param username Specify the login name of the user who wants to access other entities.
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return PUTSendUserAccessRequestResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public PUTSendUserAccessRequestResponseType pUTSendUserAccessRequests(String username, PUTSendUserAccessRequestType request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling pUTSendUserAccessRequests");
}
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pUTSendUserAccessRequests");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = UriComponentsBuilder.fromPath("/v1/users/{username}/request-access").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<PUTSendUserAccessRequestResponseType> returnType = new ParameterizedTypeReference<PUTSendUserAccessRequestResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep>
# POSTPublicNotificationDefinitionRequestCallout
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**active** | **Boolean** | The status of the callout. The default is true. | [optional]
**calloutAuth** | [**CalloutAuth**](CalloutAuth.md) | | [optional]
**calloutBaseurl** | **String** | The callout URL. It must start with 'https://' |
**calloutParams** | [**CalloutMergeFields**](CalloutMergeFields.md) | | [optional]
**calloutRetry** | **Boolean** | Specified whether to retry the callout when the callout fails. The default is true. | [optional]
**description** | **String** | Description for the callout. | [optional]
**eventTypeName** | **String** | The name of the event type. |
**httpMethod** | [**HttpMethodEnum**](#HttpMethodEnum) | The HTTP method of the callout. |
**name** | **String** | The name of the created callout. |
**requiredAuth** | **Boolean** | Specifies whether the callout requires auth. |
<a name="HttpMethodEnum"></a>
## Enum: HttpMethodEnum
Name | Value
---- | -----
GET | "GET"
PUT | "PUT"
POST | "POST"
DELETE | "DELETE"
<file_sep># AmendmentsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETAmendmentsByKey**](AmendmentsApi.md#gETAmendmentsByKey) | **GET** /v1/amendments/{amendment-key} | Get amendments by key
[**gETAmendmentsBySubscriptionID**](AmendmentsApi.md#gETAmendmentsBySubscriptionID) | **GET** /v1/amendments/subscriptions/{subscription-id} | Get amendments by subscription ID
[**objectDELETEAmendment**](AmendmentsApi.md#objectDELETEAmendment) | **DELETE** /v1/object/amendment/{id} | CRUD: Delete amendment
[**objectGETAmendment**](AmendmentsApi.md#objectGETAmendment) | **GET** /v1/object/amendment/{id} | CRUD: Get amendment
[**objectPUTAmendment**](AmendmentsApi.md#objectPUTAmendment) | **PUT** /v1/object/amendment/{id} | CRUD: Update amendment
<a name="gETAmendmentsByKey"></a>
# **gETAmendmentsByKey**
> GETAmendmentType gETAmendmentsByKey(amendmentKey, zuoraEntityIds)
Get amendments by key
Retrieves detailed information about the specified subscription amendment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AmendmentsApi;
AmendmentsApi apiInstance = new AmendmentsApi();
String amendmentKey = "amendmentKey_example"; // String | Can be the amendment ID or the amendment code.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETAmendmentType result = apiInstance.gETAmendmentsByKey(amendmentKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AmendmentsApi#gETAmendmentsByKey");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**amendmentKey** | **String**| Can be the amendment ID or the amendment code. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETAmendmentType**](GETAmendmentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAmendmentsBySubscriptionID"></a>
# **gETAmendmentsBySubscriptionID**
> GETAmendmentType gETAmendmentsBySubscriptionID(subscriptionId, zuoraEntityIds)
Get amendments by subscription ID
Retrieves detailed information about the amendment with the specified subscription.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AmendmentsApi;
AmendmentsApi apiInstance = new AmendmentsApi();
String subscriptionId = "subscriptionId_example"; // String | The ID of the subscription whose amendment changes you want to retrieve.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETAmendmentType result = apiInstance.gETAmendmentsBySubscriptionID(subscriptionId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AmendmentsApi#gETAmendmentsBySubscriptionID");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionId** | **String**| The ID of the subscription whose amendment changes you want to retrieve. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETAmendmentType**](GETAmendmentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETEAmendment"></a>
# **objectDELETEAmendment**
> ProxyDeleteResponse objectDELETEAmendment(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete amendment
**Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AmendmentsApi;
AmendmentsApi apiInstance = new AmendmentsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEAmendment(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AmendmentsApi#objectDELETEAmendment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETAmendment"></a>
# **objectGETAmendment**
> ProxyGetAmendment objectGETAmendment(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Get amendment
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AmendmentsApi;
AmendmentsApi apiInstance = new AmendmentsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetAmendment result = apiInstance.objectGETAmendment(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AmendmentsApi#objectGETAmendment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetAmendment**](ProxyGetAmendment.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTAmendment"></a>
# **objectPUTAmendment**
> ProxyCreateOrModifyResponse objectPUTAmendment(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update amendment
**Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AmendmentsApi;
AmendmentsApi apiInstance = new AmendmentsApi();
String id = "id_example"; // String | Object id
ProxyModifyAmendment modifyRequest = new ProxyModifyAmendment(); // ProxyModifyAmendment |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTAmendment(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AmendmentsApi#objectPUTAmendment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyAmendment**](ProxyModifyAmendment.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# PUTPublicNotificationDefinitionRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**active** | **Boolean** | The status of the notification definition. The default value is true. | [optional]
**callout** | [**PUTPublicNotificationDefinitionRequestCallout**](PUTPublicNotificationDefinitionRequestCallout.md) | | [optional]
**calloutActive** | **Boolean** | The status of the callout action. The default value is false. | [optional]
**communicationProfileId** | [**UUID**](UUID.md) | The profile that notification definition belongs to. If you want to update the notification to a system notification, you should pass 'SystemNotification'. ' * When EventType is CDC/External and 'ReferenceObjectType' in EventType is associated to Account, comunicationProfileId can be 'SystemNotification'/Empty/UUID. * When EventType is CDC/External and 'ReferenceObjectType' in EventType is not associated to Account, comunicationProfileId can be 'SystemNotification'/Empty. * When EventType is CDC/External and 'ReferenceObjectType' in EventType is EMPTY, comunicationProfileId can be 'SystemNotification'/Empty. | [optional]
**description** | **String** | The description of the notification definition. | [optional]
**emailActive** | **Boolean** | The status of the email action. The default is false. | [optional]
**emailTemplateId** | [**UUID**](UUID.md) | The ID of the email template. If emailActive is updated from false to true, an email template is required, and the EventType of the email template MUST be the same as the EventType of the notification definition. | [optional]
**filterRule** | [**PUTPublicNotificationDefinitionRequestFilterRule**](PUTPublicNotificationDefinitionRequestFilterRule.md) | | [optional]
**filterRuleParams** | [**FilterRuleParameterValues**](FilterRuleParameterValues.md) | | [optional]
**name** | **String** | The name of the notification definition, which is unique in the profile. | [optional]
<file_sep># OrdersApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEOrder**](OrdersApi.md#dELETEOrder) | **DELETE** /v1/orders/{orderNumber} | Delete order
[**gETAllOrders**](OrdersApi.md#gETAllOrders) | **GET** /v1/orders | Get all orders
[**gETBreakdownInvoiceByOrder**](OrdersApi.md#gETBreakdownInvoiceByOrder) | **GET** /v1/invoices/{invoiceNumber}/amountBreakdownByOrder | Get breakdown of invoice by order
[**gETOrder**](OrdersApi.md#gETOrder) | **GET** /v1/orders/{orderNumber} | Get an order
[**gETOrderBillingInfo**](OrdersApi.md#gETOrderBillingInfo) | **GET** /v1/orders/{orderNumber}/billingInfo | Get billing information for order
[**gETOrderMetricsforEvergreenSubscription**](OrdersApi.md#gETOrderMetricsforEvergreenSubscription) | **GET** /v1/orders/{orderNumber}/evergreenMetrics/{subscriptionNumber} | Get order metrics for evergreen subscription
[**gETOrderRatedResult**](OrdersApi.md#gETOrderRatedResult) | **GET** /v1/orders/{orderNumber}/ratedResults | Get rated result for order
[**gETOrdersByInvoiceOwner**](OrdersApi.md#gETOrdersByInvoiceOwner) | **GET** /v1/orders/invoiceOwner/{accountNumber} | Get orders by invoice owner
[**gETOrdersBySubscriptionNumber**](OrdersApi.md#gETOrdersBySubscriptionNumber) | **GET** /v1/orders/subscription/{subscriptionNumber} | Get orders by subscription number
[**gETOrdersBySubscriptionOwner**](OrdersApi.md#gETOrdersBySubscriptionOwner) | **GET** /v1/orders/subscriptionOwner/{accountNumber} | Get orders by subscription owner
[**gETSubscriptionTermInfo**](OrdersApi.md#gETSubscriptionTermInfo) | **GET** /v1/orders/term/{subscriptionNumber} | Get term information for subscription
[**pOSTOrder**](OrdersApi.md#pOSTOrder) | **POST** /v1/orders | Create order
[**pOSTPreviewOrder**](OrdersApi.md#pOSTPreviewOrder) | **POST** /v1/orders/preview | Preview order
[**pOSTRequestBreakdownInvoiceItemsByOrder**](OrdersApi.md#pOSTRequestBreakdownInvoiceItemsByOrder) | **POST** /v1/invoices/items/amountBreakdownByOrder | Request breakdown of invoice items by order
[**pUTOrderTriggerDates**](OrdersApi.md#pUTOrderTriggerDates) | **PUT** /v1/orders/{orderNumber}/triggerDates | Update order action trigger dates
[**pUTUpdateOrderCustomFields**](OrdersApi.md#pUTUpdateOrderCustomFields) | **PUT** /v1/orders/{orderNumber}/customFields | Update order custom fields
[**pUTUpdateSubscriptionCustomFields**](OrdersApi.md#pUTUpdateSubscriptionCustomFields) | **PUT** /v1/subscriptions/{subscriptionNumber}/customFields | Update subscription custom fields
<a name="dELETEOrder"></a>
# **dELETEOrder**
> CommonResponseType dELETEOrder(orderNumber, zuoraEntityIds)
Delete order
**Note:** The migration to full [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) is in **Limited Availability**. We are actively soliciting feedback from a small set of early adopters before releasing as generally available. Deletes a specified order. All the subscriptions changed by this order are deleted. After the deletion, the subscriptions are rolled back to the previous version. You are not allowed to delete an order if the charges that are affected by this order are invoiced.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String orderNumber = "orderNumber_example"; // String | The number of the order to be deleted.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEOrder(orderNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#dELETEOrder");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderNumber** | **String**| The number of the order to be deleted. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAllOrders"></a>
# **gETAllOrders**
> GetAllOrdersResponseType gETAllOrders(zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate)
Get all orders
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves information about all orders in your tenant. By default, it returns the first page of the orders.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer page = 1; // Integer | The page number of the orders retrieved.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String dateFilterOption = "dateFilterOption_example"; // String | The date type to filter on. This field value can be orderDate or updatedDate. Default is orderDate.
LocalDate startDate = new LocalDate(); // LocalDate | The result will only contain the orders with the date of dateFilterOption later than or equal to this date.
LocalDate endDate = new LocalDate(); // LocalDate | The result will only contains orders with the date of dateFilterOption earlier than or equal to this date.
try {
GetAllOrdersResponseType result = apiInstance.gETAllOrders(zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETAllOrders");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**page** | **Integer**| The page number of the orders retrieved. | [optional] [default to 1]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**dateFilterOption** | **String**| The date type to filter on. This field value can be orderDate or updatedDate. Default is orderDate. | [optional]
**startDate** | **LocalDate**| The result will only contain the orders with the date of dateFilterOption later than or equal to this date. | [optional]
**endDate** | **LocalDate**| The result will only contains orders with the date of dateFilterOption earlier than or equal to this date. | [optional]
### Return type
[**GetAllOrdersResponseType**](GetAllOrdersResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETBreakdownInvoiceByOrder"></a>
# **gETBreakdownInvoiceByOrder**
> GetInvoiceAmountBreakdownByOrderResponse gETBreakdownInvoiceByOrder(invoiceNumber, zuoraEntityIds)
Get breakdown of invoice by order
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves a specified invoice that is broken down by orders. One invoice item might be broken down into a list of order related items. ### Phantom Invoice Item Phantom invoice items are generated via this API operation if an invoice item has a credit back scenario and the action you are making is prior to the end of a previous action. Phantom invoice items are not real invoice items and have no impact to billing. They are generated in parallel with the real invoice item and are used to properly allocate invoice items to the relevant orders. They share the same invoice item id with the real invoice item but with a prefix of \"Phantom-\". Also, the amount of a phantom invoice item is always zero. Below is an example phantom invoice item, which reflects in the period of 2017-10-01 to 2017-12-31: * Order 1 creates the initial subscription with an invoice breakdown amount of \"3000\". * Order 2 decreases the product quantity and so reduces the amount by \"1500\". * Order 3 cancels the subscription and so reduces the remaining amount by \"1500\". ``` { \"invoiceItemId\": \"Phantom-2c98903063f6d7b1016416df98c721b6\", \"subscriptionNumber\": \"55073a2fc6eb462aac0422aad7657f3c\", \"chargeNumber\": \"d-000001\", \"applyToChargeNumber\": null, \"startDate\": \"2017-10-01\", \"endDate\": \"2017-12-31\", \"amount\": 0, \"isCredit\": true, \"breakdownDetails\": [ { \"orderNumber\": \"980c4a4d414644339c113c7919a49fc2\", \"amount\": -1500, \"termNumber\": 1, \"startDate\": \"2017-10-01\", \"endDate\": \"2017-12-31\", \"orderItemId\": \"2c98903063f6d7b1016416df8c512147\", \"generatedReason\": \"Contraction\", \"orderActionId\": \"2c98903063f6d7b1016416df9738219b\" }, { \"orderNumber\": \"e0a839e8b33d476b9a86ca50e71ccbb4\", \"amount\": -1500, \"termNumber\": 1, \"startDate\": \"2017-10-01\", \"endDate\": \"2017-12-31\", \"orderItemId\": \"2c98903063f6d7b1016416df8c512147\", \"generatedReason\": \"DecreaseQuantity\", \"orderActionId\": \"2c98903063f6d7b1016416df92242167\" }, { \"orderNumber\": \"fd0e377b1bca4cc4805fc4cf1be72e05\", \"amount\": 3000, \"termNumber\": 1, \"startDate\": \"2017-10-01\", \"endDate\": \"2017-12-31\", \"orderItemId\": \"2c98903063f6d7b1016416df8c512147\", \"generatedReason\": \"Extension\", \"orderActionId\": \"2c98903063f6d7b1016416df8bb12136\" } ] } ```
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String invoiceNumber = "invoiceNumber_example"; // String | Number of invoice to be broken down.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetInvoiceAmountBreakdownByOrderResponse result = apiInstance.gETBreakdownInvoiceByOrder(invoiceNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETBreakdownInvoiceByOrder");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceNumber** | **String**| Number of invoice to be broken down. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetInvoiceAmountBreakdownByOrderResponse**](GetInvoiceAmountBreakdownByOrderResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETOrder"></a>
# **gETOrder**
> GetOrderResponse gETOrder(orderNumber, zuoraEntityIds)
Get an order
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the detailed information about a specified order.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String orderNumber = "orderNumber_example"; // String | The order number to be retrieved.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetOrderResponse result = apiInstance.gETOrder(orderNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETOrder");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderNumber** | **String**| The order number to be retrieved. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetOrderResponse**](GetOrderResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETOrderBillingInfo"></a>
# **gETOrderBillingInfo**
> GetOrderBillingInfoResponseType gETOrderBillingInfo(orderNumber, zuoraEntityIds, asOfDate)
Get billing information for order
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the billing information about a specified order. The information includes the billed and unbilled amount of the order.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String orderNumber = "orderNumber_example"; // String | The order number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
LocalDate asOfDate = new LocalDate(); // LocalDate | Billing states of the order will be calculated as of this date. Invoices with the invoice date later than this date will not be counted into the billed amount. The default value is today.
try {
GetOrderBillingInfoResponseType result = apiInstance.gETOrderBillingInfo(orderNumber, zuoraEntityIds, asOfDate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETOrderBillingInfo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderNumber** | **String**| The order number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**asOfDate** | **LocalDate**| Billing states of the order will be calculated as of this date. Invoices with the invoice date later than this date will not be counted into the billed amount. The default value is today. | [optional]
### Return type
[**GetOrderBillingInfoResponseType**](GetOrderBillingInfoResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETOrderMetricsforEvergreenSubscription"></a>
# **gETOrderMetricsforEvergreenSubscription**
> GetOrderResponseForEvergreen gETOrderMetricsforEvergreenSubscription(orderNumber, subscriptionNumber, startDate, endDate, zuoraEntityIds)
Get order metrics for evergreen subscription
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the metrics of an evergreen subscription in a specified order.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String orderNumber = "orderNumber_example"; // String | The order number.
String subscriptionNumber = "subscriptionNumber_example"; // String | The subscription number you want to get the metrics for.
LocalDate startDate = new LocalDate(); // LocalDate | The start date of the date range for which you want to get the metrics. The date must be in yyyy-mm-dd format. For example, 2017-12-03.
LocalDate endDate = new LocalDate(); // LocalDate | The end date of the date range for which you want to get the metrics. The date must be in yyyy-mm-dd format. For example, 2017-12-03.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetOrderResponseForEvergreen result = apiInstance.gETOrderMetricsforEvergreenSubscription(orderNumber, subscriptionNumber, startDate, endDate, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETOrderMetricsforEvergreenSubscription");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderNumber** | **String**| The order number. |
**subscriptionNumber** | **String**| The subscription number you want to get the metrics for. |
**startDate** | **LocalDate**| The start date of the date range for which you want to get the metrics. The date must be in yyyy-mm-dd format. For example, 2017-12-03. |
**endDate** | **LocalDate**| The end date of the date range for which you want to get the metrics. The date must be in yyyy-mm-dd format. For example, 2017-12-03. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetOrderResponseForEvergreen**](GetOrderResponseForEvergreen.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETOrderRatedResult"></a>
# **gETOrderRatedResult**
> GetOrderRatedResultResponseType gETOrderRatedResult(orderNumber, zuoraEntityIds)
Get rated result for order
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the rated results of all the subscriptions in the specified order.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String orderNumber = "orderNumber_example"; // String | The order number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetOrderRatedResultResponseType result = apiInstance.gETOrderRatedResult(orderNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETOrderRatedResult");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderNumber** | **String**| The order number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetOrderRatedResultResponseType**](GetOrderRatedResultResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETOrdersByInvoiceOwner"></a>
# **gETOrdersByInvoiceOwner**
> GetOrdersResponse gETOrdersByInvoiceOwner(accountNumber, zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate)
Get orders by invoice owner
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the detailed information about all orders for a specified invoice owner.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String accountNumber = "accountNumber_example"; // String | The invoice owner account number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer page = 56; // Integer | The page number of the orders retrieved. The default is 1.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String dateFilterOption = "dateFilterOption_example"; // String | The date type to filter on. This field value can be orderDate or updatedDate. Default is orderDate.
LocalDate startDate = new LocalDate(); // LocalDate | The result will only contain the orders with the date of dateFilterOption later than or equal to this date.
LocalDate endDate = new LocalDate(); // LocalDate | The result will only contain the orders with the date of dateFilterOption earlier than or equal to this date.
try {
GetOrdersResponse result = apiInstance.gETOrdersByInvoiceOwner(accountNumber, zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETOrdersByInvoiceOwner");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountNumber** | **String**| The invoice owner account number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**page** | **Integer**| The page number of the orders retrieved. The default is 1. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**dateFilterOption** | **String**| The date type to filter on. This field value can be orderDate or updatedDate. Default is orderDate. | [optional]
**startDate** | **LocalDate**| The result will only contain the orders with the date of dateFilterOption later than or equal to this date. | [optional]
**endDate** | **LocalDate**| The result will only contain the orders with the date of dateFilterOption earlier than or equal to this date. | [optional]
### Return type
[**GetOrdersResponse**](GetOrdersResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETOrdersBySubscriptionNumber"></a>
# **gETOrdersBySubscriptionNumber**
> GetOrdersResponse gETOrdersBySubscriptionNumber(subscriptionNumber, zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate)
Get orders by subscription number
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the detailed information about all orders for a specified subscription. Any orders containing the changes on the specified subscription are returned.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String subscriptionNumber = "subscriptionNumber_example"; // String | The subscription number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer page = 56; // Integer | The page number of the orders retrieved. The default is '1'.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String dateFilterOption = "dateFilterOption_example"; // String | The date type to filter on. This field value can be 'orderDate' or 'updatedDate'. Default is orderDate.
LocalDate startDate = new LocalDate(); // LocalDate | The result will only contain the orders with the date of 'dateFilterOption' later than or equal to this date.
LocalDate endDate = new LocalDate(); // LocalDate | The result will only contain the orders with the date of 'dateFilterOption' earlier than or equal to this date.
try {
GetOrdersResponse result = apiInstance.gETOrdersBySubscriptionNumber(subscriptionNumber, zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETOrdersBySubscriptionNumber");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionNumber** | **String**| The subscription number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**page** | **Integer**| The page number of the orders retrieved. The default is '1'. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**dateFilterOption** | **String**| The date type to filter on. This field value can be 'orderDate' or 'updatedDate'. Default is orderDate. | [optional]
**startDate** | **LocalDate**| The result will only contain the orders with the date of 'dateFilterOption' later than or equal to this date. | [optional]
**endDate** | **LocalDate**| The result will only contain the orders with the date of 'dateFilterOption' earlier than or equal to this date. | [optional]
### Return type
[**GetOrdersResponse**](GetOrdersResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETOrdersBySubscriptionOwner"></a>
# **gETOrdersBySubscriptionOwner**
> GetOrdersResponse gETOrdersBySubscriptionOwner(accountNumber, zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate)
Get orders by subscription owner
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the detailed information about all orders for a specified subscription owner. Any orders containing the changes on the subscriptions owned by this account are returned.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String accountNumber = "accountNumber_example"; // String | The subscription owner account number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer page = 56; // Integer | The page number of the orders retrieved. The default is 1.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String dateFilterOption = "dateFilterOption_example"; // String | The date type to filter on. This field value can be 'orderDate' or 'updatedDate'. Default is orderDate.
LocalDate startDate = new LocalDate(); // LocalDate | The result will only contain the orders with the date of 'dateFilterOption' later than or equal to this date.
LocalDate endDate = new LocalDate(); // LocalDate | The result will only contain the orders with the date of 'dateFilterOption' earlier than or equal to this date.
try {
GetOrdersResponse result = apiInstance.gETOrdersBySubscriptionOwner(accountNumber, zuoraEntityIds, page, pageSize, dateFilterOption, startDate, endDate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETOrdersBySubscriptionOwner");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountNumber** | **String**| The subscription owner account number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**page** | **Integer**| The page number of the orders retrieved. The default is 1. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**dateFilterOption** | **String**| The date type to filter on. This field value can be 'orderDate' or 'updatedDate'. Default is orderDate. | [optional]
**startDate** | **LocalDate**| The result will only contain the orders with the date of 'dateFilterOption' later than or equal to this date. | [optional]
**endDate** | **LocalDate**| The result will only contain the orders with the date of 'dateFilterOption' earlier than or equal to this date. | [optional]
### Return type
[**GetOrdersResponse**](GetOrdersResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETSubscriptionTermInfo"></a>
# **gETSubscriptionTermInfo**
> GetSubscriptionTermInfoResponseType gETSubscriptionTermInfo(subscriptionNumber, zuoraEntityIds, version, page, pageSize)
Get term information for subscription
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the terms of the specified subscription.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String subscriptionNumber = "subscriptionNumber_example"; // String | The number of the subscription to retrieve terms for. For example, A-S00000001.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer version = 56; // Integer | The version of the subscription to retrieve terms for. If you do not specify this parameter, Zuora returns the terms for the latest version of the subscription.
Integer page = 1; // Integer | The page number of the terms retrieved.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GetSubscriptionTermInfoResponseType result = apiInstance.gETSubscriptionTermInfo(subscriptionNumber, zuoraEntityIds, version, page, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#gETSubscriptionTermInfo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionNumber** | **String**| The number of the subscription to retrieve terms for. For example, A-S00000001. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**version** | **Integer**| The version of the subscription to retrieve terms for. If you do not specify this parameter, Zuora returns the terms for the latest version of the subscription. | [optional]
**page** | **Integer**| The page number of the terms retrieved. | [optional] [default to 1]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GetSubscriptionTermInfoResponseType**](GetSubscriptionTermInfoResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTOrder"></a>
# **pOSTOrder**
> PostOrderResponseType pOSTOrder(body, zuoraEntityIds, zuoraVersion)
Create order
**Note:** The migration to full [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) is in **Limited Availability**. We are actively soliciting feedback from a small set of early adopters before releasing as generally available. You can use this operation to create subscriptions and make changes to subscriptions by creating orders. The following tutorials demonstrate how to use this operation: * [Add a Product to a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/A_Add_a_Product_to_a_Subscription) * [Create a Ramp Deal](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/A_Create_a_Ramp_Deal) * [Create a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/A_Create_a_Subscription) * [Change the Owner of a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/C_Change_the_Owner_of_a_Subscription) * [Change the Terms and Conditions of a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/C_Change_the_Terms_and_Conditions_of_a_Subscription) * [Renew a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/C_Renew_a_Subscription) * [Renew a Subscription and Upgrade a Product](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/C_Renew_a_Subscription_and_Upgrade_a_Product) * [Replace a Product in a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/C_Replace_a_Product_in_a_Subscription) * [Update a Product in a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/C_Update_a_Product_in_a_Subscription) * [Cancel a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/D_Cancel_a_Subscription) * [Remove a Product from a Subscription](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AC_Orders_Tutorials/D_Remove_a_Product_from_a_Subscription) Creating a draft order is currently not supported. See [Known Limitations in Ord ers](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/C_Known_Limitations_in_Orders) for additional limitations. **Note:** When using this operation to create an account, create a subscription, run billing, and collect payment in a single call, if the payment processing fails then all the other steps will be rolled back. This means that the invoice will not be generated, the subscription will not be created, and the account will not be created.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
POSTOrderRequestType body = new POSTOrderRequestType(); // POSTOrderRequestType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * subscriptions * subscriptionNumbers
try {
PostOrderResponseType result = apiInstance.pOSTOrder(body, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#pOSTOrder");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**POSTOrderRequestType**](POSTOrderRequestType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * subscriptions * subscriptionNumbers | [optional]
### Return type
[**PostOrderResponseType**](PostOrderResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTPreviewOrder"></a>
# **pOSTPreviewOrder**
> PostOrderPreviewResponseType pOSTPreviewOrder(body, zuoraEntityIds)
Preview order
**Note:** The migration to full [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) is in **Limited Availability**. We are actively soliciting feedback from a small set of early adopters before releasing as generally available. Retrieves the preview of the charge metrics and invoice items of a specified order. This operation is only an order preview and no order is created.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
POSTOrderPreviewRequestType body = new POSTOrderPreviewRequestType(); // POSTOrderPreviewRequestType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PostOrderPreviewResponseType result = apiInstance.pOSTPreviewOrder(body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#pOSTPreviewOrder");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**POSTOrderPreviewRequestType**](POSTOrderPreviewRequestType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PostOrderPreviewResponseType**](PostOrderPreviewResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRequestBreakdownInvoiceItemsByOrder"></a>
# **pOSTRequestBreakdownInvoiceItemsByOrder**
> GetInvoiceAmountBreakdownByOrderResponse pOSTRequestBreakdownInvoiceItemsByOrder(body, zuoraEntityIds)
Request breakdown of invoice items by order
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Retrieves the specified invoice items which are broken down by orders. One invoice item might be broken down into a list of order related items. The maximum number of invoice items to retrieve is 1000.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
POSTInvoiceItemsForOrderBreakdown body = new POSTInvoiceItemsForOrderBreakdown(); // POSTInvoiceItemsForOrderBreakdown |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetInvoiceAmountBreakdownByOrderResponse result = apiInstance.pOSTRequestBreakdownInvoiceItemsByOrder(body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#pOSTRequestBreakdownInvoiceItemsByOrder");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**POSTInvoiceItemsForOrderBreakdown**](POSTInvoiceItemsForOrderBreakdown.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetInvoiceAmountBreakdownByOrderResponse**](GetInvoiceAmountBreakdownByOrderResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTOrderTriggerDates"></a>
# **pUTOrderTriggerDates**
> PUTOrderTriggerDatesResponseType pUTOrderTriggerDates(orderNumber, body, zuoraEntityIds)
Update order action trigger dates
**Note:** The migration to full [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) is in **Limited Availability**. We are actively soliciting feedback from a small set of early adopters before releasing as generally available. Updates a `CreateSubscription` order action's triggering dates.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String orderNumber = "orderNumber_example"; // String | Order number of a pending order in which you are to update a `CreateSubscription` order action's triggering dates.
PUTOrderActionTriggerDatesRequestType body = new PUTOrderActionTriggerDatesRequestType(); // PUTOrderActionTriggerDatesRequestType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTOrderTriggerDatesResponseType result = apiInstance.pUTOrderTriggerDates(orderNumber, body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#pUTOrderTriggerDates");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderNumber** | **String**| Order number of a pending order in which you are to update a `CreateSubscription` order action's triggering dates. |
**body** | [**PUTOrderActionTriggerDatesRequestType**](PUTOrderActionTriggerDatesRequestType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTOrderTriggerDatesResponseType**](PUTOrderTriggerDatesResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUpdateOrderCustomFields"></a>
# **pUTUpdateOrderCustomFields**
> CommonResponseType pUTUpdateOrderCustomFields(orderNumber, body, zuoraEntityIds)
Update order custom fields
**Note:** This feature is only available if you have the [Order Metrics](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Order_Metrics) feature enabled. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). We will investigate your use cases and data before enabling this feature for you. If you have the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) feature enabled, you already have the Order Metrics feature enabled. Updates the custom fields of a specified order.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String orderNumber = "orderNumber_example"; // String | The order number.
PUTOrderPatchRequestType body = new PUTOrderPatchRequestType(); // PUTOrderPatchRequestType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTUpdateOrderCustomFields(orderNumber, body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#pUTUpdateOrderCustomFields");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderNumber** | **String**| The order number. |
**body** | [**PUTOrderPatchRequestType**](PUTOrderPatchRequestType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUpdateSubscriptionCustomFields"></a>
# **pUTUpdateSubscriptionCustomFields**
> CommonResponseType pUTUpdateSubscriptionCustomFields(subscriptionNumber, body, zuoraEntityIds)
Update subscription custom fields
**Note:** The migration to full [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders) is in **Limited Availability**. We are actively soliciting feedback from a small set of early adopters before releasing as generally available. Updates the custom fields of a specified subscription.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OrdersApi;
OrdersApi apiInstance = new OrdersApi();
String subscriptionNumber = "subscriptionNumber_example"; // String | The subscription number to be updated.
PUTSubscriptionPatchRequestType body = new PUTSubscriptionPatchRequestType(); // PUTSubscriptionPatchRequestType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTUpdateSubscriptionCustomFields(subscriptionNumber, body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OrdersApi#pUTUpdateSubscriptionCustomFields");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionNumber** | **String**| The subscription number to be updated. |
**body** | [**PUTSubscriptionPatchRequestType**](PUTSubscriptionPatchRequestType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# ProxyGetCommunicationProfile
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**createdById** | **String** | | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional]
**description** | **String** | | [optional]
**id** | **String** | Object identifier. | [optional]
**profileName** | **String** | | [optional]
**updatedById** | **String** | | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional]
<file_sep># SummaryJournalEntriesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETESummaryJournalEntry**](SummaryJournalEntriesApi.md#dELETESummaryJournalEntry) | **DELETE** /v1/journal-entries/{je-number} | Delete summary journal entry
[**gETAllSummaryJournalEntries**](SummaryJournalEntriesApi.md#gETAllSummaryJournalEntries) | **GET** /v1/journal-entries/journal-runs/{jr-number} | Get all summary journal entries in a journal run
[**gETSummaryJournalEntry**](SummaryJournalEntriesApi.md#gETSummaryJournalEntry) | **GET** /v1/journal-entries/{je-number} | Get summary journal entry
[**pOSTSummaryJournalEntry**](SummaryJournalEntriesApi.md#pOSTSummaryJournalEntry) | **POST** /v1/journal-entries | Create summary journal entry
[**pUTBasicSummaryJournalEntry**](SummaryJournalEntriesApi.md#pUTBasicSummaryJournalEntry) | **PUT** /v1/journal-entries/{je-number}/basic-information | Update basic information of a summary journal entry
[**pUTSummaryJournalEntry**](SummaryJournalEntriesApi.md#pUTSummaryJournalEntry) | **PUT** /v1/journal-entries/{je-number}/cancel | Cancel summary journal entry
<a name="dELETESummaryJournalEntry"></a>
# **dELETESummaryJournalEntry**
> CommonResponseType dELETESummaryJournalEntry(jeNumber, zuoraEntityIds)
Delete summary journal entry
This reference describes how to delete a summary journal entry using the REST API. You must have the \"Delete Cancelled Journal Entry\" user permission enabled to delete summary journal entries. A summary journal entry must be canceled before it can be deleted.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SummaryJournalEntriesApi;
SummaryJournalEntriesApi apiInstance = new SummaryJournalEntriesApi();
String jeNumber = "jeNumber_example"; // String | Journal entry number in the format JE-00000001.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETESummaryJournalEntry(jeNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SummaryJournalEntriesApi#dELETESummaryJournalEntry");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jeNumber** | **String**| Journal entry number in the format JE-00000001. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAllSummaryJournalEntries"></a>
# **gETAllSummaryJournalEntries**
> GETJournalEntriesInJournalRunType gETAllSummaryJournalEntries(jrNumber, zuoraEntityIds, pageSize)
Get all summary journal entries in a journal run
This REST API reference describes how to retrieve information about all summary journal entries in a journal run.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SummaryJournalEntriesApi;
SummaryJournalEntriesApi apiInstance = new SummaryJournalEntriesApi();
String jrNumber = "jrNumber_example"; // String | Journal run number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 8; // Integer | Number of rows returned per page.
try {
GETJournalEntriesInJournalRunType result = apiInstance.gETAllSummaryJournalEntries(jrNumber, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SummaryJournalEntriesApi#gETAllSummaryJournalEntries");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jrNumber** | **String**| Journal run number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 8]
### Return type
[**GETJournalEntriesInJournalRunType**](GETJournalEntriesInJournalRunType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETSummaryJournalEntry"></a>
# **gETSummaryJournalEntry**
> GETJournalEntryDetailType gETSummaryJournalEntry(jeNumber, zuoraEntityIds)
Get summary journal entry
This REST API reference describes how to get information about a summary journal entry by its journal entry number.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SummaryJournalEntriesApi;
SummaryJournalEntriesApi apiInstance = new SummaryJournalEntriesApi();
String jeNumber = "jeNumber_example"; // String |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETJournalEntryDetailType result = apiInstance.gETSummaryJournalEntry(jeNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SummaryJournalEntriesApi#gETSummaryJournalEntry");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jeNumber** | **String**| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETJournalEntryDetailType**](GETJournalEntryDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTSummaryJournalEntry"></a>
# **pOSTSummaryJournalEntry**
> POSTJournalEntryResponseType pOSTSummaryJournalEntry(request, zuoraEntityIds)
Create summary journal entry
This REST API reference describes how to manually create a summary journal entry. Request and response field descriptions and sample code are provided. ## Requirements 1.The sum of debits must equal the sum of credits in the summary journal entry. 2.The following applies only if you use foreign currency conversion: * If you have configured Aggregate transactions with different currencies during a Journal Run to \"Yes\", the value of the **currency** field must be the same as your tenant's home currency. That is, you must create journal entries using your home currency. * All journal entries in an accounting period must either all be aggregated or all be unaggregated. You cannot have a mix of aggregated and unaggregated journal entries in the same accounting period.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SummaryJournalEntriesApi;
SummaryJournalEntriesApi apiInstance = new SummaryJournalEntriesApi();
POSTJournalEntryType request = new POSTJournalEntryType(); // POSTJournalEntryType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTJournalEntryResponseType result = apiInstance.pOSTSummaryJournalEntry(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SummaryJournalEntriesApi#pOSTSummaryJournalEntry");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTJournalEntryType**](POSTJournalEntryType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTJournalEntryResponseType**](POSTJournalEntryResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTBasicSummaryJournalEntry"></a>
# **pUTBasicSummaryJournalEntry**
> CommonResponseType pUTBasicSummaryJournalEntry(jeNumber, request, zuoraEntityIds)
Update basic information of a summary journal entry
This REST API reference describes how to update the basic information of a summary journal entry. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SummaryJournalEntriesApi;
SummaryJournalEntriesApi apiInstance = new SummaryJournalEntriesApi();
String jeNumber = "jeNumber_example"; // String | Journal entry number in the format JE-00000001.
PUTBasicSummaryJournalEntryType request = new PUTBasicSummaryJournalEntryType(); // PUTBasicSummaryJournalEntryType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTBasicSummaryJournalEntry(jeNumber, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SummaryJournalEntriesApi#pUTBasicSummaryJournalEntry");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jeNumber** | **String**| Journal entry number in the format JE-00000001. |
**request** | [**PUTBasicSummaryJournalEntryType**](PUTBasicSummaryJournalEntryType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTSummaryJournalEntry"></a>
# **pUTSummaryJournalEntry**
> CommonResponseType pUTSummaryJournalEntry(jeNumber, zuoraEntityIds)
Cancel summary journal entry
This reference describes how to cancel a summary journal entry using the REST API. You must have the \"Cancel Journal Entry\" user permission enabled to cancel summary journal entries. A summary journal entry cannot be canceled if its Transferred to Accounting status is \"Yes\" or \"Processing\".
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.SummaryJournalEntriesApi;
SummaryJournalEntriesApi apiInstance = new SummaryJournalEntriesApi();
String jeNumber = "jeNumber_example"; // String | Journal entry number in the format JE-00000001.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTSummaryJournalEntry(jeNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SummaryJournalEntriesApi#pUTSummaryJournalEntry");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jeNumber** | **String**| Journal entry number in the format JE-00000001. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# PutBatchInvoiceType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoices** | [**List<BatchInvoiceType>**](BatchInvoiceType.md) | Container for invoice update details. | [optional]
<file_sep>
# ProxyModifyRefund
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the refund's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the refund was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | **String** | Specifies whether the refund should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. Must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. **Character limit**: 32 **V****alues**: a valid reason code | [optional]
**status** | **String** | The status of the refund. **Character limit**: 10 **Values**: automatically generated: - `Canceled` - `Error` - `Processed` - `Processing` | [optional]
**transferredToAccounting** | **String** | Specifies whether or not the object has been transferred to an external accounting system. Use this field for integrations with accounting systems such as NetSuite. **Character limit**: 10 **Values**: automatically generated: - `Processing` - `Yes` - `Error` - `Ignore` | [optional]
<file_sep># OAuthApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**createToken**](OAuthApi.md#createToken) | **POST** /oauth/token | Generate an OAuth token
<a name="createToken"></a>
# **createToken**
> TokenResponse createToken(clientId, clientSecret, grantType, zuoraTrackId)
Generate an OAuth token
Generates a bearer token that enables an OAuth client to authenticate with the Zuora REST API. The OAuth client must have been created using the Zuora UI. See [Authentication](https://www.zuora.com/developer/api-reference/#section/Authentication) for more information. **Note:** When using this operation, do not set any authentication headers such as `Authorization`, `apiAccessKeyId`, or `apiSecretAccessKey`. You should not use this operation to generate a large number of bearer tokens in a short period of time; each token should be used until it expires. If you receive a 429 Too Many Requests response when using this operation, reduce the frequency of requests. This endpoint is rate limited by IP address.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OAuthApi;
OAuthApi apiInstance = new OAuthApi();
String clientId = "clientId_example"; // String | The Client ID of the OAuth client.
String clientSecret = "clientSecret_example"; // String | The Client Secret that was displayed when the OAuth client was created.
String grantType = "grantType_example"; // String | The OAuth grant type that will be used to generate the token. The value of this parameter must be `client_credentials`.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
TokenResponse result = apiInstance.createToken(clientId, clientSecret, grantType, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OAuthApi#createToken");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**clientId** | **String**| The Client ID of the OAuth client. |
**clientSecret** | **String**| The Client Secret that was displayed when the OAuth client was created. |
**grantType** | **String**| The OAuth grant type that will be used to generate the token. The value of this parameter must be `client_credentials`. | [enum: client_credentials]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**TokenResponse**](TokenResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: application/json; charset=utf-8
<file_sep>
# POSTBillingPreviewCreditMemoItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The amount of the credit memo item. For tax-inclusive credit memo items, the amount indicates the credit memo item amount including tax. For tax-exclusive credit memo items, the amount indicates the credit memo item amount excluding tax | [optional]
**amountWithoutTax** | **Double** | The credit memo item amount excluding tax. | [optional]
**chargeDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the credit memo item is created. | [optional]
**chargeNumber** | **String** | Number of the charge. | [optional]
**chargeType** | **String** | The type of charge. Possible values are `OneTime`, `Recurring`, and `Usage`. | [optional]
**comment** | **String** | Comment of the credit memo item. | [optional]
**id** | **String** | Credit memo item id. | [optional]
**processingType** | **String** | Identifies the kind of charge. Possible values: * charge * discount * prepayment * tax | [optional]
**quantity** | **String** | Quantity of this item, in the configured unit of measure for the charge. | [optional]
**ratePlanChargeId** | **String** | Id of the rate plan charge associated with this item. | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | End date of the service period for this item, i.e., the last day of the service period, in yyyy-mm-dd format. | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | Start date of the service period for this item, in yyyy-mm-dd format. If the charge is a one-time fee, this is the date of that charge. | [optional]
**sku** | **String** | Unique SKU for the product associated with this item. | [optional]
**skuName** | **String** | Name of the unique SKU for the product associated with this item. | [optional]
**subscriptionId** | **String** | ID of the subscription associated with this item. | [optional]
**subscriptionNumber** | **String** | Name of the subscription associated with this item. | [optional]
**unitOfMeasure** | **String** | Unit used to measure consumption. | [optional]
<file_sep>
# AccountObjectNSFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**classNS** | **String** | Value of the Class field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**customerTypeNS** | [**CustomerTypeNSEnum**](#CustomerTypeNSEnum) | Value of the Customer Type field for the corresponding customer account in NetSuite. The Customer Type field is used when the customer account is created in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Value of the Department field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the account's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Value of the Location field for the corresponding customer account in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Value of the Subsidiary field for the corresponding customer account in NetSuite. The Subsidiary field is required if you use NetSuite OneWorld. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the account was sychronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | [**SynctoNetSuiteNSEnum**](#SynctoNetSuiteNSEnum) | Specifies whether the account should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
<a name="CustomerTypeNSEnum"></a>
## Enum: CustomerTypeNSEnum
Name | Value
---- | -----
COMPANY | "Company"
INDIVIDUAL | "Individual"
<a name="SynctoNetSuiteNSEnum"></a>
## Enum: SynctoNetSuiteNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<file_sep>
# ErrorResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**reasons** | [**List<ErrorResponseReasons>**](ErrorResponseReasons.md) | | [optional]
<file_sep>
# GETARPaymentTypeFinanceInformation
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**bankAccountAccountingCode** | **String** | The accounting code that maps to a bank account in your accounting system. | [optional]
**bankAccountAccountingCodeType** | **String** | The type of the accounting code that maps to a bank account in your accounting system. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the payment was transferred to an external accounting system. Use this field for integration with accounting systems, such as NetSuite. | [optional]
**unappliedPaymentAccountingCode** | **String** | The accounting code for the unapplied payment. | [optional]
**unappliedPaymentAccountingCodeType** | **String** | The type of the accounting code for the unapplied payment. | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
NO | "No"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# GETCreditMemoItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The amount of the credit memo item. For tax-inclusive credit memo items, the amount indicates the credit memo item amount including tax. For tax-exclusive credit memo items, the amount indicates the credit memo item amount excluding tax. | [optional]
**amountWithoutTax** | **Double** | The credit memo item amount excluding tax. | [optional]
**appliedAmount** | **Double** | The applied amount of the credit memo item. | [optional]
**comment** | **String** | Comments about the credit memo item. | [optional]
**createdById** | **String** | The ID of the Zuora user who created the credit memo item. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the credit memo item was created, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 15:31:10. | [optional]
**creditTaxItems** | [**List<GETCMTaxItemType>**](GETCMTaxItemType.md) | Container for credit memo taxation items. | [optional]
**financeInformation** | [**GETCreditMemoItemTypeFinanceInformation**](GETCreditMemoItemTypeFinanceInformation.md) | | [optional]
**id** | **String** | The ID of the credit memo item. | [optional]
**refundAmount** | **Double** | The amount of the refund on the credit memo item. | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | The service end date of the credit memo item. | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | The service start date of the credit memo item. If the associated charge is a one-time fee, this date is the date of that charge. | [optional]
**sku** | **String** | The SKU for the product associated with the credit memo item. | [optional]
**skuName** | **String** | The name of the SKU. | [optional]
**sourceItemId** | **String** | The ID of the source item. | [optional]
**sourceItemType** | [**SourceItemTypeEnum**](#SourceItemTypeEnum) | The type of the source item. | [optional]
**subscriptionId** | **String** | The ID of the subscription associated with the credit memo item. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**unappliedAmount** | **Double** | The unapplied amount of the credit memo item. | [optional]
**updatedById** | **String** | The ID of the Zuora user who last updated the credit memo item. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the credit memo item was last updated, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-02 15:36:10. | [optional]
<a name="SourceItemTypeEnum"></a>
## Enum: SourceItemTypeEnum
Name | Value
---- | -----
SUBSCRIPTIONCOMPONENT | "SubscriptionComponent"
INVOICEDETAIL | "InvoiceDetail"
PRODUCTRATEPLANCHARGE | "ProductRatePlanCharge"
<file_sep>
# GETPaymentRunSummaryTotalValues
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**totalValueOfCreditBalance** | **String** | **Note:** This field is only available if you have the Credit Balance feature enabled. The total amount of credit balance after the payment run is completed. | [optional]
**totalValueOfCreditMemos** | **String** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total amount of credit memos that are successfully processed in the payment run. | [optional]
**totalValueOfDebitMemos** | **String** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total amount of debit memos that are picked up for processing in the payment run. | [optional]
**totalValueOfErrors** | **String** | The total amount of receivables associated with the payments with the status of `Error` and `Processing`. | [optional]
**totalValueOfInvoices** | **String** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total amount of invoices that are picked up for processing in the payment run. | [optional]
**totalValueOfPayments** | **String** | The total amount of payments that are successfully processed in the payment run. | [optional]
**totalValueOfReceivables** | **String** | The total amount of receivables associated with the payment run. The value of this field is the sum of the value of the `totalValueOfInvoices` field and that of the `totalValueOfDebitMemos` field. | [optional]
**totalValueOfUnappliedPayments** | **Integer** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total amount of unapplied payments that are successfully processed in the payment run. | [optional]
**totalValueOfUnprocessedDebitMemos** | **String** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total amount of debit memos with remaining positive balances after the payment run is completed. | [optional]
**totalValueOfUnprocessedInvoices** | **String** | **Note:** This field is only available if you have the Invoice Settlement feature enabled. The total amount of invoices with remaining positive balances after the payment run is completed. | [optional]
**totalValueOfUnprocessedReceivables** | **String** | The total amount of receivables with remaining positive balances after the payment run is completed. | [optional]
<file_sep>
# POSTInvoiceItemsForOrderBreakdown
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoiceItemIds** | **List<String>** | The invoice items to break down. |
**invoiceNumber** | **String** | The invoice number which the invoice items belong to. |
<file_sep>
# ProxyCreatePayment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the payment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the payment was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The unique account ID for the customer that the payment is for. |
**accountingCode** | **String** | The aacccounting code for the payment. Accounting codes group transactions that contain similar accounting attributes. | [optional]
**amount** | **Double** | The amount of the payment. | [optional]
**appliedCreditBalanceAmount** | **Double** | The amount of the payment to apply to a credit balance. This field is only required if the `AppliedInvoiceAmount` field value is null. | [optional]
**appliedInvoiceAmount** | [**BigDecimal**](BigDecimal.md) | The amount of the payment to apply to an invoice. This field is only required if either the `InvoiceId` or `InvoiceNumber` field is not null. | [optional]
**authTransactionId** | **String** | The authorization transaction ID from the payment gateway. Use this field for electronic payments, such as credit cards. | [optional]
**comment** | **String** | Additional information related to the payment. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the payment takes effect. |
**gateway** | **String** | The name of the gateway instance that processes the payment. When creating a payment, the value of this field must be a valid gateway instance name, and this gateway must support the specific payment method. If no value is specified, the default gateway on the Account will be used. | [optional]
**gatewayOptionData** | [**ProxyCreatePaymentGatewayOptionData**](ProxyCreatePaymentGatewayOptionData.md) | | [optional]
**gatewayOrderId** | **String** | A merchant-specified natural key value that can be passed to the electronic payment gateway when a payment is created. If not specified, the payment number will be passed in instead. Gateways check duplicates on the gateway order ID to ensure that the merchant do not accidentally enter the same transaction twice. This ID can also be used to do reconciliation and tie the payment to a natural key in external systems. The source of this ID varies by merchant. Some merchants use their shopping cart order IDs, and others use something different. Merchants use this ID to track transactions in their eCommerce systems. | [optional]
**gatewayResponse** | **String** | The message returned from the payment gateway for the payment. This message is gateway-dependent. | [optional]
**gatewayResponseCode** | **String** | The code returned from the payment gateway for the payment. This code is gateway-dependent. | [optional]
**gatewayState** | [**GatewayStateEnum**](#GatewayStateEnum) | The status of the payment in the gateway; use for reconciliation. | [optional]
**invoiceId** | **String** | The ID of the invoice that the payment is applied to. When applying a payment to a single invoice, this field is only required if the `InvoiceNumber` field is null. | [optional]
**invoiceNumber** | **String** | The unique identification number for the invoice that the payment is applied to. When applying a payment to a single invoice, this field is only required if the `InvoiceId` field is null. | [optional]
**invoicePaymentData** | [**InvoicePaymentData**](InvoicePaymentData.md) | | [optional]
**paymentMethodId** | **String** | The ID of the payment method used for the payment. |
**paymentNumber** | **String** | The unique identification number of the payment. For example, P-00000028. | [optional]
**referenceId** | **String** | The transaction ID returned by the payment gateway. Use this field to reconcile payments between your gateway and Zuora Payments. | [optional]
**softDescriptor** | **String** | A payment gateway-specific field that maps to Zuora for the gateways, Orbital, Vantiv and Verifi. Zuora passes this field to Verifi directly without verification. In general, this field will be defaulted by the gateway. For Orbital, this field contains two fields separated by an asterisk, `SDMerchantName` and `SDProductionInfo`. For more information, contact your payment gateway. | [optional]
**softDescriptorPhone** | **String** | A payment gateway-specific field that maps to Zuora for the gateways, Orbital, Vantiv and Verifi. Verifi and Orbital determine how to format this string. For more information, contact your payment gateway. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the payment in Zuora. The value depends on the type of payment. For electronic payments, the status can be `Processed`, `Error`, or `Voided`. For external payments, the status can be `Processed` or `Canceled`. |
**type** | [**TypeEnum**](#TypeEnum) | The type of the payment, whether the payment is external or electronic. |
<a name="GatewayStateEnum"></a>
## Enum: GatewayStateEnum
Name | Value
---- | -----
MARKEDFORSUBMISSION | "MarkedForSubmission"
SUBMITTED | "Submitted"
SETTLED | "Settled"
NOTSUBMITTED | "NotSubmitted"
FAILEDTOSETTLE | "FailedToSettle"
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PROCESSED | "Processed"
ERROR | "Error"
VOIDED | "Voided"
CANCELED | "Canceled"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
EXTERNAL | "External"
ELECTRONIC | "Electronic"
<file_sep>
# CreatePaymentMethodPayPalAdaptive
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**preapprovalKey** | **String** | The PayPal preapproval key. | [optional]
<file_sep>
# GETAccountSummaryTypeTaxInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**vaTId** | **String** | EU Value Added Tax ID. | [optional]
**companyCode** | **String** | Unique code that identifies a company account in Avalara. | [optional]
**exemptCertificateId** | **String** | ID of the customer tax exemption certificate. | [optional]
**exemptCertificateType** | **String** | Type of tax exemption certificate that the customer holds. | [optional]
**exemptDescription** | **String** | Description of the tax exemption certificate that the customer holds. | [optional]
**exemptEffectiveDate** | [**LocalDate**](LocalDate.md) | Date when the customer tax exemption starts. | [optional]
**exemptEntityUseCode** | **String** | A unique entity use code to apply exemptions in Avalara AvaTax. This account-level field is required only when you choose Avalara as your tax engine. See [Exempt Transactions](https://developer.avalara.com/avatax/handling-tax-exempt-customers/)for more details. | [optional]
**exemptExpirationDate** | [**LocalDate**](LocalDate.md) | Date when the customer tax exemption expires. | [optional]
**exemptIssuingJurisdiction** | **String** | Jurisdiction in which the customer tax exemption certificate was issued. | [optional]
**exemptStatus** | **String** | Status of the account tax exemption. | [optional]
<file_sep>
# POSTSubscriptionResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**contractedMrr** | **String** | Monthly recurring revenue of the subscription. | [optional]
**creditMemoId** | **String** | The credit memo ID, if a credit memo is generated during the subscription process. **Note:** This field is only available if you have the Invoice Settlements feature enabled. | [optional]
**invoiceId** | **String** | Invoice ID, if an invoice is generated during the subscription process. | [optional]
**paidAmount** | **String** | Payment amount, if a payment is collected. | [optional]
**paymentId** | **String** | Payment ID, if a payment is collected. | [optional]
**subscriptionId** | **String** | | [optional]
**subscriptionNumber** | **String** | | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**totalContractedValue** | **String** | Total contracted value of the subscription. | [optional]
<file_sep>
# ProductObjectNSFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the product's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**itemTypeNS** | [**ItemTypeNSEnum**](#ItemTypeNSEnum) | Type of item that is created in NetSuite for the product. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the product was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
<a name="ItemTypeNSEnum"></a>
## Enum: ItemTypeNSEnum
Name | Value
---- | -----
INVENTORY | "Inventory"
NON_INVENTORY | "Non Inventory"
SERVICE | "Service"
<file_sep>
# GetOrdersResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**nextPage** | **String** | URL to retrieve the next page of the response if it exists; otherwise absent. | [optional]
**orders** | [**List<Order>**](Order.md) | | [optional]
<file_sep>
# GETPaymentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the payment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the payment was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountID** | **String** | Customer account ID. | [optional]
**accountName** | **String** | Customer account name. | [optional]
**accountNumber** | **String** | Customer account number. | [optional]
**amount** | **String** | Payment amount. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | Effective payment date as _yyyy-mm-dd_. | [optional]
**gatewayTransactionNumber** | **String** | Transaction ID from payment gateway. | [optional]
**id** | **String** | PaymentID. | [optional]
**paidInvoices** | [**List<GETPaidInvoicesType>**](GETPaidInvoicesType.md) | Information about one or more invoices to which this payment was applied: | [optional]
**paymentMethodID** | **String** | Payment method. | [optional]
**paymentNumber** | **String** | Unique payment number. | [optional]
**status** | **String** | Possible values are: `Draft`, `Processing`, `Processed`, `Error`, `Voided`, `Canceled`, `Posted. | [optional]
**type** | **String** | Possible values are: `External`, `Electronic`. | [optional]
<file_sep>
# ChargePreviewMetricsTcv
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**discount** | [**BigDecimal**](BigDecimal.md) | Always equals to discountTcb. | [optional]
**discountDelta** | [**BigDecimal**](BigDecimal.md) | Always equals to delta discountTcb. | [optional]
**regular** | [**BigDecimal**](BigDecimal.md) | | [optional]
**regularDelta** | [**BigDecimal**](BigDecimal.md) | | [optional]
<file_sep>
# LastTerm
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**period** | **Integer** | Specify only when the termType is 'TERMED'. | [optional]
**periodType** | [**PeriodTypeEnum**](#PeriodTypeEnum) | Specify only when the termType is 'TERMED'. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The start date of the last term. You are not allowed to change the term start date after you have made the 'RenewSubscription' order action. | [optional]
**termType** | [**TermTypeEnum**](#TermTypeEnum) | |
<a name="PeriodTypeEnum"></a>
## Enum: PeriodTypeEnum
Name | Value
---- | -----
MONTH | "Month"
YEAR | "Year"
DAY | "Day"
WEEK | "Week"
<a name="TermTypeEnum"></a>
## Enum: TermTypeEnum
Name | Value
---- | -----
TERMED | "TERMED"
EVERGREEN | "EVERGREEN"
<file_sep>
# POSTCreditMemoItemsForOrderBreakdown
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**memoItemIds** | **List<String>** | The credit memo items to break down. |
**memoNumber** | **String** | The credit memo number which the invoice items belong to. |
<file_sep>
# GETAccountingCodeItemWithoutSuccessType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**category** | [**CategoryEnum**](#CategoryEnum) | The category associated with the accounting code. | [optional]
**createdBy** | **String** | The ID of the user who created the accounting code. | [optional]
**createdOn** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time when the accounting code was created. | [optional]
**glAccountName** | **String** | Name of the account in your general ledger. Field only available if you have Zuora Finance enabled. | [optional]
**glAccountNumber** | **String** | Account number in your general ledger. Field only available if you have Zuora Finance enabled. | [optional]
**id** | **String** | ID of the accounting code. | [optional]
**name** | **String** | Name of the accounting code. | [optional]
**notes** | **String** | Any optional notes for the accounting code. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The accounting code status. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Accounting code type. Note that `On-Account Receivable` is only available if you enable the Invoice Settlement feature. | [optional]
**updatedBy** | **String** | The ID of the user who last updated the accounting code. | [optional]
**updatedOn** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time when the accounting code was last updated. | [optional]
<a name="CategoryEnum"></a>
## Enum: CategoryEnum
Name | Value
---- | -----
ASSETS | "Assets"
LIABILITIES | "Liabilities"
EQUITY | "Equity"
REVENUE | "Revenue"
EXPENSES | "Expenses"
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
ACTIVE | "Active"
INACTIVE | "Inactive"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
ACCOUNTSRECEIVABLE | "AccountsReceivable"
ON_ACCOUNT_RECEIVABLE | "On-Account Receivable"
CASH | "Cash"
OTHERASSETS | "OtherAssets"
CUSTOMERCASHONACCOUNT | "CustomerCashOnAccount"
DEFERREDREVENUE | "DeferredRevenue"
SALESTAXPAYABLE | "SalesTaxPayable"
OTHERLIABILITIES | "OtherLiabilities"
SALESREVENUE | "SalesRevenue"
SALESDISCOUNTS | "SalesDiscounts"
OTHERREVENUE | "OtherRevenue"
OTHEREQUITY | "OtherEquity"
BADDEBT | "BadDebt"
OTHEREXPENSES | "OtherExpenses"
<file_sep>
# CreditMemoObjectNSFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the credit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the credit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
<file_sep>
# PUTAllocateManuallyType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**eventType** | [**EventTypeEnum**](#EventTypeEnum) | Label of the revenue event type. Revenue event type labels can be duplicated. You can configure your revenue event type labels by navigating to **Settings > Finance > Configure Revenue Event Types** in the Zuora UI. Note that `Credit Memo Posted` and `Debit Memo Posted` are only available if you enable the Invoice Settlement feature. | [optional]
**eventTypeSystemId** | **String** | System ID of the revenue event type. Each eventType has a unique system ID. You can configure your revenue event type system IDs by navigating to **Settings > Finance > Configure Revenue Event Types** in the Zuora UI. Cannot be duplicated. | [optional]
**notes** | **String** | Additional information about this record. | [optional]
**revenueDistributions** | [**List<POSTDistributionItemType>**](POSTDistributionItemType.md) | An array of revenue distributions. Represents how you want to distribute revenue for this revenue schedule. You can distribute revenue into a maximum of 250 accounting periods with one revenue schedule. | [optional]
<a name="EventTypeEnum"></a>
## Enum: EventTypeEnum
Name | Value
---- | -----
INVOICE_POSTED | "Invoice Posted"
INVOICE_ITEM_ADJUSTMENT_CREATED | "Invoice Item Adjustment Created"
INVOICE_CANCELED | "Invoice Canceled"
INVOICE_ITEM_ADJUSTMENT_CANCELED | "Invoice Item Adjustment Canceled"
REVENUE_DISTRIBUTED | "Revenue Distributed"
CREDIT_MEMO_POSTED | "Credit Memo Posted"
DEBIT_MEMO_POSTED | "Debit Memo Posted"
<file_sep>
# RatePlanChargeData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ratePlanCharge** | [**RatePlanChargeDataRatePlanCharge**](RatePlanChargeDataRatePlanCharge.md) | |
**ratePlanChargeTier** | [**List<RatePlanChargeTier>**](RatePlanChargeTier.md) | | [optional]
<file_sep># ProductRatePlansApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETProductRatePlans**](ProductRatePlansApi.md#gETProductRatePlans) | **GET** /v1/rateplan/{product_id}/productRatePlan | Get product rate plans
[**objectDELETEProductRatePlan**](ProductRatePlansApi.md#objectDELETEProductRatePlan) | **DELETE** /v1/object/product-rate-plan/{id} | CRUD: Delete ProductRatePlan
[**objectGETProductRatePlan**](ProductRatePlansApi.md#objectGETProductRatePlan) | **GET** /v1/object/product-rate-plan/{id} | CRUD: Retrieve ProductRatePlan
[**objectPOSTProductRatePlan**](ProductRatePlansApi.md#objectPOSTProductRatePlan) | **POST** /v1/object/product-rate-plan | CRUD: Create ProductRatePlan
[**objectPUTProductRatePlan**](ProductRatePlansApi.md#objectPUTProductRatePlan) | **PUT** /v1/object/product-rate-plan/{id} | CRUD: Update ProductRatePlan
<a name="gETProductRatePlans"></a>
# **gETProductRatePlans**
> GETProductRatePlansResponse gETProductRatePlans(productId, zuoraEntityIds, pageSize)
Get product rate plans
Retrieves information about all product rate plans of a specific product.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlansApi;
ProductRatePlansApi apiInstance = new ProductRatePlansApi();
String productId = "productId_example"; // String | The unique ID of a product. For example, 2c92c0f96487e16a016487f663c71a61.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETProductRatePlansResponse result = apiInstance.gETProductRatePlans(productId, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlansApi#gETProductRatePlans");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**productId** | **String**| The unique ID of a product. For example, 2c92c0f96487e16a016487f663c71a61. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETProductRatePlansResponse**](GETProductRatePlansResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETEProductRatePlan"></a>
# **objectDELETEProductRatePlan**
> ProxyDeleteResponse objectDELETEProductRatePlan(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete ProductRatePlan
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlansApi;
ProductRatePlansApi apiInstance = new ProductRatePlansApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEProductRatePlan(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlansApi#objectDELETEProductRatePlan");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETProductRatePlan"></a>
# **objectGETProductRatePlan**
> ProxyGetProductRatePlan objectGETProductRatePlan(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve ProductRatePlan
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlansApi;
ProductRatePlansApi apiInstance = new ProductRatePlansApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetProductRatePlan result = apiInstance.objectGETProductRatePlan(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlansApi#objectGETProductRatePlan");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetProductRatePlan**](ProxyGetProductRatePlan.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTProductRatePlan"></a>
# **objectPOSTProductRatePlan**
> ProxyCreateOrModifyResponse objectPOSTProductRatePlan(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create ProductRatePlan
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlansApi;
ProductRatePlansApi apiInstance = new ProductRatePlansApi();
ProxyCreateProductRatePlan createRequest = new ProxyCreateProductRatePlan(); // ProxyCreateProductRatePlan |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTProductRatePlan(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlansApi#objectPOSTProductRatePlan");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateProductRatePlan**](ProxyCreateProductRatePlan.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTProductRatePlan"></a>
# **objectPUTProductRatePlan**
> ProxyCreateOrModifyResponse objectPUTProductRatePlan(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update ProductRatePlan
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlansApi;
ProductRatePlansApi apiInstance = new ProductRatePlansApi();
String id = "id_example"; // String | Object id
ProxyModifyProductRatePlan modifyRequest = new ProxyModifyProductRatePlan(); // ProxyModifyProductRatePlan |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTProductRatePlan(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlansApi#objectPUTProductRatePlan");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyProductRatePlan**](ProxyModifyProductRatePlan.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># TaxationItemsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETETaxationItem**](TaxationItemsApi.md#dELETETaxationItem) | **DELETE** /v1/taxationitems/{id} | Delete taxation item
[**gETTaxationItem**](TaxationItemsApi.md#gETTaxationItem) | **GET** /v1/taxationitems/{id} | Get taxation item
[**objectDELETETaxationItem**](TaxationItemsApi.md#objectDELETETaxationItem) | **DELETE** /v1/object/taxation-item/{id} | CRUD: Delete TaxationItem
[**objectGETTaxationItem**](TaxationItemsApi.md#objectGETTaxationItem) | **GET** /v1/object/taxation-item/{id} | CRUD: Retrieve TaxationItem
[**objectPOSTTaxationItem**](TaxationItemsApi.md#objectPOSTTaxationItem) | **POST** /v1/object/taxation-item | CRUD: Create TaxationItem
[**objectPUTTaxationItem**](TaxationItemsApi.md#objectPUTTaxationItem) | **PUT** /v1/object/taxation-item/{id} | CRUD: Update TaxationItem
[**pUTTaxationItem**](TaxationItemsApi.md#pUTTaxationItem) | **PUT** /v1/taxationitems/{id} | Update taxation item
<a name="dELETETaxationItem"></a>
# **dELETETaxationItem**
> CommonResponseType dELETETaxationItem(id, zuoraEntityIds)
Delete taxation item
Deletes a specific taxation item by ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TaxationItemsApi;
TaxationItemsApi apiInstance = new TaxationItemsApi();
String id = "id_example"; // String | The unique ID of a taxation item.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETETaxationItem(id, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TaxationItemsApi#dELETETaxationItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The unique ID of a taxation item. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETTaxationItem"></a>
# **gETTaxationItem**
> GETTaxationItemType gETTaxationItem(id, zuoraEntityIds)
Get taxation item
Retrieves the information about a specific taxation item by ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TaxationItemsApi;
TaxationItemsApi apiInstance = new TaxationItemsApi();
String id = "id_example"; // String | The unique ID of a taxation item.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETTaxationItemType result = apiInstance.gETTaxationItem(id, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TaxationItemsApi#gETTaxationItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The unique ID of a taxation item. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETTaxationItemType**](GETTaxationItemType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETETaxationItem"></a>
# **objectDELETETaxationItem**
> ProxyDeleteResponse objectDELETETaxationItem(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete TaxationItem
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TaxationItemsApi;
TaxationItemsApi apiInstance = new TaxationItemsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETETaxationItem(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TaxationItemsApi#objectDELETETaxationItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETTaxationItem"></a>
# **objectGETTaxationItem**
> ProxyGetTaxationItem objectGETTaxationItem(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve TaxationItem
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TaxationItemsApi;
TaxationItemsApi apiInstance = new TaxationItemsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetTaxationItem result = apiInstance.objectGETTaxationItem(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TaxationItemsApi#objectGETTaxationItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetTaxationItem**](ProxyGetTaxationItem.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTTaxationItem"></a>
# **objectPOSTTaxationItem**
> ProxyCreateOrModifyResponse objectPOSTTaxationItem(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create TaxationItem
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TaxationItemsApi;
TaxationItemsApi apiInstance = new TaxationItemsApi();
ProxyCreateTaxationItem createRequest = new ProxyCreateTaxationItem(); // ProxyCreateTaxationItem |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTTaxationItem(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TaxationItemsApi#objectPOSTTaxationItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateTaxationItem**](ProxyCreateTaxationItem.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTTaxationItem"></a>
# **objectPUTTaxationItem**
> ProxyCreateOrModifyResponse objectPUTTaxationItem(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update TaxationItem
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TaxationItemsApi;
TaxationItemsApi apiInstance = new TaxationItemsApi();
String id = "id_example"; // String | Object id
ProxyModifyTaxationItem modifyRequest = new ProxyModifyTaxationItem(); // ProxyModifyTaxationItem |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTTaxationItem(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TaxationItemsApi#objectPUTTaxationItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyTaxationItem**](ProxyModifyTaxationItem.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTTaxationItem"></a>
# **pUTTaxationItem**
> GETTaxationItemType pUTTaxationItem(body, id, zuoraEntityIds)
Update taxation item
Updates a specific taxation item by ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.TaxationItemsApi;
TaxationItemsApi apiInstance = new TaxationItemsApi();
PUTTaxationItemType body = new PUTTaxationItemType(); // PUTTaxationItemType |
String id = "id_example"; // String | The unique ID of a taxation item.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETTaxationItemType result = apiInstance.pUTTaxationItem(body, id, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TaxationItemsApi#pUTTaxationItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**PUTTaxationItemType**](PUTTaxationItemType.md)| |
**id** | **String**| The unique ID of a taxation item. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETTaxationItemType**](GETTaxationItemType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# SubscribeRequestSubscriptionData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ratePlanData** | [**List<RatePlanData>**](RatePlanData.md) | |
**subscription** | [**SubscribeRequestSubscriptionDataSubscription**](SubscribeRequestSubscriptionDataSubscription.md) | |
<file_sep>
# CreditMemoItemBreakdown
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**applyToChargeNumber** | **String** | Available only when the credit memo item represents a discount invoice item. | [optional]
**breakdownDetails** | [**List<BreakdownDetail>**](BreakdownDetail.md) | | [optional]
**chargeNumber** | **String** | | [optional]
**creditMemoItemId** | **String** | | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | | [optional]
**isNegativePrice** | **Boolean** | Whether the amount of the product rate plan charge, which the credit memo is created from, is negative. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | | [optional]
**subscriptionNumber** | **String** | | [optional]
<file_sep>
# CreditMemoUnapplyDebitMemoRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The credit memo amount to be unapplied from the debit memo. |
**debitMemoId** | **String** | The unique ID of the debit memo that the credit memo is unapplied from. |
**items** | [**List<CreditMemoUnapplyDebitMemoItemRequestType>**](CreditMemoUnapplyDebitMemoItemRequestType.md) | Container for items. | [optional]
<file_sep>
# AmendResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amendmentIds** | **List<String>** | A list of the IDs of the associated amendments. There can be as many as three amendment IDs. Use a comma to separate each amendment ID. | [optional]
**chargeMetricsData** | [**ChargeMetricsData**](ChargeMetricsData.md) | | [optional]
**errors** | [**List<ActionsErrorResponse>**](ActionsErrorResponse.md) | | [optional]
**gatewayResponse** | **String** | | [optional]
**gatewayResponseCode** | **String** | | [optional]
**invoiceDatas** | [**List<InvoiceData>**](InvoiceData.md) | | [optional]
**invoiceId** | **String** | | [optional]
**paymentId** | **String** | | [optional]
**paymentTransactionNumber** | **String** | | [optional]
**subscriptionId** | **String** | | [optional]
**success** | **Boolean** | | [optional]
**totalDeltaMrr** | **Double** | | [optional]
**totalDeltaTcv** | **Double** | | [optional]
<file_sep>
# ProxyCreateRefundRefundInvoicePaymentData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**refundInvoicePayment** | [**List<RefundInvoicePayment>**](RefundInvoicePayment.md) | |
<file_sep>
# TriggerDate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | [**NameEnum**](#NameEnum) | Name of the trigger date of the order action. | [optional]
**triggerDate** | [**LocalDate**](LocalDate.md) | Trigger date in YYYY-MM-DD format. | [optional]
<a name="NameEnum"></a>
## Enum: NameEnum
Name | Value
---- | -----
CONTRACTEFFECTIVE | "ContractEffective"
SERVICEACTIVATION | "ServiceActivation"
CUSTOMERACCEPTANCE | "CustomerAcceptance"
<file_sep>
# PUTEventRIDetailType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**revenueItems** | [**List<EventRevenueItemType>**](EventRevenueItemType.md) | Revenue items are listed in ascending order by the accounting period start date. Include at least one custom field. |
<file_sep>
# GETAccountSummarySubscriptionRatePlanType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**productId** | **String** | Product ID. | [optional]
**productName** | **String** | Product name. | [optional]
**productRatePlanId** | **String** | Product Rate Plan ID. | [optional]
**productSku** | **String** | | [optional]
**ratePlanName** | **String** | Rate plan name. | [optional]
<file_sep>
# GETPaymentsType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nextPage** | **String** | URL to retrieve the next page of the response if it exists; otherwise absent. | [optional]
**payments** | [**List<GETPaymentType>**](GETPaymentType.md) | Information about one or more payments: | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
<file_sep># ProductRatePlanChargesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEProductRatePlanCharge**](ProductRatePlanChargesApi.md#objectDELETEProductRatePlanCharge) | **DELETE** /v1/object/product-rate-plan-charge/{id} | CRUD: Delete product rate plan charge
[**objectGETProductRatePlanCharge**](ProductRatePlanChargesApi.md#objectGETProductRatePlanCharge) | **GET** /v1/object/product-rate-plan-charge/{id} | CRUD: Get product rate plan charge
[**objectPOSTProductRatePlanCharge**](ProductRatePlanChargesApi.md#objectPOSTProductRatePlanCharge) | **POST** /v1/object/product-rate-plan-charge | CRUD: Create product rate plan charge
[**objectPUTProductRatePlanCharge**](ProductRatePlanChargesApi.md#objectPUTProductRatePlanCharge) | **PUT** /v1/object/product-rate-plan-charge/{id} | CRUD: Update product rate plan charge
<a name="objectDELETEProductRatePlanCharge"></a>
# **objectDELETEProductRatePlanCharge**
> ProxyDeleteResponse objectDELETEProductRatePlanCharge(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete product rate plan charge
Deletes a product rate plan charge.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlanChargesApi;
ProductRatePlanChargesApi apiInstance = new ProductRatePlanChargesApi();
String id = "id_example"; // String | The unique ID of the product rate plan charge to be deleted. For example, 2c93808457d787030157e031fcd34e19.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEProductRatePlanCharge(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlanChargesApi#objectDELETEProductRatePlanCharge");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The unique ID of the product rate plan charge to be deleted. For example, 2c93808457d787030157e031fcd34e19. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETProductRatePlanCharge"></a>
# **objectGETProductRatePlanCharge**
> ProxyGetProductRatePlanCharge objectGETProductRatePlanCharge(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Get product rate plan charge
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlanChargesApi;
ProductRatePlanChargesApi apiInstance = new ProductRatePlanChargesApi();
String id = "id_example"; // String | The unique ID of a product rate plan charge to be retrieved. For example, 2c93808457d787030157e031fcd34e19.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetProductRatePlanCharge result = apiInstance.objectGETProductRatePlanCharge(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlanChargesApi#objectGETProductRatePlanCharge");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The unique ID of a product rate plan charge to be retrieved. For example, 2c93808457d787030157e031fcd34e19. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetProductRatePlanCharge**](ProxyGetProductRatePlanCharge.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTProductRatePlanCharge"></a>
# **objectPOSTProductRatePlanCharge**
> ProxyCreateOrModifyResponse objectPOSTProductRatePlanCharge(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create product rate plan charge
Creates a product rate plan charge for a specified rate plan charge. Product rate plan charges can be of three types, one-time fees, recurring fees, and usage fees.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlanChargesApi;
ProductRatePlanChargesApi apiInstance = new ProductRatePlanChargesApi();
ProxyCreateProductRatePlanCharge createRequest = new ProxyCreateProductRatePlanCharge(); // ProxyCreateProductRatePlanCharge |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTProductRatePlanCharge(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlanChargesApi#objectPOSTProductRatePlanCharge");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateProductRatePlanCharge**](ProxyCreateProductRatePlanCharge.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTProductRatePlanCharge"></a>
# **objectPUTProductRatePlanCharge**
> ProxyCreateOrModifyResponse objectPUTProductRatePlanCharge(modifyRequest, id, zuoraEntityIds, zuoraTrackId)
CRUD: Update product rate plan charge
Updates the information about a product rate plan charge.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductRatePlanChargesApi;
ProductRatePlanChargesApi apiInstance = new ProductRatePlanChargesApi();
ProxyModifyProductRatePlanCharge modifyRequest = new ProxyModifyProductRatePlanCharge(); // ProxyModifyProductRatePlanCharge |
String id = "id_example"; // String | The unique ID of the product rate plan charge to be updated. For example, 2c93808457d787030157e031fcd34e19.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTProductRatePlanCharge(modifyRequest, id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductRatePlanChargesApi#objectPUTProductRatePlanCharge");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**modifyRequest** | [**ProxyModifyProductRatePlanCharge**](ProxyModifyProductRatePlanCharge.md)| |
**id** | **String**| The unique ID of the product rate plan charge to be updated. For example, 2c93808457d787030157e031fcd34e19. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># ActionsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**actionPOSTamend**](ActionsApi.md#actionPOSTamend) | **POST** /v1/action/amend | Amend
[**actionPOSTcreate**](ActionsApi.md#actionPOSTcreate) | **POST** /v1/action/create | Create
[**actionPOSTdelete**](ActionsApi.md#actionPOSTdelete) | **POST** /v1/action/delete | Delete
[**actionPOSTexecute**](ActionsApi.md#actionPOSTexecute) | **POST** /v1/action/execute | Execute
[**actionPOSTgenerate**](ActionsApi.md#actionPOSTgenerate) | **POST** /v1/action/generate | Generate
[**actionPOSTquery**](ActionsApi.md#actionPOSTquery) | **POST** /v1/action/query | Query
[**actionPOSTqueryMore**](ActionsApi.md#actionPOSTqueryMore) | **POST** /v1/action/queryMore | QueryMore
[**actionPOSTsubscribe**](ActionsApi.md#actionPOSTsubscribe) | **POST** /v1/action/subscribe | Subscribe
[**actionPOSTupdate**](ActionsApi.md#actionPOSTupdate) | **POST** /v1/action/update | Update
<a name="actionPOSTamend"></a>
# **actionPOSTamend**
> ProxyActionamendResponse actionPOSTamend(amendRequest, zuoraEntityIds, zuoraTrackId)
Amend
Modifies a subscription by creating Amendment objects. The availability of this operation depends on whether you have the Orders feature enabled: * If you have the Orders feature enabled, this operation is not available. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. * If you do not have the Orders feature enabled, this operation is available. However, Zuora recommends that you use [Update subscription](https://www.zuora.com/developer/api-reference/#operation/PUT_Subscription) instead of this operation. You can use this operation to create up to 10 Amendment objects. You must specify the following fields for each Amendment object: * `ContractEffectiveDate` * `Name` * `SubscriptionId` * `Type` Additionally, the value of `SubscriptionId` must be the same for each Amendment object. You cannot use this operation to update multiple subscriptions. **Note:** When you call this operation, Zuora modifies the subscription in the order that you specify Amendment objects in the request body. If Zuora is unable to create an Amendment object when you call this operation, the entire call fails.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActionamendRequest amendRequest = new ProxyActionamendRequest(); // ProxyActionamendRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyActionamendResponse result = apiInstance.actionPOSTamend(amendRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTamend");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**amendRequest** | [**ProxyActionamendRequest**](ProxyActionamendRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyActionamendResponse**](ProxyActionamendResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTcreate"></a>
# **actionPOSTcreate**
> List<SaveResult> actionPOSTcreate(createRequest, zuoraEntityIds, zuoraTrackId)
Create
Use the create call to create one or more objects of a specific type. You can specify different types in different create calls, but each create call must apply to only one type of object. ## Limits ### Objects per Call 50 objects are supported in a single call. ## How to Use this Call You can call create on an array of one or more zObjects. It returns an array of SaveResults, indicating the success or failure of creating each object. The following information applies to this call: * You cannot pass in null zObjects. * You can pass in a maximum of 50 zObjects at a time. * All objects must be of the same type. ### Using Create and Subscribe Calls Both the create and subscribe calls will create a new account. However, there are differences between the calls. Use the create call to create an account independent of a subscription. Use the subscribe call to create the account with the subscription and the initial payment information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActioncreateRequest createRequest = new ProxyActioncreateRequest(); // ProxyActioncreateRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
List<SaveResult> result = apiInstance.actionPOSTcreate(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTcreate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyActioncreateRequest**](ProxyActioncreateRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**List<SaveResult>**](SaveResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTdelete"></a>
# **actionPOSTdelete**
> List<DeleteResult> actionPOSTdelete(deleteRequest, zuoraEntityIds, zuoraTrackId)
Delete
Deletes one or more objects of the same type. You can specify different types in different delete calls, but each delete call must apply only to one type of object. The following information applies to this call: * You will need to first determine the IDs for the objects you wish to delete. * You cannot pass in any null IDs. * All objects in a specific delete call must be of the same type. ### Objects per Call 50 objects are supported in a single call.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActiondeleteRequest deleteRequest = new ProxyActiondeleteRequest(); // ProxyActiondeleteRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
List<DeleteResult> result = apiInstance.actionPOSTdelete(deleteRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTdelete");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**deleteRequest** | [**ProxyActiondeleteRequest**](ProxyActiondeleteRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**List<DeleteResult>**](DeleteResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTexecute"></a>
# **actionPOSTexecute**
> List<ExecuteResult> actionPOSTexecute(executeRequest, zuoraEntityIds, zuoraTrackId)
Execute
Use the execute call to execute a process to split an invoice into multiple invoices. The original invoice must be in draft status. The resulting invoices are called split invoices. **Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com). To split a draft invoice into multiple split invoices: 1. Use the create call to create a separate InvoiceSplitItem object for each split invoice that you want to create from the original draft invoice. 2. Use the create call to create a single InvoiceSplit object to collect all of the InvoiceSplitItem objects. 3. Use the execute call to split the draft invoice into multiple split invoices. You need to create InvoiceSplitItem objects and an InvoiceSplit object before you can use the execute call. * Supported objects: InvoiceSplit * Asynchronous process: yes
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActionexecuteRequest executeRequest = new ProxyActionexecuteRequest(); // ProxyActionexecuteRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
List<ExecuteResult> result = apiInstance.actionPOSTexecute(executeRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTexecute");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**executeRequest** | [**ProxyActionexecuteRequest**](ProxyActionexecuteRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**List<ExecuteResult>**](ExecuteResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTgenerate"></a>
# **actionPOSTgenerate**
> List<SaveResult> actionPOSTgenerate(generateRequest, zuoraEntityIds, zuoraTrackId)
Generate
Generates an on-demand invoice for a specific customer. This is similar to creating an ad-hoc bill run for a specific customer account in the Zuora UI. * Supported objects: Invoice * Asynchronous process: yes The ID of the generated invoice is returned in the response. If multiple invoices are generated, only the id of the first invoice generated is returned. This occurs when an account has multiple subscriptions with the [invoice subscription separately](https://knowledgecenter.zuora.com/BC_Subscription_Management/Subscriptions/B_Creating_Subscriptions/Invoicing_Subscriptions_Separately) option enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActiongenerateRequest generateRequest = new ProxyActiongenerateRequest(); // ProxyActiongenerateRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
List<SaveResult> result = apiInstance.actionPOSTgenerate(generateRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTgenerate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**generateRequest** | [**ProxyActiongenerateRequest**](ProxyActiongenerateRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**List<SaveResult>**](SaveResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTquery"></a>
# **actionPOSTquery**
> ProxyActionqueryResponse actionPOSTquery(queryRequest, zuoraEntityIds, zuoraTrackId)
Query
The query call sends a query expression by specifying the object to query, the fields to retrieve from that object, and any filters to determine whether a given object should be queried. You can use [Zuora Object Query Language](https://knowledgecenter.zuora.com/DC_Developers/K_Zuora_Object_Query_Language) (ZOQL) to construct those queries, passing them through the `queryString`. Once the call is made, the API executes the query against the specified object and returns a query response object to your application. Your application can then iterate through rows in the query response to retrieve information. ## Limitations This call has the following limitations: * All ZOQL keywords must be in lower case. * The number of records returned is limited to 2000 records
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActionqueryRequest queryRequest = new ProxyActionqueryRequest(); // ProxyActionqueryRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyActionqueryResponse result = apiInstance.actionPOSTquery(queryRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTquery");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**queryRequest** | [**ProxyActionqueryRequest**](ProxyActionqueryRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyActionqueryResponse**](ProxyActionqueryResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTqueryMore"></a>
# **actionPOSTqueryMore**
> ProxyActionqueryMoreResponse actionPOSTqueryMore(queryMoreRequest, zuoraEntityIds, zuoraTrackId)
QueryMore
Use queryMore to request additional results from a previous query call. If your initial query call returns more than 2000 results, you can use queryMore to query for the additional results. Any `queryLocator` results greater than 2,000, will only be stored by Zuora for 5 days before it is deleted. This call sends a request for additional results from an initial query call. If the initial query call returns more than 2000 results, you can use the `queryLocator` returned from query to request the next set of results. **Note:** Zuora expires queryMore cursors after 15 minutes of activity. To use queryMore, you first construct a query call. By default, the query call will return up to 2000 results. If there are more than 2000 results, query will return a boolean `done`, which will be marked as `false`, and a `queryLocator`, which is a marker you will pass to queryMore to get the next set of results.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActionqueryMoreRequest queryMoreRequest = new ProxyActionqueryMoreRequest(); // ProxyActionqueryMoreRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyActionqueryMoreResponse result = apiInstance.actionPOSTqueryMore(queryMoreRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTqueryMore");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**queryMoreRequest** | [**ProxyActionqueryMoreRequest**](ProxyActionqueryMoreRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyActionqueryMoreResponse**](ProxyActionqueryMoreResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTsubscribe"></a>
# **actionPOSTsubscribe**
> List<SubscribeResult> actionPOSTsubscribe(subscribeRequest, zuoraEntityIds, zuoraTrackId)
Subscribe
This call performs many actions. Use the subscribe call to bundle information required to create at least one new subscription. **Note:** This feature is unavailable if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. The call takes in an array of SubscribeRequests. Because it takes an array, you can submit a batch of subscription requests at once. You can create up to 50 different subscriptions in a single subscribe call. This is a combined call that you can use to perform all of the following tasks in a single call: * Create accounts * Create contacts * Create payment methods, including external payment options * Create an invoice for the subscription * Apply the first payment to a subscription ## Object Limits 50 objects are supported in a single call. ## Effective Date If the effective date is in the future, the invoices will not be generated, and there will be no invoice number. ## Subscription Name, Number, and ID ### Subscription Name and Number The subscription name is a unique identifier for the subscription. If you do not specify a value for the name, Zuora will create one automatically. The automatically generated value is known as the subscription number, such as `A-S00000080`. You cannot change the subscription name or number after creating the subscription. * **Subscription name**: The name that you set for the subscription. * **Subscription number**: The value generated by Zuora automatically if you do not specify a subscription name. Both the subscription name and number must be unique. If they are not, an error will occur. ### Subscription ID The subscription ID is a 32-digit ID in the format 4028xxxx. This is also the unique identifier for a subscription. This value is automatically generated by the system and cannot be edited or updated, but it can be queried. One subscription can have only one subscription name or number, but it can have multiple IDs: Each version of a subscription has a different ID. The Subscription object contains the fields `OriginalId` and `PreviousSubscriptionId`. `OriginalId` is the ID for the first version of a subscription. `PreviousSubscriptionId` is the ID of the version created immediately prior to the current version. ## Subscription Preview You can preview invoices that would be generated by the subscribe call. ## Invoice Subscriptions Separately If you have enabled the invoice subscriptions separately feature, a subscribe call will generate an invoice for each subscription for every subscription where the field `IsInvoiceSeparate` is set to `true`. If the invoice subscriptions separately feature is disabled, a subscribe call will generate a single invoice for all subscriptions. See [Invoicing Subscriptions Separately](https://knowledgecenter.zuora.com/BC_Subscription_Management/Subscriptions/B_Creating_Subscriptions/Invoicing_Subscriptions_Separately) for more information. ## Subscriptions and Draft Invoices If a draft invoice that includes charges exists in a customer account, using the subscribe call to create a new subscription and generate an invoice will cause the new subscription to be added to the existing draft invoice. Zuora will then post the invoice. ## When to Use Subscribe and Create Calls You can use either the subscribe call or the create call to create the objects associated with a subscription (accounts, contacts, and so on). There are differences between these calls, however, and some situations are better for one or the other. ### Use the Subscribe Call The subscribe call bundles up all the information you need for a subscription. Use the subscribe call to create new subscriptions when you have all the information you need. Subscribe calls cannot update BillTo, SoldTo, and Account objects. Payment information objects cannot be updated if there is an existing account ID in the call. These objects are not supported in a subscribe call. ### Use the Create Call The create call is more useful when you want to develop in stages. For example, if you want to first create an account, then a contact, and so on. If you do not have all information available, use the create call. To create a subscription, you must activate the account from Draft status to Active by calling the subscribe call.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActionsubscribeRequest subscribeRequest = new ProxyActionsubscribeRequest(); // ProxyActionsubscribeRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
List<SubscribeResult> result = apiInstance.actionPOSTsubscribe(subscribeRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTsubscribe");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscribeRequest** | [**ProxyActionsubscribeRequest**](ProxyActionsubscribeRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**List<SubscribeResult>**](SubscribeResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="actionPOSTupdate"></a>
# **actionPOSTupdate**
> List<SaveResult> actionPOSTupdate(updateRequest, zuoraEntityIds, zuoraTrackId)
Update
Updates the information in one or more objects of the same type. You can specify different types of objects in different update calls, but each specific update call must apply to only one type of object. You can update an array of one or more zObjects. It returns an array of SaveResults, indicating the success or failure of updating each object. The following information applies to this call: * You cannot pass in null zObjects. * You can pass in a maximum of 50 zObjects at a time. * All objects must be of the same type. * For each field in each object, you must determine that object's ID. Then populate the fields that you want update with the new information. * Zuora ignores unrecognized fields in update calls. For example, if an optional field is spelled incorrectly or a field that does not exist is specified, Zuora ignores the field and continues to process the call. No error message is returned for unrecognized fields. ## Object Limits 50 objects are supported in a single call.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ActionsApi;
ActionsApi apiInstance = new ActionsApi();
ProxyActionupdateRequest updateRequest = new ProxyActionupdateRequest(); // ProxyActionupdateRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
List<SaveResult> result = apiInstance.actionPOSTupdate(updateRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ActionsApi#actionPOSTupdate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**updateRequest** | [**ProxyActionupdateRequest**](ProxyActionupdateRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**List<SaveResult>**](SaveResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># ProductsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEProduct**](ProductsApi.md#objectDELETEProduct) | **DELETE** /v1/object/product/{id} | CRUD: Delete Product
[**objectGETProduct**](ProductsApi.md#objectGETProduct) | **GET** /v1/object/product/{id} | CRUD: Retrieve Product
[**objectPOSTProduct**](ProductsApi.md#objectPOSTProduct) | **POST** /v1/object/product | CRUD: Create Product
[**objectPUTProduct**](ProductsApi.md#objectPUTProduct) | **PUT** /v1/object/product/{id} | CRUD: Update Product
<a name="objectDELETEProduct"></a>
# **objectDELETEProduct**
> ProxyDeleteResponse objectDELETEProduct(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Product
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductsApi;
ProductsApi apiInstance = new ProductsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEProduct(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductsApi#objectDELETEProduct");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETProduct"></a>
# **objectGETProduct**
> ProxyGetProduct objectGETProduct(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Product
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductsApi;
ProductsApi apiInstance = new ProductsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetProduct result = apiInstance.objectGETProduct(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductsApi#objectGETProduct");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetProduct**](ProxyGetProduct.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTProduct"></a>
# **objectPOSTProduct**
> ProxyCreateOrModifyResponse objectPOSTProduct(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create Product
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductsApi;
ProductsApi apiInstance = new ProductsApi();
ProxyCreateProduct createRequest = new ProxyCreateProduct(); // ProxyCreateProduct |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTProduct(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductsApi#objectPOSTProduct");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateProduct**](ProxyCreateProduct.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTProduct"></a>
# **objectPUTProduct**
> ProxyCreateOrModifyResponse objectPUTProduct(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update Product
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ProductsApi;
ProductsApi apiInstance = new ProductsApi();
String id = "id_example"; // String | Object id
ProxyModifyProduct modifyRequest = new ProxyModifyProduct(); // ProxyModifyProduct |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTProduct(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ProductsApi#objectPUTProduct");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyProduct**](ProxyModifyProduct.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# SubscriptionObjectQTFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cpqBundleJsonIdQT** | **String** | The Bundle product structures from Zuora Quotes if you utilize Bundling in Salesforce. Do not change the value in this field. | [optional]
**opportunityCloseDateQT** | [**LocalDate**](LocalDate.md) | The closing date of the Opportunity. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**opportunityNameQT** | **String** | The unique identifier of the Opportunity. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteBusinessTypeQT** | **String** | The specific identifier for the type of business transaction the Quote represents such as New, Upsell, Downsell, Renewal or Churn. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteNumberQT** | **String** | The unique identifier of the Quote. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteTypeQT** | **String** | The Quote type that represents the subscription lifecycle stage such as New, Amendment, Renew or Cancel. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.CommonResponseType;
import de.keylight.zuora.client.model.GETPaymentMethodsType;
import de.keylight.zuora.client.model.POSTAuthorizeResponse;
import de.keylight.zuora.client.model.POSTDelayAuthorizeCapture;
import de.keylight.zuora.client.model.POSTPaymentMethodDecryption;
import de.keylight.zuora.client.model.POSTPaymentMethodRequest;
import de.keylight.zuora.client.model.POSTPaymentMethodResponse;
import de.keylight.zuora.client.model.POSTPaymentMethodResponseDecryption;
import de.keylight.zuora.client.model.POSTPaymentMethodResponseType;
import de.keylight.zuora.client.model.POSTPaymentMethodType;
import de.keylight.zuora.client.model.POSTVoidAuthorize;
import de.keylight.zuora.client.model.POSTVoidAuthorizeResponse;
import de.keylight.zuora.client.model.PUTPaymentMethodResponseType;
import de.keylight.zuora.client.model.PUTPaymentMethodType;
import de.keylight.zuora.client.model.PUTVerifyPaymentMethodResponseType;
import de.keylight.zuora.client.model.PUTVerifyPaymentMethodType;
import de.keylight.zuora.client.model.ProxyBadRequestResponse;
import de.keylight.zuora.client.model.ProxyCreateOrModifyResponse;
import de.keylight.zuora.client.model.ProxyCreatePaymentMethod;
import de.keylight.zuora.client.model.ProxyDeleteResponse;
import de.keylight.zuora.client.model.ProxyGetPaymentMethod;
import de.keylight.zuora.client.model.ProxyModifyPaymentMethod;
import de.keylight.zuora.client.model.ProxyNoDataResponse;
import de.keylight.zuora.client.model.ProxyUnauthorizedResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.PaymentMethodsApi")
public class PaymentMethodsApi {
private ApiClient apiClient;
public PaymentMethodsApi() {
this(new ApiClient());
}
@Autowired
public PaymentMethodsApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Delete payment method
* Deletes a credit card payment method from the specified customer account. If the specified payment method is the account's default payment method, the request will fail. In that case, you must first designate a different payment method for that customer to be the default.
* <p><b>200</b> -
* @param paymentMethodId Unique identifier of a payment method. (Since this ID is unique, and linked to a customer account in the system, no customer identifier is needed.)
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return CommonResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public CommonResponseType dELETEPaymentMethods(String paymentMethodId, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'paymentMethodId' is set
if (paymentMethodId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'paymentMethodId' when calling dELETEPaymentMethods");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("payment-method-id", paymentMethodId);
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/{payment-method-id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<CommonResponseType> returnType = new ParameterizedTypeReference<CommonResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Get credit card payment methods for account
* This REST API reference describes how to retrieve all credit card information for the specified customer account. ## Notes The response includes details credit or debit cards for the specified customer account. Card numbers are masked, e.g., \"************1234\". Cards are returned in reverse chronological order of last update. You can send requests for bank transfer payment methods types. The response will not include bank transfer details. The response only includes payment details on payment methods that are credit or debit cards.
* <p><b>200</b> -
* @param accountKey Account number or account ID.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param pageSize Number of rows returned per page.
* @return GETPaymentMethodsType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GETPaymentMethodsType gETPaymentMethodsCreditCard(String accountKey, String zuoraEntityIds, Integer pageSize) throws RestClientException {
Object postBody = null;
// verify the required parameter 'accountKey' is set
if (accountKey == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'accountKey' when calling gETPaymentMethodsCreditCard");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("account-key", accountKey);
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/credit-cards/accounts/{account-key}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "pageSize", pageSize));
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GETPaymentMethodsType> returnType = new ParameterizedTypeReference<GETPaymentMethodsType>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* CRUD: Delete payment method
*
* <p><b>200</b> -
* <p><b>401</b> -
* @param id Object id
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param zuoraTrackId A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
* @return ProxyDeleteResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ProxyDeleteResponse objectDELETEPaymentMethod(String id, String zuoraEntityIds, String zuoraTrackId) throws RestClientException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling objectDELETEPaymentMethod");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", id);
String path = UriComponentsBuilder.fromPath("/v1/object/payment-method/{id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
if (zuoraTrackId != null)
headerParams.add("Zuora-Track-Id", apiClient.parameterToString(zuoraTrackId));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<ProxyDeleteResponse> returnType = new ParameterizedTypeReference<ProxyDeleteResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* CRUD: Get payment method
*
* <p><b>200</b> -
* <p><b>401</b> -
* <p><b>404</b> -
* @param id Object id
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param zuoraTrackId A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
* @param fields Object fields to return
* @return ProxyGetPaymentMethod
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ProxyGetPaymentMethod objectGETPaymentMethod(String id, String zuoraEntityIds, String zuoraTrackId, String fields) throws RestClientException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling objectGETPaymentMethod");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", id);
String path = UriComponentsBuilder.fromPath("/v1/object/payment-method/{id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "fields", fields));
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
if (zuoraTrackId != null)
headerParams.add("Zuora-Track-Id", apiClient.parameterToString(zuoraTrackId));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<ProxyGetPaymentMethod> returnType = new ParameterizedTypeReference<ProxyGetPaymentMethod>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* CRUD: Create payment method
*
* <p><b>200</b> -
* <p><b>400</b> -
* <p><b>401</b> -
* @param createRequest
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param zuoraTrackId A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
* @return ProxyCreateOrModifyResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ProxyCreateOrModifyResponse objectPOSTPaymentMethod(ProxyCreatePaymentMethod createRequest, String zuoraEntityIds, String zuoraTrackId) throws RestClientException {
Object postBody = createRequest;
// verify the required parameter 'createRequest' is set
if (createRequest == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'createRequest' when calling objectPOSTPaymentMethod");
}
String path = UriComponentsBuilder.fromPath("/v1/object/payment-method").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
if (zuoraTrackId != null)
headerParams.add("Zuora-Track-Id", apiClient.parameterToString(zuoraTrackId));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<ProxyCreateOrModifyResponse> returnType = new ParameterizedTypeReference<ProxyCreateOrModifyResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* CRUD: Update payment method
*
* <p><b>200</b> -
* <p><b>401</b> -
* @param id Object id
* @param modifyRequest
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param zuoraTrackId A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
* @return ProxyCreateOrModifyResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ProxyCreateOrModifyResponse objectPUTPaymentMethod(String id, ProxyModifyPaymentMethod modifyRequest, String zuoraEntityIds, String zuoraTrackId) throws RestClientException {
Object postBody = modifyRequest;
// verify the required parameter 'id' is set
if (id == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling objectPUTPaymentMethod");
}
// verify the required parameter 'modifyRequest' is set
if (modifyRequest == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'modifyRequest' when calling objectPUTPaymentMethod");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", id);
String path = UriComponentsBuilder.fromPath("/v1/object/payment-method/{id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
if (zuoraTrackId != null)
headerParams.add("Zuora-Track-Id", apiClient.parameterToString(zuoraTrackId));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<ProxyCreateOrModifyResponse> returnType = new ParameterizedTypeReference<ProxyCreateOrModifyResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Cancel authorization
* **Note:** If you wish to enable this feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Allows you to cancel an authorization. The payment gateways that support this operation include Verifi, CyberSource 1.28, and CyberSource 1.97.
* <p><b>200</b> -
* @param paymentMethodId The unique ID of the payment method where the authorization is cancelled.
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return POSTVoidAuthorizeResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public POSTVoidAuthorizeResponse pOSTCancelAuthorization(String paymentMethodId, POSTVoidAuthorize request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'paymentMethodId' is set
if (paymentMethodId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'paymentMethodId' when calling pOSTCancelAuthorization");
}
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTCancelAuthorization");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("payment-method-id", paymentMethodId);
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/{payment-method-id}/voidAuthorize").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<POSTVoidAuthorizeResponse> returnType = new ParameterizedTypeReference<POSTVoidAuthorizeResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Create authorization
* **Note:** If you wish to enable this feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Enables you to authorize the availability of funds for a transaction but delay the capture of funds until a later time. The payment gateways that support this operation include Verifi, CyberSource 1.28, and CyberSource 1.97.
* <p><b>200</b> -
* @param paymentMethodId The unique ID of the payment method where the authorization is created.
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return POSTAuthorizeResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public POSTAuthorizeResponse pOSTCreateAuthorization(String paymentMethodId, POSTDelayAuthorizeCapture request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'paymentMethodId' is set
if (paymentMethodId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'paymentMethodId' when calling pOSTCreateAuthorization");
}
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTCreateAuthorization");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("payment-method-id", paymentMethodId);
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/{payment-method-id}/authorize").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<POSTAuthorizeResponse> returnType = new ParameterizedTypeReference<POSTAuthorizeResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Create payment method
* You can use this operation to create a payment method for a customer account. This operation supports the payment methods listed below. ### PayPal Express Checkout The following request body fields are specific to this payment method: * `BAID` (required) * `email` (required) ### PayPal Native Express Checkout The following request body fields are specific to this payment method: * `BAID` (required) * `email` (optional) ### PayPal Adaptive The following request body fields are specific to this payment method: * `preapprovalKey` (required) * `email` (required)
* <p><b>200</b> -
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return POSTPaymentMethodResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public POSTPaymentMethodResponse pOSTPaymentMethods(POSTPaymentMethodRequest request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTPaymentMethods");
}
String path = UriComponentsBuilder.fromPath("/v1/payment-methods").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<POSTPaymentMethodResponse> returnType = new ParameterizedTypeReference<POSTPaymentMethodResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Create credit card payment method
* This REST API reference describes how to create a new credit card payment method for a customer account. This API call is CORS Enabled. Use client-side JavaScript to invoke the call. **Note**: If you use this operation to create credit card payment methods instead of using the [iFrame of Hosted Payment Pages](https://knowledgecenter.zuora.com/CB_Billing/LA_Hosted_Payment_Pages/C_Hosted_Payment_Pages/B_Implementing_Hosted_Payment_Pages_on_Your_Website/C_Embed_and_Submit_the_iFrame), you are subject to PCI-compliance audit requirements.
* <p><b>200</b> -
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return POSTPaymentMethodResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public POSTPaymentMethodResponseType pOSTPaymentMethodsCreditCard(POSTPaymentMethodType request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTPaymentMethodsCreditCard");
}
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/credit-cards").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<POSTPaymentMethodResponseType> returnType = new ParameterizedTypeReference<POSTPaymentMethodResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Create Apple Pay payment method
* The decryption API endpoint can conditionally perform 3 tasks in one atomic call: * Decrypt Apple Pay Payment token * Create Credit Card Payment Method in Zuora with decrypted Apple Pay information * Process Payment on a specified Invoice (optional)
* <p><b>200</b> -
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return POSTPaymentMethodResponseDecryption
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public POSTPaymentMethodResponseDecryption pOSTPaymentMethodsDecryption(POSTPaymentMethodDecryption request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTPaymentMethodsDecryption");
}
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/decryption").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<POSTPaymentMethodResponseDecryption> returnType = new ParameterizedTypeReference<POSTPaymentMethodResponseDecryption>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Update credit card payment method
* Updates an existing credit card payment method for the specified customer account.
* <p><b>200</b> -
* @param paymentMethodId Unique ID of the payment method to update.
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return PUTPaymentMethodResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public PUTPaymentMethodResponseType pUTPaymentMethodsCreditCard(String paymentMethodId, PUTPaymentMethodType request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'paymentMethodId' is set
if (paymentMethodId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'paymentMethodId' when calling pUTPaymentMethodsCreditCard");
}
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pUTPaymentMethodsCreditCard");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("payment-method-id", paymentMethodId);
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/credit-cards/{payment-method-id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<PUTPaymentMethodResponseType> returnType = new ParameterizedTypeReference<PUTPaymentMethodResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Scrub payment method
* **Note:** If you wish to enable this feature, submit a request at [Zuora Global Support](http://support.zuora.com/). This operation enables you to replace all sensitive data in a payment method, related payment method snapshot table, and four related log tables with dummy values that will be stored in Zuora databases. This operation will scrub the sensitive data and soft-delete the specified payment method at the same time.
* <p><b>200</b> -
* @param paymentMethodId The ID of the payment method where you want to scrub the sensitive data.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return CommonResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public CommonResponseType pUTScrubPaymentMethods(String paymentMethodId, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'paymentMethodId' is set
if (paymentMethodId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'paymentMethodId' when calling pUTScrubPaymentMethods");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("payment-method-id", paymentMethodId);
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/{payment-method-id}/scrub").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<CommonResponseType> returnType = new ParameterizedTypeReference<CommonResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Verify payment method
* Sends an authorization request to the corresponding payment gateway to verify the payment method, even though no changes are made for the payment method. Supported payment methods are Credit Cards and Paypal. Zuora now supports performing a standalone zero dollar verification or one dollar authorization for credit cards. It also supports a billing agreement status check on PayPal payment methods. If a payment method is created by Hosted Payment Pages and is not assigned to any billing account, the payment method cannot be verified through this operation.
* <p><b>200</b> -
* @param paymentMethodId The ID of the payment method to be verified.
* @param body
* @return PUTVerifyPaymentMethodResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public PUTVerifyPaymentMethodResponseType pUTVerifyPaymentMethods(String paymentMethodId, PUTVerifyPaymentMethodType body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'paymentMethodId' is set
if (paymentMethodId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'paymentMethodId' when calling pUTVerifyPaymentMethods");
}
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling pUTVerifyPaymentMethods");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("payment-method-id", paymentMethodId);
String path = UriComponentsBuilder.fromPath("/v1/payment-methods/{payment-method-id}/verify").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<PUTVerifyPaymentMethodResponseType> returnType = new ParameterizedTypeReference<PUTVerifyPaymentMethodResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep>
# GETRsRevenueItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountingPeriodEndDate** | [**LocalDate**](LocalDate.md) | The accounting period end date. The accounting period end date of the open-ended accounting period is null. | [optional]
**accountingPeriodName** | **String** | The name of the accounting period. The open-ended accounting period is named `Open-Ended`. | [optional]
**accountingPeriodStartDate** | [**LocalDate**](LocalDate.md) | The accounting period start date. | [optional]
**amount** | **String** | The amount of the revenue item. | [optional]
**currency** | **String** | The type of currency used. | [optional]
**deferredRevenueAccountingCode** | **String** | The accounting code for deferred revenue, such as Monthly Recurring Liability. Required only when `overrideChargeAccountingCodes` is `true`. Otherwise, this value is ignored. | [optional]
**deferredRevenueAccountingCodeType** | **String** | The type of the deferred revenue accounting code, such as Deferred Revenue. Required only when `overrideChargeAccountingCodes` is `true`. Otherwise, this value is ignored. | [optional]
**isAccountingPeriodClosed** | **Boolean** | Indicates if the accounting period is closed or open. | [optional]
**recognizedRevenueAccountingCode** | **String** | The accounting code for recognized revenue, such as Monthly Recurring Charges or Overage Charges. Required only when `overrideChargeAccountingCodes` is `true`. Otherwise, the value is ignored. | [optional]
**recognizedRevenueAccountingCodeType** | **String** | The type of the recognized revenue accounting code, such as Sales Revenue or Sales Discount. Required only when `overrideChargeAccountingCodes` is `true`. Otherwise, this value is ignored. | [optional]
<file_sep>
# TimeSlicedMetrics
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | | [optional]
**generatedReason** | [**GeneratedReasonEnum**](#GeneratedReasonEnum) | Specify the reason why the metrics are generated by the certain order action. | [optional]
**invoiceOwner** | **String** | The acount number of the billing account that is billed for the subscription. | [optional]
**orderItemId** | **String** | The ID of the order item referenced by the order metrics. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | | [optional]
**subscriptionOwner** | **String** | The acount number of the billing account that owns the subscription. | [optional]
**termNumber** | [**BigDecimal**](BigDecimal.md) | | [optional]
<a name="GeneratedReasonEnum"></a>
## Enum: GeneratedReasonEnum
Name | Value
---- | -----
INCREASEQUANTITY | "IncreaseQuantity"
DECREASEQUANTITY | "DecreaseQuantity"
CHANGEPRICE | "ChangePrice"
EXTENSION | "Extension"
CONTRACTION | "Contraction"
<file_sep>
# PUTCreditMemoType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the credit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the credit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**autoApplyUponPosting** | **Boolean** | Whether the credit memo automatically applies to the invoice upon posting. | [optional]
**comment** | **String** | Comments about the credit memo. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the credit memo takes effect. | [optional]
**excludeFromAutoApplyRules** | **Boolean** | Whether the credit memo is excluded from the rule of automatically applying credit memos to invoices. | [optional]
**items** | [**List<PUTCreditMemoItemType>**](PUTCreditMemoItemType.md) | Container for credit memo items. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the credit memo is transferred to an external accounting system. Use this field for integration with accounting systems, such as NetSuite. | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
NO | "No"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# CreateSubscriptionNewSubscriptionOwnerAccount
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountNumber** | **String** | Account number. For example, A00000001. | [optional]
**autoPay** | **Boolean** | Specifies whether future payments are automatically billed when they are due. | [optional]
**batch** | **String** | Name of the billing batch that the account belongs to. For example, Batch1. | [optional]
**billCycleDay** | **Integer** | Day of the month that the account prefers billing periods to begin on. If set to 0, the bill cycle day will be set as \"AutoSet\". |
**billToContact** | [**BillToContact**](BillToContact.md) | |
**communicationProfileId** | **String** | Internal identifier of the communication profile that Zuora uses when sending notifications to the account's contacts. | [optional]
**creditCard** | [**CreditCard**](CreditCard.md) | | [optional]
**crmId** | **String** | External identifier of the account in a CRM system. | [optional]
**currency** | **String** | ISO 3-letter currency code (uppercase). For example, USD. |
**customFields** | [**AccountObjectCustomFields**](AccountObjectCustomFields.md) | | [optional]
**hpmCreditCardPaymentMethodId** | **String** | Internal identifier of the hosted payment method (HPM) credit card payment method associated with the account. | [optional]
**invoiceDeliveryPrefsEmail** | **Boolean** | Specifies whether to turn on the invoice delivery method 'Email' for the new account. Values are: * `true` (default). Turn on the invoice delivery method 'Email' for the new account. * `false`. Turn off the invoice delivery method 'Email' for the new account. | [optional]
**invoiceDeliveryPrefsPrint** | **Boolean** | Specifies whether to turn on the invoice delivery method 'Print' for the new account. Values are: * `true`. Turn on the invoice delivery method 'Print' for the new account. * `false` (default). Turn off the invoice delivery method 'Print' for the new account. | [optional]
**invoiceTemplateId** | **String** | Internal identifier of the invoice template that Zuora uses when generating invoices for the account. | [optional]
**name** | **String** | Account name. |
**notes** | **String** | Notes about the account. These notes are only visible to Zuora users. | [optional]
**parentId** | **String** | Identifier of the parent customer account for this Account object. Use this field if you have customer hierarchy enabled. | [optional]
**paymentGateway** | **String** | The payment gateway that Zuora uses when processing electronic payments and refunds for the account. If you do not specify this field or if the value of this field is null, Zuora uses your default payment gateway. | [optional]
**paymentTerm** | **String** | Name of the payment term associated with the account. For example, \"Net 30\". The payment term determines the due dates of invoices. | [optional]
**soldToContact** | [**SoldToContact**](SoldToContact.md) | | [optional]
**taxInfo** | [**TaxInfo**](TaxInfo.md) | | [optional]
<file_sep># RevenueEventsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETRevenueEventDetails**](RevenueEventsApi.md#gETRevenueEventDetails) | **GET** /v1/revenue-events/{event-number} | Get revenue event details
[**gETRevenueEventForRevenueSchedule**](RevenueEventsApi.md#gETRevenueEventForRevenueSchedule) | **GET** /v1/revenue-events/revenue-schedules/{rs-number} | Get revenue events for a revenue schedule
<a name="gETRevenueEventDetails"></a>
# **gETRevenueEventDetails**
> GETRevenueEventDetailType gETRevenueEventDetails(eventNumber, zuoraEntityIds)
Get revenue event details
This REST API reference describes how to get revenue event details by specifying the revenue event number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueEventsApi;
RevenueEventsApi apiInstance = new RevenueEventsApi();
String eventNumber = "eventNumber_example"; // String | The number associated with the revenue event.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRevenueEventDetailType result = apiInstance.gETRevenueEventDetails(eventNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueEventsApi#gETRevenueEventDetails");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**eventNumber** | **String**| The number associated with the revenue event. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRevenueEventDetailType**](GETRevenueEventDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRevenueEventForRevenueSchedule"></a>
# **gETRevenueEventForRevenueSchedule**
> GETRevenueEventDetailsType gETRevenueEventForRevenueSchedule(rsNumber, zuoraEntityIds, pageSize)
Get revenue events for a revenue schedule
This REST API reference describes how to get all revenue events in a revenue schedule by specifying the revenue schedule number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueEventsApi;
RevenueEventsApi apiInstance = new RevenueEventsApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 8; // Integer | Number of rows returned per page.
try {
GETRevenueEventDetailsType result = apiInstance.gETRevenueEventForRevenueSchedule(rsNumber, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueEventsApi#gETRevenueEventForRevenueSchedule");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 8]
### Return type
[**GETRevenueEventDetailsType**](GETRevenueEventDetailsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# InvoiceItemAdjustmentObjectNSFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoiceItemAdjustmentIntegrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**invoiceItemAdjustmentIntegrationStatusNS** | **String** | Status of the invoice item adjustment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**invoiceItemAdjustmentSyncDateNS** | **String** | Date when the invoice item adjustment was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
<file_sep>
# OrderSubscriptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**baseVersion** | **Integer** | The base version of the subscription. | [optional]
**customFields** | [**SubscriptionObjectCustomFields**](SubscriptionObjectCustomFields.md) | | [optional]
**newVersion** | **Integer** | The latest version of the subscription. | [optional]
**orderActions** | [**List<OrderAction>**](OrderAction.md) | | [optional]
**sequence** | **Integer** | The sequence number of a certain subscription processed by the order. | [optional]
**subscriptionNumber** | **String** | The new subscription number for a new subscription created, or the existing subscription number. Unlike the order request, the subscription number here always has a value. | [optional]
<file_sep>
# BillingOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**documentDate** | [**LocalDate**](LocalDate.md) | | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | | [optional]
<file_sep>
# ProductRatePlanChargeObjectNSFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**classNS** | **String** | Class associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**deferredRevAccountNS** | **String** | Deferrred revenue account associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Department associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**includeChildrenNS** | [**IncludeChildrenNSEnum**](#IncludeChildrenNSEnum) | Specifies whether the corresponding item in NetSuite is visible under child subsidiaries. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the product rate plan charge's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**itemTypeNS** | [**ItemTypeNSEnum**](#ItemTypeNSEnum) | Type of item that is created in NetSuite for the product rate plan charge. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Location associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**recognizedRevAccountNS** | **String** | Recognized revenue account associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**revRecEndNS** | [**RevRecEndNSEnum**](#RevRecEndNSEnum) | End date condition of the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**revRecStartNS** | [**RevRecStartNSEnum**](#RevRecStartNSEnum) | Start date condition of the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**revRecTemplateTypeNS** | **String** | Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Subsidiary associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the product rate plan charge was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
<a name="IncludeChildrenNSEnum"></a>
## Enum: IncludeChildrenNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<a name="ItemTypeNSEnum"></a>
## Enum: ItemTypeNSEnum
Name | Value
---- | -----
INVENTORY | "Inventory"
NON_INVENTORY | "Non Inventory"
SERVICE | "Service"
<a name="RevRecEndNSEnum"></a>
## Enum: RevRecEndNSEnum
Name | Value
---- | -----
CHARGE_PERIOD_START | "Charge Period Start"
REV_REC_TRIGGER_DATE | "Rev Rec Trigger Date"
USE_NETSUITE_REV_REC_TEMPLATE | "Use NetSuite Rev Rec Template"
<a name="RevRecStartNSEnum"></a>
## Enum: RevRecStartNSEnum
Name | Value
---- | -----
CHARGE_PERIOD_START | "Charge Period Start"
REV_REC_TRIGGER_DATE | "Rev Rec Trigger Date"
USE_NETSUITE_REV_REC_TEMPLATE | "Use NetSuite Rev Rec Template"
<file_sep># InvoiceAdjustmentsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEInvoiceAdjustment**](InvoiceAdjustmentsApi.md#objectDELETEInvoiceAdjustment) | **DELETE** /v1/object/invoice-adjustment/{id} | CRUD: Delete InvoiceAdjustment
[**objectGETInvoiceAdjustment**](InvoiceAdjustmentsApi.md#objectGETInvoiceAdjustment) | **GET** /v1/object/invoice-adjustment/{id} | CRUD: Retrieve InvoiceAdjustment
[**objectPOSTInvoiceAdjustment**](InvoiceAdjustmentsApi.md#objectPOSTInvoiceAdjustment) | **POST** /v1/object/invoice-adjustment | CRUD: Create InvoiceAdjustment
[**objectPUTInvoiceAdjustment**](InvoiceAdjustmentsApi.md#objectPUTInvoiceAdjustment) | **PUT** /v1/object/invoice-adjustment/{id} | CRUD: Update InvoiceAdjustment
<a name="objectDELETEInvoiceAdjustment"></a>
# **objectDELETEInvoiceAdjustment**
> ProxyDeleteResponse objectDELETEInvoiceAdjustment(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete InvoiceAdjustment
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoiceAdjustmentsApi;
InvoiceAdjustmentsApi apiInstance = new InvoiceAdjustmentsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEInvoiceAdjustment(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoiceAdjustmentsApi#objectDELETEInvoiceAdjustment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETInvoiceAdjustment"></a>
# **objectGETInvoiceAdjustment**
> ProxyGetInvoiceAdjustment objectGETInvoiceAdjustment(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve InvoiceAdjustment
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoiceAdjustmentsApi;
InvoiceAdjustmentsApi apiInstance = new InvoiceAdjustmentsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetInvoiceAdjustment result = apiInstance.objectGETInvoiceAdjustment(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoiceAdjustmentsApi#objectGETInvoiceAdjustment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetInvoiceAdjustment**](ProxyGetInvoiceAdjustment.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTInvoiceAdjustment"></a>
# **objectPOSTInvoiceAdjustment**
> ProxyCreateOrModifyResponse objectPOSTInvoiceAdjustment(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create InvoiceAdjustment
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoiceAdjustmentsApi;
InvoiceAdjustmentsApi apiInstance = new InvoiceAdjustmentsApi();
ProxyCreateInvoiceAdjustment createRequest = new ProxyCreateInvoiceAdjustment(); // ProxyCreateInvoiceAdjustment |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTInvoiceAdjustment(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoiceAdjustmentsApi#objectPOSTInvoiceAdjustment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateInvoiceAdjustment**](ProxyCreateInvoiceAdjustment.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTInvoiceAdjustment"></a>
# **objectPUTInvoiceAdjustment**
> ProxyCreateOrModifyResponse objectPUTInvoiceAdjustment(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update InvoiceAdjustment
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.InvoiceAdjustmentsApi;
InvoiceAdjustmentsApi apiInstance = new InvoiceAdjustmentsApi();
String id = "id_example"; // String | Object id
ProxyModifyInvoiceAdjustment modifyRequest = new ProxyModifyInvoiceAdjustment(); // ProxyModifyInvoiceAdjustment |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTInvoiceAdjustment(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling InvoiceAdjustmentsApi#objectPUTInvoiceAdjustment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyInvoiceAdjustment**](ProxyModifyInvoiceAdjustment.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# Order
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**createdBy** | **String** | The ID of the user who created this order. | [optional]
**createdDate** | **String** | The time that the order gets created in the system, in the `YYYY-MM-DD HH:MM:SS` format. | [optional]
**currency** | **String** | Currency code. | [optional]
**customFields** | [**OrderObjectCustomFields**](OrderObjectCustomFields.md) | | [optional]
**existingAccountNumber** | **String** | The account number that this order has been created under. This is also the invoice owner of the subscriptions included in this order. | [optional]
**orderDate** | [**LocalDate**](LocalDate.md) | The date when the order is signed. All the order actions under this order will use this order date as the contract effective date if no additinal contractEffectiveDate is provided. | [optional]
**orderNumber** | **String** | The order number of the order. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the order. If the order contains any `Pending Activation` or `Pending Acceptance` subscription, the order status will be `Pending`; otherwise the order status is `Completed`. | [optional]
**subscriptions** | [**List<OrderSubscriptions>**](OrderSubscriptions.md) | Represents a processed subscription, including the origin request (order actions) that create this version of subscription and the processing result (order metrics). The reference part in the request will be overridden with the info in the new subscription version. | [optional]
**updatedBy** | **String** | The ID of the user who updated this order. | [optional]
**updatedDate** | **String** | The time that the order gets updated in the system(for example, an order description update), in the `YYYY-MM-DD HH:MM:SS` format. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
COMPLETED | "Completed"
PENDING | "Pending"
<file_sep>
# ChargeOverridePricing
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**discount** | [**DiscountPricingOverride**](DiscountPricingOverride.md) | | [optional]
**oneTimeFlatFee** | [**OneTimeFlatFeePricingOverride**](OneTimeFlatFeePricingOverride.md) | | [optional]
**oneTimePerUnit** | [**OneTimePerUnitPricingOverride**](OneTimePerUnitPricingOverride.md) | | [optional]
**oneTimeTiered** | [**OneTimeTieredPricingOverride**](OneTimeTieredPricingOverride.md) | | [optional]
**oneTimeVolume** | [**OneTimeVolumePricingOverride**](OneTimeVolumePricingOverride.md) | | [optional]
**recurringFlatFee** | [**RecurringFlatFeePricingOverride**](RecurringFlatFeePricingOverride.md) | | [optional]
**recurringPerUnit** | [**RecurringPerUnitPricingOverride**](RecurringPerUnitPricingOverride.md) | | [optional]
**recurringTiered** | [**RecurringTieredPricingOverride**](RecurringTieredPricingOverride.md) | | [optional]
**recurringVolume** | [**RecurringVolumePricingOverride**](RecurringVolumePricingOverride.md) | | [optional]
**usageFlatFee** | [**UsageFlatFeePricingOverride**](UsageFlatFeePricingOverride.md) | | [optional]
**usageOverage** | [**UsageOveragePricingOverride**](UsageOveragePricingOverride.md) | | [optional]
**usagePerUnit** | [**UsagePerUnitPricingOverride**](UsagePerUnitPricingOverride.md) | | [optional]
**usageTiered** | [**UsageTieredPricingOverride**](UsageTieredPricingOverride.md) | | [optional]
**usageTieredWithOverage** | [**UsageTieredWithOveragePricingOverride**](UsageTieredWithOveragePricingOverride.md) | | [optional]
**usageVolume** | [**UsageVolumePricingOverride**](UsageVolumePricingOverride.md) | | [optional]
<file_sep># PaymentsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEPayment**](PaymentsApi.md#dELETEPayment) | **DELETE** /v1/payments/{paymentId} | Delete payment
[**gETPayment**](PaymentsApi.md#gETPayment) | **GET** /v1/payments/{paymentId} | Get payment
[**gETPaymentItemPart**](PaymentsApi.md#gETPaymentItemPart) | **GET** /v1/payments/{paymentId}/parts/{partid}/itemparts/{itempartid} | Get payment part item
[**gETPaymentItemParts**](PaymentsApi.md#gETPaymentItemParts) | **GET** /v1/payments/{paymentId}/parts/{partid}/itemparts | Get payment part items
[**gETPaymentPart**](PaymentsApi.md#gETPaymentPart) | **GET** /v1/payments/{paymentId}/parts/{partid} | Get payment part
[**gETPaymentParts**](PaymentsApi.md#gETPaymentParts) | **GET** /v1/payments/{paymentId}/parts | Get payment parts
[**gETRetrieveAllPayments**](PaymentsApi.md#gETRetrieveAllPayments) | **GET** /v1/payments | Get all payments
[**objectDELETEPayment**](PaymentsApi.md#objectDELETEPayment) | **DELETE** /v1/object/payment/{id} | CRUD: Delete payment
[**objectGETPayment**](PaymentsApi.md#objectGETPayment) | **GET** /v1/object/payment/{id} | CRUD: Get payment
[**objectPOSTPayment**](PaymentsApi.md#objectPOSTPayment) | **POST** /v1/object/payment | CRUD: Create payment
[**objectPUTPayment**](PaymentsApi.md#objectPUTPayment) | **PUT** /v1/object/payment/{id} | CRUD: Update payment
[**pOSTCreatePayment**](PaymentsApi.md#pOSTCreatePayment) | **POST** /v1/payments | Create payment
[**pOSTRefundPayment**](PaymentsApi.md#pOSTRefundPayment) | **POST** /v1/payments/{paymentId}/refunds | Refund payment
[**pUTApplyPayment**](PaymentsApi.md#pUTApplyPayment) | **PUT** /v1/payments/{paymentId}/apply | Apply payment
[**pUTCancelPayment**](PaymentsApi.md#pUTCancelPayment) | **PUT** /v1/payments/{paymentId}/cancel | Cancel payment
[**pUTTransferPayment**](PaymentsApi.md#pUTTransferPayment) | **PUT** /v1/payments/{paymentId}/transfer | Transfer payment
[**pUTUnapplyPayment**](PaymentsApi.md#pUTUnapplyPayment) | **PUT** /v1/payments/{paymentId}/unapply | Unapply payment
[**pUTUpdatePayment**](PaymentsApi.md#pUTUpdatePayment) | **PUT** /v1/payments/{paymentId} | Update payment
<a name="dELETEPayment"></a>
# **dELETEPayment**
> CommonResponseType dELETEPayment(paymentId, zuoraEntityIds)
Delete payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Deletes a payment. Only payments with the Cancelled status can be deleted.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String paymentId = "paymentId_example"; // String | The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEPayment(paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#dELETEPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentId** | **String**| The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETPayment"></a>
# **gETPayment**
> GETARPaymentType gETPayment(paymentId, zuoraEntityIds)
Get payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about one specific payment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String paymentId = "paymentId_example"; // String | The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETARPaymentType result = apiInstance.gETPayment(paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#gETPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentId** | **String**| The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETARPaymentType**](GETARPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETPaymentItemPart"></a>
# **gETPaymentItemPart**
> GETPaymentItemPartType gETPaymentItemPart(partid, itempartid, paymentId, zuoraEntityIds)
Get payment part item
**Note:** The Invoice Item Settlement feature is in **Limited Availability**, and it must be used together with other Invoice Settlement features (Unapplied Payments, and Credit and Debit memos). If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about a specific payment part item. A payment part item is a single line item in a payment part. A payment part can consist of several different types of items.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String partid = "partid_example"; // String | The unique ID of a specific payment part. You can get the payment part ID from the response of [Get payment parts](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentParts).
String itempartid = "itempartid_example"; // String | The unique ID of a specific payment part item. You can get the payment part item ID from the response of [Get payment part items](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentItemParts).
String paymentId = "paymentId_example"; // String | The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPaymentItemPartType result = apiInstance.gETPaymentItemPart(partid, itempartid, paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#gETPaymentItemPart");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**partid** | **String**| The unique ID of a specific payment part. You can get the payment part ID from the response of [Get payment parts](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentParts). |
**itempartid** | **String**| The unique ID of a specific payment part item. You can get the payment part item ID from the response of [Get payment part items](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentItemParts). |
**paymentId** | **String**| The unique ID of a payment. For example, 8<PASSWORD>. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPaymentItemPartType**](GETPaymentItemPartType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETPaymentItemParts"></a>
# **gETPaymentItemParts**
> GETPaymentItemPartCollectionType gETPaymentItemParts(partid, paymentId, zuoraEntityIds, pageSize)
Get payment part items
**Note:** The Invoice Item Settlement feature is in **Limited Availability**, and it must be used together with other Invoice Settlement features (Unapplied Payments, and Credit and Debit memos). If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all items of a payment part. A payment part item is a single line item in a payment part. A payment part can consist of several different types of items.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String partid = "partid_example"; // String | The unique ID of a specific payment part. You can get the payment part ID from the response of [Get payment parts](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentParts).
String paymentId = "paymentId_example"; // String | The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETPaymentItemPartCollectionType result = apiInstance.gETPaymentItemParts(partid, paymentId, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#gETPaymentItemParts");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**partid** | **String**| The unique ID of a specific payment part. You can get the payment part ID from the response of [Get payment parts](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentParts). |
**paymentId** | **String**| The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETPaymentItemPartCollectionType**](GETPaymentItemPartCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETPaymentPart"></a>
# **gETPaymentPart**
> GETPaymentPartType gETPaymentPart(partid, paymentId, zuoraEntityIds)
Get payment part
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about a specific payment part. A payment can consist of an unapplied part, and several parts applied to invoices and debit memos.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String partid = "partid_example"; // String | The unique ID of a specific payment part. You can get the payment part ID from the response of [Get payment parts](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentParts).
String paymentId = "paymentId_example"; // String | The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPaymentPartType result = apiInstance.gETPaymentPart(partid, paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#gETPaymentPart");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**partid** | **String**| The unique ID of a specific payment part. You can get the payment part ID from the response of [Get payment parts](https://www.zuora.com/developer/api-reference/#operation/GET_PaymentParts). |
**paymentId** | **String**| The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPaymentPartType**](GETPaymentPartType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETPaymentParts"></a>
# **gETPaymentParts**
> GETPaymentPartsCollectionType gETPaymentParts(paymentId, zuoraEntityIds, pageSize)
Get payment parts
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all parts of a payment. A payment can consist of an unapplied part, and several parts applied to invoices and debit memos. You can use this operation to get all the applied and unapplied portions of a payment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String paymentId = "paymentId_example"; // String | The unique ID of a payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETPaymentPartsCollectionType result = apiInstance.gETPaymentParts(paymentId, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#gETPaymentParts");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentId** | **String**| The unique ID of a payment. For example, <KEY>. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETPaymentPartsCollectionType**](GETPaymentPartsCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRetrieveAllPayments"></a>
# **gETRetrieveAllPayments**
> PaymentCollectionResponseType gETRetrieveAllPayments(zuoraEntityIds, pageSize, accountId, amount, appliedAmount, createdById, createdDate, creditBalanceAmount, currency, effectiveDate, number, refundAmount, status, type, unappliedAmount, updatedById, updatedDate, sort)
Get all payments
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the information about all payments from all your customer accounts. ### Filtering You can use query parameters to restrict the data returned in the response. Each query parameter corresponds to one field in the response body. If the value of a filterable field is string, you can set the corresponding query parameter to `null` when filtering. Then, you can get the response data with this field value being `null`. Examples: - /v1/payments?status=Processed - /v1/payments?currency=USD&status=Processed - /v1/payments?status=Processed&type=External&sort=+number
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String accountId = "accountId_example"; // String | This parameter filters the response based on the `accountId` field.
Double amount = 3.4D; // Double | This parameter filters the response based on the `amount` field.
Double appliedAmount = 3.4D; // Double | This parameter filters the response based on the `appliedAmount` field.
String createdById = "createdById_example"; // String | This parameter filters the response based on the `createdById` field.
OffsetDateTime createdDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `createdDate` field.
Double creditBalanceAmount = 3.4D; // Double | This parameter filters the response based on the `creditBalanceAmount` field.
String currency = "currency_example"; // String | This parameter filters the response based on the `currency` field.
OffsetDateTime effectiveDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `effectiveDate` field.
String number = "number_example"; // String | This parameter filters the response based on the `number` field.
Double refundAmount = 3.4D; // Double | This parameter filters the response based on the `refundAmount` field.
String status = "status_example"; // String | This parameter filters the response based on the `status` field.
String type = "type_example"; // String | This parameter filters the response based on the `type` field.
Double unappliedAmount = 3.4D; // Double | This parameter filters the response based on the `unappliedAmount` field.
String updatedById = "updatedById_example"; // String | This parameter filters the response based on the `updatedById` field.
OffsetDateTime updatedDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `updatedDate` field.
String sort = "sort_example"; // String | This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by payment number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - number - accountId - amount - appliedAmount - unappliedAmount - refundAmount - creditBalanceAmount - effectiveDate - createdDate - createdById - updatedDate - updatedById Examples: - /v1/payments?sort=+number - /v1/payments?status=Processed&sort=-number,+amount
try {
PaymentCollectionResponseType result = apiInstance.gETRetrieveAllPayments(zuoraEntityIds, pageSize, accountId, amount, appliedAmount, createdById, createdDate, creditBalanceAmount, currency, effectiveDate, number, refundAmount, status, type, unappliedAmount, updatedById, updatedDate, sort);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#gETRetrieveAllPayments");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**accountId** | **String**| This parameter filters the response based on the `accountId` field. | [optional]
**amount** | **Double**| This parameter filters the response based on the `amount` field. | [optional]
**appliedAmount** | **Double**| This parameter filters the response based on the `appliedAmount` field. | [optional]
**createdById** | **String**| This parameter filters the response based on the `createdById` field. | [optional]
**createdDate** | **OffsetDateTime**| This parameter filters the response based on the `createdDate` field. | [optional]
**creditBalanceAmount** | **Double**| This parameter filters the response based on the `creditBalanceAmount` field. | [optional]
**currency** | **String**| This parameter filters the response based on the `currency` field. | [optional]
**effectiveDate** | **OffsetDateTime**| This parameter filters the response based on the `effectiveDate` field. | [optional]
**number** | **String**| This parameter filters the response based on the `number` field. | [optional]
**refundAmount** | **Double**| This parameter filters the response based on the `refundAmount` field. | [optional]
**status** | **String**| This parameter filters the response based on the `status` field. | [optional] [enum: Draft, Processing, Processed, Error, Canceled, Posted]
**type** | **String**| This parameter filters the response based on the `type` field. | [optional] [enum: External, Electronic]
**unappliedAmount** | **Double**| This parameter filters the response based on the `unappliedAmount` field. | [optional]
**updatedById** | **String**| This parameter filters the response based on the `updatedById` field. | [optional]
**updatedDate** | **OffsetDateTime**| This parameter filters the response based on the `updatedDate` field. | [optional]
**sort** | **String**| This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by payment number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - number - accountId - amount - appliedAmount - unappliedAmount - refundAmount - creditBalanceAmount - effectiveDate - createdDate - createdById - updatedDate - updatedById Examples: - /v1/payments?sort=+number - /v1/payments?status=Processed&sort=-number,+amount | [optional]
### Return type
[**PaymentCollectionResponseType**](PaymentCollectionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETEPayment"></a>
# **objectDELETEPayment**
> ProxyDeleteResponse objectDELETEPayment(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete payment
Deletes a payment. Only payments with the Cancelled status can be deleted.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String id = "id_example"; // String | The unique ID of the payment to be deleted. For example, 2c92c0f85d4e95ae015d4f7e5d690622.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEPayment(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#objectDELETEPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The unique ID of the payment to be deleted. For example, 2c92c0f85d4e95ae015d4f7e5d690622. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETPayment"></a>
# **objectGETPayment**
> ProxyGetPayment objectGETPayment(id, zuoraEntityIds, zuoraTrackId)
CRUD: Get payment
Retrives the information about one specific payment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String id = "id_example"; // String | The unique ID of a payment. For example, 2c92c095592623ea01596621ada84352.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyGetPayment result = apiInstance.objectGETPayment(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#objectGETPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The unique ID of a payment. For example, 2c92c095592623ea01596621ada84352. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyGetPayment**](ProxyGetPayment.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTPayment"></a>
# **objectPOSTPayment**
> ProxyCreateOrModifyResponse objectPOSTPayment(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create payment
Creates a payment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
ProxyCreatePayment createRequest = new ProxyCreatePayment(); // ProxyCreatePayment |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTPayment(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#objectPOSTPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreatePayment**](ProxyCreatePayment.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTPayment"></a>
# **objectPUTPayment**
> ProxyCreateOrModifyResponse objectPUTPayment(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update payment
Updates a payment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String id = "id_example"; // String | The unique ID of a payment. For example, 2c92c095592623ea01596621ada84352.
ProxyModifyPayment modifyRequest = new ProxyModifyPayment(); // ProxyModifyPayment |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTPayment(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#objectPUTPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| The unique ID of a payment. For example, 2c92c095592623ea01596621ada84352. |
**modifyRequest** | [**ProxyModifyPayment**](ProxyModifyPayment.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTCreatePayment"></a>
# **pOSTCreatePayment**
> GETARPaymentType pOSTCreatePayment(body, zuoraEntityIds)
Create payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates a payment for the following scenarios: - A full payment on an invoice or debit memo - A partial payment - A payment for several invoices and debit memos - An unapplied payment If you do not know to which customer account the payment belongs, you can create a payment without specifying a customer account. When creating a payment, the total number of invoices and debit memos that the payment will apply to should be less than or equal to 1,000. If the Proration application rule is used, when creating a payment, the following quantity must be less than or equal to 10,000: (number of invoice items + number of debit memo items) * number of payment items Otherwise, the First In First Out rule will be used instead of the Proration rule. For more information, see [Create Payments](https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/A_Unapplied_Payments/Management_of_Unapplied_Payments/AA_Create_Payments) and [Create Payments Without Specifying Customer Accounts](https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/A_Unapplied_Payments/Management_of_Unapplied_Payments/AA_Create_Payments_Without_Specifying_Customer_Accounts).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
CreatePaymentType body = new CreatePaymentType(); // CreatePaymentType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETARPaymentType result = apiInstance.pOSTCreatePayment(body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#pOSTCreatePayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**CreatePaymentType**](CreatePaymentType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETARPaymentType**](GETARPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRefundPayment"></a>
# **pOSTRefundPayment**
> GETRefundPaymentType pOSTRefundPayment(body, paymentId, zuoraEntityIds)
Refund payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Refunds a full or partial unapplied payment to your customers. To refund applied payments, you must unapply the applied payments from the invoices or debit memos, and then refund the unapplied payments to customers. For more information, see [Refund Payments](https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/A_Unapplied_Payments/Management_of_Unapplied_Payments/Z_Refund_Payments).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
PostRefundType body = new PostRefundType(); // PostRefundType |
String paymentId = "paymentId_example"; // String | The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRefundPaymentType result = apiInstance.pOSTRefundPayment(body, paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#pOSTRefundPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**PostRefundType**](PostRefundType.md)| |
**paymentId** | **String**| The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRefundPaymentType**](GETRefundPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTApplyPayment"></a>
# **pUTApplyPayment**
> GETARPaymentType pUTApplyPayment(body, paymentId, zuoraEntityIds)
Apply payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Applies an unapplied payment to invoices and debit memos. When applying a payment, the total number of invoices and debit memos that the payment will apply to must be less than or equal to 1,000. If the Proration application rule is used, when applying a payment, the following quantity must be less than or equal to 10,000: (number of invoice items + number of debit memo items) * number of payment items Otherwise, the First In First Out rule will be used instead of the Proration rule. For more information, see [Apply Unapplied Payments to Invoices and Debit Memos](https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/A_Unapplied_Payments/Management_of_Unapplied_Payments/Apply_Unapplied_Payments_to_Invoices_and_Debit_Memos).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
ApplyPaymentType body = new ApplyPaymentType(); // ApplyPaymentType |
String paymentId = "paymentId_example"; // String | The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETARPaymentType result = apiInstance.pUTApplyPayment(body, paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#pUTApplyPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**ApplyPaymentType**](ApplyPaymentType.md)| |
**paymentId** | **String**| The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETARPaymentType**](GETARPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTCancelPayment"></a>
# **pUTCancelPayment**
> GETARPaymentType pUTCancelPayment(paymentId, zuoraEntityIds)
Cancel payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Cancels a payment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
String paymentId = "paymentId_example"; // String | The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETARPaymentType result = apiInstance.pUTCancelPayment(paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#pUTCancelPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentId** | **String**| The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETARPaymentType**](GETARPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTTransferPayment"></a>
# **pUTTransferPayment**
> GETARPaymentType pUTTransferPayment(body, paymentId, zuoraEntityIds)
Transfer payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Transfers an unapplied payment. For more information, see [Transfer Unapplied Payments](https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/A_Unapplied_Payments/Management_of_Unapplied_Payments/Transfer_Unapplied_Payments).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
TransferPaymentType body = new TransferPaymentType(); // TransferPaymentType |
String paymentId = "paymentId_example"; // String | The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETARPaymentType result = apiInstance.pUTTransferPayment(body, paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#pUTTransferPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**TransferPaymentType**](TransferPaymentType.md)| |
**paymentId** | **String**| The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETARPaymentType**](GETARPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUnapplyPayment"></a>
# **pUTUnapplyPayment**
> GETARPaymentType pUTUnapplyPayment(body, paymentId, zuoraEntityIds)
Unapply payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Unapplies an applied payment from invoices and debit memos. For more information, see [Unapply Payments from Invoices and Debit Memos](https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/A_Unapplied_Payments/Management_of_Unapplied_Payments/Unapply_Payments_from_Invoices_and_Debit_Memos).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
UnapplyPaymentType body = new UnapplyPaymentType(); // UnapplyPaymentType |
String paymentId = "paymentId_example"; // String | The unique ID of an applied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETARPaymentType result = apiInstance.pUTUnapplyPayment(body, paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#pUTUnapplyPayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**UnapplyPaymentType**](UnapplyPaymentType.md)| |
**paymentId** | **String**| The unique ID of an applied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETARPaymentType**](GETARPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUpdatePayment"></a>
# **pUTUpdatePayment**
> GETARPaymentType pUTUpdatePayment(body, paymentId, zuoraEntityIds)
Update payment
**Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Updates a payment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentsApi;
PaymentsApi apiInstance = new PaymentsApi();
UpdatePaymentType body = new UpdatePaymentType(); // UpdatePaymentType |
String paymentId = "paymentId_example"; // String | The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETARPaymentType result = apiInstance.pUTUpdatePayment(body, paymentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentsApi#pUTUpdatePayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**UpdatePaymentType**](UpdatePaymentType.md)| |
**paymentId** | **String**| The unique ID of an unapplied payment. For example, 8a8082e65b27f6c3015b89e4344c16b1. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETARPaymentType**](GETARPaymentType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># HostedPagesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**getHostedPages**](HostedPagesApi.md#getHostedPages) | **GET** /v1/hostedpages | Return hosted pages
<a name="getHostedPages"></a>
# **getHostedPages**
> GetHostedPagesType getHostedPages(zuoraEntityIds, pageSize, versionNumber)
Return hosted pages
The hostedpages call returns the Payment Pages configuration metadata, specifically, page ID, page version, payment method type. The following are the version-specific and general REST requests for Payment Pages: * The request for Payment Pages 1.0 configuration information: `GET <BaseURL>/hostedpages?version=1` * The request for Payment Pages 2.0 configuration information: `GET <BaseURL>/hostedpages?version=2` * The request for all versions of Payment Pages configuration information: `GET <BaseURL>/hostedpages` ## Notes If you do not have the corresponding tenant setting enabled, e.g., the request `version` parameter set to 2 with the Payment Pages 2.0 setting disabled, you will receive an error.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.HostedPagesApi;
HostedPagesApi apiInstance = new HostedPagesApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String versionNumber = "versionNumber_example"; // String | Version of the Payment Pages for which you want to retrieve the configuration information. Specify 1 for Payment Pages 1.0 or 2 for Payment Pages 2.0. If omitted, information for all versions of Payment Pages are returned. The response also depends on your tenant settings for Payment Pages 1.0 and Payment Pages 2.0. For example, if only the tenant setting for Payment Pages 2.0 is enabled, the response will only contain information for Payment Pages 2.0 forms even when this parameter is omitted.
try {
GetHostedPagesType result = apiInstance.getHostedPages(zuoraEntityIds, pageSize, versionNumber);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling HostedPagesApi#getHostedPages");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**versionNumber** | **String**| Version of the Payment Pages for which you want to retrieve the configuration information. Specify 1 for Payment Pages 1.0 or 2 for Payment Pages 2.0. If omitted, information for all versions of Payment Pages are returned. The response also depends on your tenant settings for Payment Pages 1.0 and Payment Pages 2.0. For example, if only the tenant setting for Payment Pages 2.0 is enabled, the response will only contain information for Payment Pages 2.0 forms even when this parameter is omitted. | [optional]
### Return type
[**GetHostedPagesType**](GetHostedPagesType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# CreditMemoUnapplyInvoiceRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The credit memo amount to be unapplied from the invoice. |
**invoiceId** | **String** | The unique ID of the invoice that the credit memo is unapplied from. |
**items** | [**List<CreditMemoUnapplyInvoiceItemRequestType>**](CreditMemoUnapplyInvoiceItemRequestType.md) | Container for items. | [optional]
<file_sep>
# PUTOrderActionTriggerDatesRequestTypeTriggerDates
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | [**NameEnum**](#NameEnum) | Name of the trigger date of the order action. | [optional]
**triggerDate** | [**LocalDate**](LocalDate.md) | Trigger date in YYYY-MM-DD format. The date you are to set as the service activation date or the customer acceptance date. | [optional]
<a name="NameEnum"></a>
## Enum: NameEnum
Name | Value
---- | -----
SERVICEACTIVATION | "ServiceActivation"
CUSTOMERACCEPTANCE | "CustomerAcceptance"
<file_sep>
# PUTOrderPatchRequestTypeSubscriptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**orderActions** | [**List<PUTOrderPatchRequestTypeOrderActions>**](PUTOrderPatchRequestTypeOrderActions.md) | | [optional]
**subscriptionNumber** | **String** | | [optional]
<file_sep># RsaSignaturesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**pOSTDecryptRSASignatures**](RsaSignaturesApi.md#pOSTDecryptRSASignatures) | **POST** /v1/rsa-signatures/decrypt | Decrypt RSA signature
[**pOSTRSASignatures**](RsaSignaturesApi.md#pOSTRSASignatures) | **POST** /v1/rsa-signatures | Generate RSA signature
<a name="pOSTDecryptRSASignatures"></a>
# **pOSTDecryptRSASignatures**
> POSTDecryptResponseType pOSTDecryptRSASignatures(request, zuoraEntityIds)
Decrypt RSA signature
The REST API used in Payment Pages 2.0 are CORS (Cross-Origin Resource Sharing) enabled and therefore requires a digital signature. You use rsa_signatures to generate the required digital signature and token for a Payment Pages 2.0 form, and then you use the decrypt REST service to decrypt the signature to validate the signature and key. This REST service should be used only when you implement Payment Pages 2.0.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RsaSignaturesApi;
RsaSignaturesApi apiInstance = new RsaSignaturesApi();
POSTDecryptionType request = new POSTDecryptionType(); // POSTDecryptionType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTDecryptResponseType result = apiInstance.pOSTDecryptRSASignatures(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RsaSignaturesApi#pOSTDecryptRSASignatures");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTDecryptionType**](POSTDecryptionType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTDecryptResponseType**](POSTDecryptResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSASignatures"></a>
# **pOSTRSASignatures**
> POSTRSASignatureResponseType pOSTRSASignatures(request, zuoraEntityIds)
Generate RSA signature
The REST API used in Payment Pages 2.0 are CORS (Cross-Origin Resource Sharing) enabled and therefore requires a digital signature. The POST rsa_signatures call generates and returns the required digital signature and token for a Payment Pages 2.0 form. You need to pass the generated signature to your client for it to access Payment Pages 2.0. This REST service should be used only when you implement Payment Pages 2.0.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RsaSignaturesApi;
RsaSignaturesApi apiInstance = new RsaSignaturesApi();
POSTRSASignatureType request = new POSTRSASignatureType(); // POSTRSASignatureType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTRSASignatureResponseType result = apiInstance.pOSTRSASignatures(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RsaSignaturesApi#pOSTRSASignatures");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTRSASignatureType**](POSTRSASignatureType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTRSASignatureResponseType**](POSTRSASignatureResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# POSTPublicNotificationDefinitionRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**active** | **Boolean** | The status of the notification definition. The default value is true. | [optional]
**callout** | [**POSTPublicNotificationDefinitionRequestCallout**](POSTPublicNotificationDefinitionRequestCallout.md) | | [optional]
**calloutActive** | **Boolean** | The status of the callout action. Default value is false. | [optional]
**communicationProfileId** | **String** | The profile that notification definition belongs to. If you do not pass the communicationProfileId, notification service will be automatically added to the 'Default Profile'. | [optional]
**description** | **String** | The description of the notification definition. | [optional]
**emailActive** | **Boolean** | The status of the email action. The default value is false. | [optional]
**emailTemplateId** | [**UUID**](UUID.md) | The ID of the email template. If emailActive is true, an email template is required. And EventType of the email template MUST be the same as the eventType. | [optional]
**eventTypeName** | **String** | The name of the event type. |
**filterRule** | [**POSTPublicNotificationDefinitionRequestFilterRule**](POSTPublicNotificationDefinitionRequestFilterRule.md) | | [optional]
**filterRuleParams** | [**FilterRuleParameterValues**](FilterRuleParameterValues.md) | | [optional]
**name** | **String** | The name of the notification definition, unique per communication profile. |
<file_sep>
# GETJournalRunType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**aggregateCurrency** | **Boolean** | | [optional]
**executedOn** | [**OffsetDateTime**](OffsetDateTime.md) | Date and time the journal run was executed. | [optional]
**journalEntryDate** | [**LocalDate**](LocalDate.md) | Date of the journal entry. | [optional]
**number** | **String** | Journal run number. | [optional]
**segmentationRuleName** | **String** | Name of GL segmentation rule used in the journal run. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | Status of the journal run. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**targetEndDate** | [**LocalDate**](LocalDate.md) | The target end date of the journal run. | [optional]
**targetStartDate** | [**LocalDate**](LocalDate.md) | The target start date of the journal run. | [optional]
**totalJournalEntryCount** | **Long** | Total number of journal entries in the journal run. | [optional]
**transactionTypes** | [**List<GETJournalRunTransactionType>**](GETJournalRunTransactionType.md) | Transaction types included in the journal run. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PENDING | "Pending"
PROCESSING | "Processing"
COMPLETED | "Completed"
ERROR | "Error"
CANCELINPROGRESS | "CancelInprogress"
CANCELLED | "Cancelled"
DELETEINPROGRESS | "DeleteInprogress"
<file_sep># AttachmentsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEAttachments**](AttachmentsApi.md#dELETEAttachments) | **DELETE** /v1/attachments/{attachment-id} | Delete attachments
[**gETAttachments**](AttachmentsApi.md#gETAttachments) | **GET** /v1/attachments/{attachment-id} | View attachments
[**gETAttachmentsList**](AttachmentsApi.md#gETAttachmentsList) | **GET** /v1/attachments/{object-type}/{object-key} | View attachments list
[**pOSTAttachments**](AttachmentsApi.md#pOSTAttachments) | **POST** /v1/attachments | Add attachments
[**pUTAttachments**](AttachmentsApi.md#pUTAttachments) | **PUT** /v1/attachments/{attachment-id} | Edit attachments
<a name="dELETEAttachments"></a>
# **dELETEAttachments**
> CommonResponseType dELETEAttachments(attachmentId, zuoraEntityIds)
Delete attachments
Use the Delete Attachment REST request to delete an attachment from a Zuora object.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AttachmentsApi;
AttachmentsApi apiInstance = new AttachmentsApi();
String attachmentId = "attachmentId_example"; // String | Id of the attachment to be deleted.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEAttachments(attachmentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#dELETEAttachments");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**attachmentId** | **String**| Id of the attachment to be deleted. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAttachments"></a>
# **gETAttachments**
> GETAttachmentResponseType gETAttachments(attachmentId, zuoraEntityIds)
View attachments
Use the View Attachment REST request to retrieve information about an attachment document.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AttachmentsApi;
AttachmentsApi apiInstance = new AttachmentsApi();
String attachmentId = "attachmentId_example"; // String | Id of the attachment you want to view.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETAttachmentResponseType result = apiInstance.gETAttachments(attachmentId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#gETAttachments");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**attachmentId** | **String**| Id of the attachment you want to view. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETAttachmentResponseType**](GETAttachmentResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAttachmentsList"></a>
# **gETAttachmentsList**
> GETAttachmentsResponseType gETAttachmentsList(objectType, objectKey, zuoraEntityIds, pageSize)
View attachments list
Use the View Attachment REST request to get a list of attachments on an account, an invoice, or a subscription.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AttachmentsApi;
AttachmentsApi apiInstance = new AttachmentsApi();
String objectType = "objectType_example"; // String | The type of object to list attachements for.
String objectKey = "objectKey_example"; // String | ID of the object to list attachements for. - If `object-type` is `account`, specify an account ID. - If `object-type` is `invoice`, specify an invoice ID. - If `object-type` is `subscription`, specify a subscription number.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETAttachmentsResponseType result = apiInstance.gETAttachmentsList(objectType, objectKey, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#gETAttachmentsList");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**objectType** | **String**| The type of object to list attachements for. | [enum: account, invoice, subscription]
**objectKey** | **String**| ID of the object to list attachements for. - If `object-type` is `account`, specify an account ID. - If `object-type` is `invoice`, specify an invoice ID. - If `object-type` is `subscription`, specify a subscription number. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETAttachmentsResponseType**](GETAttachmentsResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTAttachments"></a>
# **pOSTAttachments**
> POSTAttachmentResponseType pOSTAttachments(associatedObjectType, associatedObjectKey, file, zuoraEntityIds, description)
Add attachments
Use the Add Attachment REST request with a multipart/form-data to attach a document file to an Account, a Subscription, or an Invoice.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AttachmentsApi;
AttachmentsApi apiInstance = new AttachmentsApi();
String associatedObjectType = "associatedObjectType_example"; // String | Specify one of the following values: Account, Subscription, or Invoice.
String associatedObjectKey = "associatedObjectKey_example"; // String | For the Subscription type, specify the Subscription Number. An attachment is tied to the Subscription Number and thus viewable with every subscription version. For Account and Invoice, specify the id.
File file = new File("/path/to/file.txt"); // File | The file to be attached. Files with the following extensions are supported: .pdf, .csv, .png, .xlsx, .xls, .doc, .docx, .msg, .jpg, .txt, .htm, .html, .eml, .pptx, .gif, .rtf, .xml, .jpeg, .log, .cls The maximum file size is 4 MB.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String description = "description_example"; // String | Description of the attachment document.
try {
POSTAttachmentResponseType result = apiInstance.pOSTAttachments(associatedObjectType, associatedObjectKey, file, zuoraEntityIds, description);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#pOSTAttachments");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**associatedObjectType** | **String**| Specify one of the following values: Account, Subscription, or Invoice. |
**associatedObjectKey** | **String**| For the Subscription type, specify the Subscription Number. An attachment is tied to the Subscription Number and thus viewable with every subscription version. For Account and Invoice, specify the id. |
**file** | **File**| The file to be attached. Files with the following extensions are supported: .pdf, .csv, .png, .xlsx, .xls, .doc, .docx, .msg, .jpg, .txt, .htm, .html, .eml, .pptx, .gif, .rtf, .xml, .jpeg, .log, .cls The maximum file size is 4 MB. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**description** | **String**| Description of the attachment document. | [optional]
### Return type
[**POSTAttachmentResponseType**](POSTAttachmentResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json; charset=utf-8
<a name="pUTAttachments"></a>
# **pUTAttachments**
> CommonResponseType pUTAttachments(attachmentId, zuoraEntityIds, request)
Edit attachments
Use the Edit Attachment REST request to make changes to the descriptive fields of an attachment, such as the description and the file name. You cannot change the actual content of the attached file in Zuora. If you need to change the actual content, you need to delete the attachment and add the updated file as a new attachment.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AttachmentsApi;
AttachmentsApi apiInstance = new AttachmentsApi();
String attachmentId = "attachmentId_example"; // String | Id of the attachment to be updated.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
PUTAttachmentType request = new PUTAttachmentType(); // PUTAttachmentType |
try {
CommonResponseType result = apiInstance.pUTAttachments(attachmentId, zuoraEntityIds, request);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#pUTAttachments");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**attachmentId** | **String**| Id of the attachment to be updated. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**request** | [**PUTAttachmentType**](PUTAttachmentType.md)| | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# ProxyActionexecuteRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ids** | **List<String>** | The ID of the object. **Values:** a valid InvoiceSplit object ID. |
**synchronous** | **Boolean** | Indicates if the call is synchronous or asynchronous. **Values:** `false` |
**type** | [**TypeEnum**](#TypeEnum) | Specifies the type of executed item. |
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
INVOICESPLIT | "InvoiceSplit"
<file_sep>
# PutInvoiceType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**autoPay** | **Boolean** | Whether invoices are automatically picked up for processing in the corresponding payment run. By default, invoices are automatically picked up for processing in the corresponding payment run. | [optional]
**dueDate** | [**LocalDate**](LocalDate.md) | The date by which the payment for this invoice is due. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the invoice was transferred to an external accounting system. | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# GETEntitiesResponseTypeWithId
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**displayName** | **String** | The display name of the entity that is shown in the Zuora UI and APIs. | [optional]
**id** | **String** | The entity Id. | [optional]
**locale** | **String** | The locale that is used in this entity. | [optional]
**name** | **String** | The name of the entity. | [optional]
**parentId** | **String** | The Id of the parent entity. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the entity. | [optional]
**success** | **Boolean** | Returns `true` if the request is successful. | [optional]
**tenantId** | **String** | The Id of the tenant that the entity belongs to. | [optional]
**timezone** | **String** | The time zone that is used in this entity. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PROVISIONED | "Provisioned"
UNPROVISIONED | "Unprovisioned"
<file_sep>
# POSTVoidAuthorize
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | **String** | The ID of the customer account. |
**accountNumber** | **String** | The number of the customer account. |
**gatewayOrderId** | **String** | The order ID for the specific gateway. |
**transactionId** | **String** | The ID of the transaction. |
<file_sep>
# PUTOrderPatchRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFields** | [**OrderObjectCustomFields**](OrderObjectCustomFields.md) | | [optional]
**subscriptions** | [**List<PUTOrderPatchRequestTypeSubscriptions>**](PUTOrderPatchRequestTypeSubscriptions.md) | | [optional]
<file_sep>
# DebitMemoFromInvoiceType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the debit memo's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the debit memo was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**autoPay** | **Boolean** | Whether debit memos are automatically picked up for processing in the corresponding payment run. By default, debit memos are automatically picked up for processing in the corresponding payment run. | [optional]
**comment** | **String** | Comments about the debit memo. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the debit memo takes effect. | [optional]
**invoiceId** | **String** | The ID of the invoice that the debit memo is created from. | [optional]
**items** | [**List<DebitMemoItemFromInvoiceItemType>**](DebitMemoItemFromInvoiceItemType.md) | Container for items. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. The value must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. | [optional]
**taxAutoCalculation** | **Boolean** | Whether to automatically calculate taxes in the debit memo. | [optional]
<file_sep>
# ChargeTier
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**endingUnit** | [**BigDecimal**](BigDecimal.md) | Limit on the number of units for which the tier is effective. | [optional]
**price** | [**BigDecimal**](BigDecimal.md) | Price or per-unit price of the tier, depending on the value of the `priceFormat` field. |
**priceFormat** | [**PriceFormatEnum**](#PriceFormatEnum) | Specifies whether the tier has a fixed price or a per-unit price. | [optional]
**startingUnit** | [**BigDecimal**](BigDecimal.md) | Number of units at which the tier becomes effective. |
**tier** | **Integer** | Index of the tier in the charge. |
<a name="PriceFormatEnum"></a>
## Enum: PriceFormatEnum
Name | Value
---- | -----
FLATFEE | "FlatFee"
PERUNIT | "PerUnit"
<file_sep># UsageApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETUsage**](UsageApi.md#gETUsage) | **GET** /v1/usage/accounts/{account-key} | Get usage
[**objectDELETEUsage**](UsageApi.md#objectDELETEUsage) | **DELETE** /v1/object/usage/{id} | CRUD: Delete Usage
[**objectGETUsage**](UsageApi.md#objectGETUsage) | **GET** /v1/object/usage/{id} | CRUD: Retrieve Usage
[**objectPOSTUsage**](UsageApi.md#objectPOSTUsage) | **POST** /v1/object/usage | CRUD: Create Usage
[**objectPUTUsage**](UsageApi.md#objectPUTUsage) | **PUT** /v1/object/usage/{id} | CRUD: Update Usage
[**pOSTUsage**](UsageApi.md#pOSTUsage) | **POST** /v1/usage | Post usage
<a name="gETUsage"></a>
# **gETUsage**
> GETUsageWrapper gETUsage(accountKey, zuoraEntityIds, pageSize)
Get usage
This REST API reference describes how to retrieve usage details for an account. Usage data is returned in reverse chronological order.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsageApi;
UsageApi apiInstance = new UsageApi();
String accountKey = "accountKey_example"; // String | Account number or account ID.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETUsageWrapper result = apiInstance.gETUsage(accountKey, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsageApi#gETUsage");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Account number or account ID. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETUsageWrapper**](GETUsageWrapper.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETEUsage"></a>
# **objectDELETEUsage**
> ProxyDeleteResponse objectDELETEUsage(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Usage
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsageApi;
UsageApi apiInstance = new UsageApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEUsage(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsageApi#objectDELETEUsage");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETUsage"></a>
# **objectGETUsage**
> ProxyGetUsage objectGETUsage(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Usage
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsageApi;
UsageApi apiInstance = new UsageApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetUsage result = apiInstance.objectGETUsage(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsageApi#objectGETUsage");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetUsage**](ProxyGetUsage.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTUsage"></a>
# **objectPOSTUsage**
> ProxyCreateOrModifyResponse objectPOSTUsage(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create Usage
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsageApi;
UsageApi apiInstance = new UsageApi();
ProxyCreateUsage createRequest = new ProxyCreateUsage(); // ProxyCreateUsage |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTUsage(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsageApi#objectPOSTUsage");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateUsage**](ProxyCreateUsage.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTUsage"></a>
# **objectPUTUsage**
> ProxyCreateOrModifyResponse objectPUTUsage(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update Usage
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsageApi;
UsageApi apiInstance = new UsageApi();
String id = "id_example"; // String | Object id
ProxyModifyUsage modifyRequest = new ProxyModifyUsage(); // ProxyModifyUsage |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTUsage(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsageApi#objectPUTUsage");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyUsage**](ProxyModifyUsage.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTUsage"></a>
# **pOSTUsage**
> POSTUsageResponseType pOSTUsage(file, zuoraEntityIds)
Post usage
This REST API reference describes how to post or import usage data for one or more accounts in the CSV format. There are no path or query parameters. The data is uploade using the HTTP multipart/form-data POST method and applied to the user's tenant. ## How this REST API Call Works The content of the upload file must follow the format used by the UI import tool. It must be a comma-separated (CSV) file with a corresponding .csv extension. The length of the file name must not exceed 50 characters. The file size must not exceed 4MB. Click [here](https://knowledgecenter.zuora.com/@api/deki/files/4105/UsageFileFormat.csv) to download the usage file template. At the completion of the upload, before actually processing the file contents, theAPI returns a response containing the byte count of the received file and a URL for checking the status of the import process. Of the five possible results displayed at that URL Pending, Processing, Completed, Canceled, and Failed) only a Completed status indicates that the import was successful. The operation is atomic; if any record fails, the file is rejected. In that case, the entire import is rolled back and all stored data is returned to its original state. To view the actual import status, enter the resulting status URL from the checkImportStatus response using a tool such as POSTMAN.This additional step provides more information about why the import may have failed. To manage the information after a successful upload, use the web-based UI. ## Upload File Format The upload file uses the following headings: | Heading | Description | Required | |-----------------|--------|----------| | ACCOUNT_ID | Enter the account number, e.g., the default account number, such as A00000001, or your custom account number.,Although this field is labeled as Account_Id, it is not the actual Account ID nor Account Name. | Yes | | UOM | Enter the unit of measure. This must match the UOM for the usage. | Yes | | QTY | Enter the quantity. | Yes | | STARTDATE | Enter the start date of the usage.,This date determines the invoice item service period the associated usage is billed to. Date format is based on locale of the current user. Default date format: `MM/DD/YYYY` | Yes | | ENDDATE | Enter the end date of the usage.,This is not used in calculations for usage billing and is optional. Date format is based on locale of the current user. Default date format: `MM/DD/YYYY` | Yes | | SUBSCRIPTION_ID | Enter the subscription number or subscription name. If you created the subscription in the Zuora application, Zuora created a number automatically in a format similar to A-S00000001. If you do not provide a value for this field, the associated usage will be added to all subscriptions for the specified Account that use this Unit Of Measure. If your Accounts can have multiple subscriptions and you do not want double or triple counting of usage, you must specify the Subscription or Charge ID in each usage record. | Yes | | CHARGE_ID | Enter the charge number (not the charge name). You can see the charge ID, e.g., C-00000001, when you add your rate plan to your subscription and view your individual charges. If your Accounts can have multiple subscriptions and you do not want double or triple counting of usage, you must specify the specific Subscription or Charge ID in each usage record. This field is related to the Charge Number on the subscription rate plan. | Yes | | DESCRIPTION | Enter a description for the charge. | No |
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsageApi;
UsageApi apiInstance = new UsageApi();
File file = new File("/path/to/file.txt"); // File | The usage data to import.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTUsageResponseType result = apiInstance.pOSTUsage(file, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsageApi#pOSTUsage");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**file** | **File**| The usage data to import. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTUsageResponseType**](POSTUsageResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json; charset=utf-8
<file_sep>
# CreditMemoItemFromInvoiceItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The amount of the invoice item. |
**comment** | **String** | Comments about the invoice item. | [optional]
**financeInformation** | [**CreditMemoItemFromInvoiceItemTypeFinanceInformation**](CreditMemoItemFromInvoiceItemTypeFinanceInformation.md) | | [optional]
**invoiceItemId** | **String** | The ID of the invoice item. | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | The service end date of the invoice item. | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | The service start date of the invoice item. | [optional]
**skuName** | **String** | The name of the SKU. |
**taxItems** | [**List<CreditMemoTaxItemFromInvoiceTaxItemType>**](CreditMemoTaxItemFromInvoiceTaxItemType.md) | Container for taxation items. | [optional]
**unitOfMeasure** | **String** | The definable unit that you measure when determining charges. | [optional]
<file_sep># AccountsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETAccount**](AccountsApi.md#gETAccount) | **GET** /v1/accounts/{account-key} | Get account
[**gETAccountSummary**](AccountsApi.md#gETAccountSummary) | **GET** /v1/accounts/{account-key}/summary | Get account summary
[**gETBillingDocumentFilesDeletionJob**](AccountsApi.md#gETBillingDocumentFilesDeletionJob) | **GET** /v1/accounts/billing-documents/files/deletion-jobs/{jobId} | Get job of hard deleting billing document files
[**objectDELETEAccount**](AccountsApi.md#objectDELETEAccount) | **DELETE** /v1/object/account/{id} | CRUD: Delete Account
[**objectGETAccount**](AccountsApi.md#objectGETAccount) | **GET** /v1/object/account/{id} | CRUD: Retrieve Account
[**objectPOSTAccount**](AccountsApi.md#objectPOSTAccount) | **POST** /v1/object/account | CRUD: Create Account
[**objectPUTAccount**](AccountsApi.md#objectPUTAccount) | **PUT** /v1/object/account/{id} | CRUD: Update Account
[**pOSTAccount**](AccountsApi.md#pOSTAccount) | **POST** /v1/accounts | Create account
[**pOSTBillingDocumentFilesDeletionJob**](AccountsApi.md#pOSTBillingDocumentFilesDeletionJob) | **POST** /v1/accounts/billing-documents/files/deletion-jobs | Create job to hard delete billing document files
[**pOSTGenerateBillingDocuments**](AccountsApi.md#pOSTGenerateBillingDocuments) | **POST** /v1/accounts/{id}/billing-documents/generate | Generate billing documents by account
[**pUTAccount**](AccountsApi.md#pUTAccount) | **PUT** /v1/accounts/{account-key} | Update account
<a name="gETAccount"></a>
# **gETAccount**
> GETAccountType gETAccount(accountKey, zuoraEntityIds)
Get account
This REST API reference describes how to retrieve basic information about a customer account. This REST call is a quick retrieval that doesn't include the account's subscriptions, invoices, payments, or usage details. Use Get account summary to get more detailed information about an account.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
String accountKey = "accountKey_example"; // String | Account number or account ID.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETAccountType result = apiInstance.gETAccount(accountKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#gETAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Account number or account ID. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETAccountType**](GETAccountType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAccountSummary"></a>
# **gETAccountSummary**
> GETAccountSummaryType gETAccountSummary(accountKey, zuoraEntityIds)
Get account summary
This REST API reference describes how to retrieve detailed information about the specified customer account. The response includes the account information and a summary of the account’s subscriptions, invoices, payments, and usages for the last six recently updated subscriptions. ## Notes Returns only the six most recent subscriptions based on the subscription updatedDate. Within those subscriptions, there may be many rate plans and many rate plan charges. These items are subject to the maximum limit on the array size.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
String accountKey = "accountKey_example"; // String | Account number or account ID.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETAccountSummaryType result = apiInstance.gETAccountSummary(accountKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#gETAccountSummary");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Account number or account ID. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETAccountSummaryType**](GETAccountSummaryType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETBillingDocumentFilesDeletionJob"></a>
# **gETBillingDocumentFilesDeletionJob**
> GETBillingDocumentFilesDeletionJobResponse gETBillingDocumentFilesDeletionJob(jobId, zuoraEntityIds)
Get job of hard deleting billing document files
Retrieves information about an asynchronous job of permanently deleting all billing document PDF files for specific accounts. **Note**: This REST API operation can be used only if you have the Billing user permission \"Hard Delete Billing Document Files\" enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
String jobId = "jobId_example"; // String | The unique ID of a billing document file deletion job. For example, 2c92c8f83dc4f752013dc72c24ee016c.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETBillingDocumentFilesDeletionJobResponse result = apiInstance.gETBillingDocumentFilesDeletionJob(jobId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#gETBillingDocumentFilesDeletionJob");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jobId** | **String**| The unique ID of a billing document file deletion job. For example, 2c92c8f83dc4f752013dc72c24ee016c. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETBillingDocumentFilesDeletionJobResponse**](GETBillingDocumentFilesDeletionJobResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETEAccount"></a>
# **objectDELETEAccount**
> ProxyDeleteResponse objectDELETEAccount(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Account
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEAccount(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#objectDELETEAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETAccount"></a>
# **objectGETAccount**
> ProxyGetAccount objectGETAccount(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Account
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetAccount result = apiInstance.objectGETAccount(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#objectGETAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetAccount**](ProxyGetAccount.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTAccount"></a>
# **objectPOSTAccount**
> ProxyCreateOrModifyResponse objectPOSTAccount(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create Account
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
ProxyCreateAccount createRequest = new ProxyCreateAccount(); // ProxyCreateAccount |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTAccount(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#objectPOSTAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateAccount**](ProxyCreateAccount.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTAccount"></a>
# **objectPUTAccount**
> ProxyCreateOrModifyResponse objectPUTAccount(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update Account
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
String id = "id_example"; // String | Object id
ProxyModifyAccount modifyRequest = new ProxyModifyAccount(); // ProxyModifyAccount |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTAccount(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#objectPUTAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyAccount**](ProxyModifyAccount.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTAccount"></a>
# **pOSTAccount**
> POSTAccountResponseType pOSTAccount(request, zuoraEntityIds, zuoraVersion)
Create account
This REST API reference describes how to create a customer account with a credit-card payment method, a bill-to contact, and an optional sold-to contact. Request and response field descriptions and sample code are provided. Use this method to optionally create a subscription, invoice for that subscription, and collect payment through the default payment method. The transaction is atomic; if any part fails for any reason, the entire transaction is rolled back. This API call is CORS Enabled, so you can use client-side Javascript to invoke the call. ## Notes 1. The account is created in active status. 2. The request must provide either a **creditCard** structure or the **hpmCreditCardPaymentMethodId** field (but not both). The one provided becomes the default payment method for this account. If the credit card information is declined or can't be verified, then the account is not created. 3. Customer accounts created with this call are automatically be set to Auto Pay. 4. If either the **workEmail** or **personalEmail** are specified, then the account's email delivery preference is automatically set to `true`. (In that case, emails go to the **workEmail** address, if it exists, or else the **personalEmail**.) If neither field is specified, the email delivery preference is automatically set to `false`. 5. You cannot use this operation to create subscriptions if you have the Orders feature enabled. See [Orders Migration Guidance](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AB_Orders_Migration_Guidance) for more information. ## Defaults for customerAcceptanceDate and serviceActivationDate Default values for **customerAcceptanceDate** and **serviceActivationDate** are set as follows. | | serviceActivationDate(SA) specified | serviceActivationDate (SA) NOT specified | | ------------- |:-------------:| -----:| | customerAcceptanceDate (CA) specified | SA uses value in the request call; CA uses value in the request call| CA uses value in the request call;SA uses CE as default | | customerAcceptanceDate (CA) NOT specified | SA uses value in the request call; CA uses SA as default | SA and CA use CE as default |
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
POSTAccountType request = new POSTAccountType(); // POSTAccountType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate
try {
POSTAccountResponseType result = apiInstance.pOSTAccount(request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#pOSTAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTAccountType**](POSTAccountType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the following fields: * invoice * collect * runBilling * targetDate | [optional]
### Return type
[**POSTAccountResponseType**](POSTAccountResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTBillingDocumentFilesDeletionJob"></a>
# **pOSTBillingDocumentFilesDeletionJob**
> POSTBillingDocumentFilesDeletionJobResponse pOSTBillingDocumentFilesDeletionJob(body, zuoraEntityIds)
Create job to hard delete billing document files
Creates an asynchronous job to permanently delete all billing document PDF files for specific accounts. After the deletion job is completed, all billing document PDF files are permanently deleted. To retrieve the status of a deletion job, call [Get job of hard deleting billing document files](https://www.zuora.com/developer/api-reference/#operation/GET_BillingDocumentFilesDeletionJob). **Note**: This REST API operation can be used only if you have the Billing user permission \"Hard Delete Billing Document Files\" enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
POSTBillingDocumentFilesDeletionJobRequest body = new POSTBillingDocumentFilesDeletionJobRequest(); // POSTBillingDocumentFilesDeletionJobRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTBillingDocumentFilesDeletionJobResponse result = apiInstance.pOSTBillingDocumentFilesDeletionJob(body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#pOSTBillingDocumentFilesDeletionJob");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**POSTBillingDocumentFilesDeletionJobRequest**](POSTBillingDocumentFilesDeletionJobRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTBillingDocumentFilesDeletionJobResponse**](POSTBillingDocumentFilesDeletionJobResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTGenerateBillingDocuments"></a>
# **pOSTGenerateBillingDocuments**
> GenerateBillingDocumentResponseType pOSTGenerateBillingDocuments(body, id, zuoraEntityIds)
Generate billing documents by account
Generates draft or posted billing documents for a specified account. You can also generate billing documents for specified subscriptions of a specified account. The billing documents contain invoices and credit memos. To generate credit memos, you must have the Invoice Settlement feature enabled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
PostGenerateBillingDocumentType body = new PostGenerateBillingDocumentType(); // PostGenerateBillingDocumentType |
String id = "id_example"; // String | The ID of the customer account that billing documents are generated for. For example, 8a8082e65b27f6c3015ba3e326b26419.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GenerateBillingDocumentResponseType result = apiInstance.pOSTGenerateBillingDocuments(body, id, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#pOSTGenerateBillingDocuments");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**PostGenerateBillingDocumentType**](PostGenerateBillingDocumentType.md)| |
**id** | **String**| The ID of the customer account that billing documents are generated for. For example, 8a8082e65b27f6c3015ba3e326b26419. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GenerateBillingDocumentResponseType**](GenerateBillingDocumentResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTAccount"></a>
# **pUTAccount**
> CommonResponseType pUTAccount(accountKey, request, zuoraEntityIds)
Update account
This REST API reference describes how to update a customer account by specifying the account-key. ## Notes 1. Only the fields to be changed should be specified. Any field that's not included in the request body will not be changed. 2. If an empty field is submitted with this call, the corresponding field in the account is emptied. 3. Email addresses: If no email addresses are specified, no change is made to the email addresses on file or to the email delivery preference. If either the **personalEmail** or **workEmail** is specified (or both), the system updates the corresponding email address(es) on file and the email delivery preference is set to `true`. (In that case, emails go to the **workEmail** address, if it exists, or else the **personalEmail**.) On the other hand, if as a result of this call both of the email addresses for the account are empty, the email delivery preference is set to `false`. 4. The bill-to and sold-to contacts are separate data entities; updating either one does not update the other.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountsApi;
AccountsApi apiInstance = new AccountsApi();
String accountKey = "accountKey_example"; // String | Account number or account ID.
PUTAccountType request = new PUTAccountType(); // PUTAccountType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTAccount(accountKey, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountsApi#pUTAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Account number or account ID. |
**request** | [**PUTAccountType**](PUTAccountType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# POSTPaymentMethodRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**BAID** | **String** | ID of a PayPal billing agreement. For example, I-1TJ3GAGG82Y9. | [optional]
**email** | **String** | Email address associated with the payment method. This field is required if you want to create a PayPal Express Checkout payment method or a PayPal Adaptive payment method. | [optional]
**preapprovalKey** | **String** | The PayPal preapproval key. | [optional]
**accountKey** | **String** | Internal ID of the customer account that will own the payment method. | [optional]
**authGateway** | **String** | Internal ID of the payment gateway that Zuora will use to authorize the payments that are made with the payment method. If you do not set this field, Zuora will use one of the following payment gateways instead: * The default payment gateway of the customer account that owns the payment method, if the `accountKey` field is set. * The default payment gateway of your Zuora tenant, if the `accountKey` field is not set. | [optional]
**makeDefault** | **Boolean** | Specifies whether the payment method will be the default payment method of the customer account that owns the payment method. Only applicable if the `accountKey` field is set. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Type of payment method. The following types of the payment method are supported: * `PayPalEC` - PayPal Express Checkout payment method. Use this type if you are using a [PayPal Payflow Pro Gateway](https://knowledgecenter.zuora.com/CB_Billing/M_Payment_Gateways/Supported_Payment_Gateways/PayPal_Payflow_Pro%2C_Website_Payments_Payflow_Edition%2C_Website_Pro_Payment_Gateway) instance. * `PayPalNativeEC` - PayPal Native Express Checkout payment method. Use this type if you are using a [PayPal Express Checkout Gateway](https://knowledgecenter.zuora.com/CB_Billing/M_Payment_Gateways/Supported_Payment_Gateways/PayPal_Express_Checkout_Gateway) instance. * `PayPalAdaptive` - PayPal Adaptive payment method. Use this type if you are using a [PayPal Adaptive Payment Gateway](https://knowledgecenter.zuora.com/CB_Billing/M_Payment_Gateways/Supported_Payment_Gateways/PayPal_Adaptive_Payments_Gateway) instance. |
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
PAYPALEC | "PayPalEC"
PAYPALNATIVEEC | "PayPalNativeEC"
PAYPALADAPTIVE | "PayPalAdaptive"
<file_sep>
# PostOrderResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**accountNumber** | **String** | The account number for the order. | [optional]
**creditMemoNumbers** | **List<String>** | An array of the credit memo numbers generated in this order request. The credit memo is only available if you have the Avdanced AR Settlement feature enabled. | [optional]
**invoiceNumbers** | **List<String>** | An array of the invoice numbers generated in this order request. Normally it includes one invoice number only, but can include multiple items when a subscription was tagged as invoice separately. | [optional]
**orderNumber** | **String** | The order number of the order created. | [optional]
**paidAmount** | **String** | The total amount collected in this order request. | [optional]
**paymentNumber** | **String** | The payment number that collected in this order request. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | Status of the order. `Pending` is only applicable for an order that contains a `CreateSubscription` order action. | [optional]
**subscriptionNumbers** | **List<String>** | **Note:** This field is in Zuora REST API version control. Supported minor versions are 222.4 or earlier. To use this field in the method, you must set the `zuora-version` parameter to the minor version number in the request header. Container for the subscription numbers of the subscriptions in an order. | [optional]
**subscriptions** | [**List<PostOrderResponseTypeSubscriptions>**](PostOrderResponseTypeSubscriptions.md) | **Note:** This field is in Zuora REST API version control. Supported minor versions are 223.0 or later. To use this field in the method, you must set the `zuora-version` parameter to the minor version number in the request header. Container for the subscription numbers and statuses in an order. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
COMPLETED | "Completed"
PENDING | "Pending"
<file_sep>
# InvoiceFile
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **String** | The ID of the invoice PDF file. This is the ID for the file object and different from the file handle ID in the `pdfFileUrl` field. To open a file, you have to use the file handle ID. | [optional]
**pdfFileUrl** | **String** | The REST URL for the invoice PDF file. Click the URL to open the invoice PDF file. | [optional]
**versionNumber** | **Long** | The version number of the invoice PDF file. | [optional]
<file_sep>
# GETAccountSummarySubscriptionType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cpqBundleJsonIdQT** | **String** | The Bundle product structures from Zuora Quotes if you utilize Bundling in Salesforce. Do not change the value in this field. | [optional]
**opportunityCloseDateQT** | [**LocalDate**](LocalDate.md) | The closing date of the Opportunity. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**opportunityNameQT** | **String** | The unique identifier of the Opportunity. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteBusinessTypeQT** | **String** | The specific identifier for the type of business transaction the Quote represents such as New, Upsell, Downsell, Renewal or Churn. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteNumberQT** | **String** | The unique identifier of the Quote. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**quoteTypeQT** | **String** | The Quote type that represents the subscription lifecycle stage such as New, Amendment, Renew or Cancel. This field is used in Zuora data sources to report on Subscription metrics. If the subscription originated from Zuora Quotes, the value is populated with the value from Zuora Quotes. | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the subscription's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**projectNS** | **String** | The NetSuite project that the subscription was created from. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**salesOrderNS** | **String** | The NetSuite sales order than the subscription was created from. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the subscription was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**autoRenew** | **Boolean** | If `true`, auto-renew is enabled. If `false`, auto-renew is disabled. | [optional]
**id** | **String** | Subscription ID. | [optional]
**initialTerm** | **String** | Duration of the initial subscription term in whole months. | [optional]
**ratePlans** | [**List<GETAccountSummarySubscriptionRatePlanType>**](GETAccountSummarySubscriptionRatePlanType.md) | Container for rate plans for this subscription. | [optional]
**renewalTerm** | **String** | Duration of the renewal term in whole months. | [optional]
**status** | **String** | Subscription status; possible values are: `Draft`, `PendingActivation`, `PendingAcceptance`, `Active`, `Cancelled`, `Expired`. | [optional]
**subscriptionNumber** | **String** | Subscription Number. | [optional]
**subscriptionStartDate** | [**LocalDate**](LocalDate.md) | Subscription start date. | [optional]
**termEndDate** | [**LocalDate**](LocalDate.md) | End date of the subscription term. If the subscription is evergreen, this is either null or equal to the cancellation date, as appropriate. | [optional]
**termStartDate** | [**LocalDate**](LocalDate.md) | Start date of the subscription term. If this is a renewal subscription, this date is different than the subscription start date. | [optional]
**termType** | **String** | Possible values are: `TERMED`, `EVERGREEN`. | [optional]
<file_sep># JournalRunsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEJournalRun**](JournalRunsApi.md#dELETEJournalRun) | **DELETE** /v1/journal-runs/{jr-number} | Delete journal run
[**gETJournalRun**](JournalRunsApi.md#gETJournalRun) | **GET** /v1/journal-runs/{jr-number} | Get journal run
[**pOSTJournalRun**](JournalRunsApi.md#pOSTJournalRun) | **POST** /v1/journal-runs | Create journal run
[**pUTJournalRun**](JournalRunsApi.md#pUTJournalRun) | **PUT** /v1/journal-runs/{jr-number}/cancel | Cancel journal run
<a name="dELETEJournalRun"></a>
# **dELETEJournalRun**
> CommonResponseType dELETEJournalRun(jrNumber, zuoraEntityIds)
Delete journal run
This reference describes how to delete a journal run using the REST API. You can only delete journal runs that have already been canceled. You must have the \"Delete Cancelled Journal Run\" Zuora Finance user permission enabled to delete journal runs.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.JournalRunsApi;
JournalRunsApi apiInstance = new JournalRunsApi();
String jrNumber = "jrNumber_example"; // String | Journal run number. Must be a valid journal run number in the format `JR-00000001`.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEJournalRun(jrNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling JournalRunsApi#dELETEJournalRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jrNumber** | **String**| Journal run number. Must be a valid journal run number in the format `JR-00000001`. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETJournalRun"></a>
# **gETJournalRun**
> GETJournalRunType gETJournalRun(jrNumber, zuoraEntityIds)
Get journal run
This REST API reference describes how to get information about a journal run. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.JournalRunsApi;
JournalRunsApi apiInstance = new JournalRunsApi();
String jrNumber = "jrNumber_example"; // String | Journal run number. Must be a valid journal run number in the format `JR-00000001`.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETJournalRunType result = apiInstance.gETJournalRun(jrNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling JournalRunsApi#gETJournalRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jrNumber** | **String**| Journal run number. Must be a valid journal run number in the format `JR-00000001`. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETJournalRunType**](GETJournalRunType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTJournalRun"></a>
# **pOSTJournalRun**
> POSTJournalRunResponseType pOSTJournalRun(request, zuoraEntityIds)
Create journal run
This REST API reference describes how to create a journal run. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.JournalRunsApi;
JournalRunsApi apiInstance = new JournalRunsApi();
POSTJournalRunType request = new POSTJournalRunType(); // POSTJournalRunType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTJournalRunResponseType result = apiInstance.pOSTJournalRun(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling JournalRunsApi#pOSTJournalRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTJournalRunType**](POSTJournalRunType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTJournalRunResponseType**](POSTJournalRunResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTJournalRun"></a>
# **pUTJournalRun**
> CommonResponseType pUTJournalRun(jrNumber, zuoraEntityIds)
Cancel journal run
This reference describes how to cancel a journal run using the REST API. The summary journal entries in the journal run are canceled asynchronously. See the \"Example\" section below for details. You must have the \"Cancel Journal Run\" Zuora Finance user permission enabled to cancel journal runs. ## Notes When you cancel a journal run, the summary journal entries associated with that journal run are canceled asynchronously. A response of `{ \"success\": true }` means only that the specified journal run has a status of \"Pending\", \"Error\", or \"Completed\" and therefore can be canceled, but does not mean that the whole journal run was successfully canceled. For example, let's say you want to cancel journal run JR-00000075. The journal run status is \"Completed\" and it contains ten journal entries. One of the journal entries has its Transferred to Accounting status set to \"Yes\", meaning that the entry cannot be canceled. The workflow might go as follows: 1. You make an API call to cancel the journal run. 2. The journal run status is \"Completed\", so you receive a response of `{ \"success\": true }`. 3. Zuora begins asynchronously canceling journal entries associated with the journal run. The journal entry whose Transferred to Accounting status is \"Yes\" fails to be canceled. The cancelation process continues, and the other journal entries are successfully canceled. 4. The journal run status remains as \"Completed\". The status does not change to \"Canceled\" because the journal run still contains a journey entry that is not canceled.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.JournalRunsApi;
JournalRunsApi apiInstance = new JournalRunsApi();
String jrNumber = "jrNumber_example"; // String | Journal run number. Must be a valid journal run number in the format JR-00000001. You can only cancel a journal run whose status is \"Pending\", \"Error\", or \"Completed\".
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTJournalRun(jrNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling JournalRunsApi#pUTJournalRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**jrNumber** | **String**| Journal run number. Must be a valid journal run number in the format JR-00000001. You can only cancel a journal run whose status is \"Pending\", \"Error\", or \"Completed\". |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# ProxyGetPaymentMethodSnapshot
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | **String** | The ID of the customer account associated with this payment method. | [optional]
**achAbaCode** | **String** | The nine-digit routing number or ABA number used by banks. Applicable to ACH payment methods. | [optional]
**achAccountName** | **String** | The name of the account holder, which can be either a person or a company. Applicable to ACH payment methods. | [optional]
**achAccountNumberMask** | **String** | This is a masked displayable version of the ACH account number, used for security purposes. For example: `XXXXXXXXX54321`. | [optional]
**achAccountType** | [**AchAccountTypeEnum**](#AchAccountTypeEnum) | The type of bank account associated with the ACH payment. | [optional]
**achBankName** | **String** | The name of the bank where the ACH payment account is held. | [optional]
**bankBranchCode** | **String** | The branch code of the bank used for direct debit. | [optional]
**bankCheckDigit** | **String** | The check digit in the international bank account number, which confirms the validity of the account. Applicable to direct debit payment methods. | [optional]
**bankCity** | **String** | The city of the direct debit bank. | [optional]
**bankCode** | **String** | The sort code or number that identifies the bank. This is also known as the sort code. | [optional]
**bankIdentificationNumber** | **String** | The first six digits of the payment method's number, such as the credit card number or account number. Banks use this number to identify a payment method. | [optional]
**bankName** | **String** | The name of the direct debit bank. | [optional]
**bankPostalCode** | **String** | The zip code or postal code of the direct debit bank. | [optional]
**bankStreetName** | **String** | The name of the street of the direct debit bank. | [optional]
**bankStreetNumber** | **String** | The number of the direct debit bank. | [optional]
**bankTransferAccountName** | **String** | The name on the direct debit bank account. | [optional]
**bankTransferAccountNumberMask** | **String** | This is a masked displayable version of the bank account number, used for security purposes. For example: `XXXXXXXXX54321`. | [optional]
**bankTransferAccountType** | **String** | The type of the customer's bank account. Applicable to direct debit payment methods. | [optional]
**bankTransferType** | [**BankTransferTypeEnum**](#BankTransferTypeEnum) | Specifies the type of direct debit transfer. The value of this field is dependent on the country of the user. Possible Values: * `AutomatischIncasso` (NL) * `LastschriftDE` (Germany) * `LastschriftAT` (Austria) * `DemandeDePrelevement` (FR) * `DirectDebitUK` (UK) * `Domicil` (Belgium) * `LastschriftCH` (CH) * `RID` (Italy) * `OrdenDeDomiciliacion` (Spain) | [optional]
**businessIdentificationCode** | **String** | The business identification code for Swiss direct payment methods that use the Global Collect payment gateway. Only applicable to direct debit payments in Switzerland with Global Collect. | [optional]
**city** | **String** | The city of the customer's address. Applicable to debit payment methods. | [optional]
**country** | **String** | The two-letter country code of the customer's address. Applicable to direct debit payment methods. | [optional]
**creditCardAddress1** | **String** | The first line of the card holder's address, which is often a street address or business name. Applicable to credit card and direct debit payment methods. | [optional]
**creditCardAddress2** | **String** | The second line of the card holder's address. Applicable to credit card and direct debit payment methods. | [optional]
**creditCardCity** | **String** | The city of the card holder's address. Applicable to credit card and direct debit payment methods. | [optional]
**creditCardCountry** | **String** | The country of the card holder's address. | [optional]
**creditCardExpirationMonth** | **Integer** | The expiration month of the credit card or debit card. Applicable to credit card and direct debit payment methods. | [optional]
**creditCardExpirationYear** | **Integer** | The expiration month of the credit card or debit card. Applicable to credit card and direct debit payment methods. | [optional]
**creditCardHolderName** | **String** | The full name of the card holder. Applicable to credit card and direct debit payment methods. | [optional]
**creditCardMaskNumber** | **String** | A masked version of the credit or debit card number. | [optional]
**creditCardPostalCode** | **String** | The billing address's zip code. | [optional]
**creditCardState** | **String** | The billing address's state. Applicable if `CreditCardCountry` is either Canada or the US. | [optional]
**creditCardType** | [**CreditCardTypeEnum**](#CreditCardTypeEnum) | The type of credit card or debit card. | [optional]
**deviceSessionId** | **String** | The session ID of the user when the `PaymentMethod` was created or updated. | [optional]
**email** | **String** | An email address for the payment method in addition to the bill to contact email address. | [optional]
**existingMandate** | [**ExistingMandateEnum**](#ExistingMandateEnum) | Indicates if the customer has an existing mandate or a new mandate. Only applicable to direct debit payment methods. | [optional]
**firstName** | **String** | The customer's first name. Only applicable to direct debit payment methods. | [optional]
**IBAN** | **String** | The International Bank Account Number. Only applicable to direct debit payment methods. | [optional]
**ipAddress** | **String** | The IP address of the user when the payment method was created or updated. | [optional]
**id** | **String** | Object identifier. | [optional]
**lastFailedSaleTransactionDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date of the last failed attempt to collect payment with this payment method. | [optional]
**lastName** | **String** | The customer's last name. Only applicable to direct debit payment methods. | [optional]
**lastTransactionDateTime** | [**OffsetDateTime**](OffsetDateTime.md) | The date of the most recent transaction. | [optional]
**lastTransactionStatus** | **String** | The status of the most recent transaction. | [optional]
**mandateCreationDate** | [**LocalDate**](LocalDate.md) | The date when the mandate was created, in `yyyy-mm-dd` format. A mandate is a signed authorization for UK and NL customers. Only applicable to direct debit payment methods. | [optional]
**mandateID** | **String** | The ID of the mandate. A mandate is a signed authorization for UK and NL customers. Only applicable to direct debit payment methods. | [optional]
**mandateReceived** | **String** | Indicates if the mandate was received. A mandate is a signed authorization for UK and NL customers. Only applicable to direct debit payment methods. | [optional]
**mandateUpdateDate** | [**LocalDate**](LocalDate.md) | The date when the mandate was last updated, in `yyyy-mm-dd` format. A mandate is a signed authorization for UK and NL customers. Only applicable to direct debit payment methods. | [optional]
**maxConsecutivePaymentFailures** | **Integer** | The number of allowable consecutive failures Zuora attempts with the payment method before stopping. | [optional]
**name** | **String** | The name of the payment method. | [optional]
**numConsecutiveFailures** | **Integer** | The number of consecutive failed payment for the payment method. | [optional]
**paymentMethodId** | **String** | Object identifier of the payment method. | [optional]
**paymentMethodStatus** | [**PaymentMethodStatusEnum**](#PaymentMethodStatusEnum) | Specifies the status of the payment method. | [optional]
**paymentRetryWindow** | **Integer** | The retry interval setting, which prevents making a payment attempt if the last failed attempt was within the last specified number of hours. | [optional]
**paypalBaid** | **String** | The PayPal billing agreement ID, which is a contract between two PayPal accounts. | [optional]
**paypalEmail** | **String** | The email address associated with the account holder's PayPal account or of the PayPal account of the person paying for the service. | [optional]
**paypalPreapprovalKey** | **String** | PayPal's Adaptive Payments API key. | [optional]
**paypalType** | [**PaypalTypeEnum**](#PaypalTypeEnum) | Specifies the PayPal gateway: PayFlow Pro (Express Checkout) or Adaptive Payments. | [optional]
**phone** | **String** | The phone number that the account holder registered with the bank. This field is used for credit card validation when passing to a gateway. | [optional]
**postalCode** | **String** | The zip code of the customer's address. Only applicable to direct debit payment methods. | [optional]
**secondTokenId** | **String** | A gateway unique identifier that replaces sensitive payment method data. Applicable to CC Reference Transaction payment methods. | [optional]
**state** | **String** | The state of the customer's address. Only applicable to direct debit payment methods. | [optional]
**streetName** | **String** | The street name of the customer's address. Only applicable to direct debit payment methods. | [optional]
**streetNumber** | **String** | The street number of the customer's address. Only applicable to direct debit payment methods. | [optional]
**tokenId** | **String** | A gateway unique identifier that replaces sensitive payment method data or represents a gateway's unique customer profile. Applicable to CC Reference Transaction payment methods. | [optional]
**totalNumberOfErrorPayments** | **Integer** | The number of error payments that used this payment method. | [optional]
**totalNumberOfProcessedPayments** | **Integer** | The number of successful payments that used this payment method. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | The type of payment method. | [optional]
**useDefaultRetryRule** | **Boolean** | Determines whether to use the default retry rules configured in the Zuora Payments settings. | [optional]
<a name="AchAccountTypeEnum"></a>
## Enum: AchAccountTypeEnum
Name | Value
---- | -----
BUSINESSCHECKING | "BusinessChecking"
CHECKING | "Checking"
SAVING | "Saving"
<a name="BankTransferTypeEnum"></a>
## Enum: BankTransferTypeEnum
Name | Value
---- | -----
AUTOMATISCHINCASSO | "AutomatischIncasso"
LASTSCHRIFTDE | "LastschriftDE"
LASTSCHRIFTAT | "LastschriftAT"
DEMANDEDEPRELEVEMENT | "DemandeDePrelevement"
DIRECTDEBITUK | "DirectDebitUK"
DOMICIL | "Domicil"
LASTSCHRIFTCH | "LastschriftCH"
RID | "RID"
ORDENDEDOMICILIACION | "OrdenDeDomiciliacion"
<a name="CreditCardTypeEnum"></a>
## Enum: CreditCardTypeEnum
Name | Value
---- | -----
AMERICANEXPRESS | "AmericanExpress"
DISCOVER | "Discover"
MASTERCARD | "MasterCard"
VISA | "Visa"
<a name="ExistingMandateEnum"></a>
## Enum: ExistingMandateEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<a name="PaymentMethodStatusEnum"></a>
## Enum: PaymentMethodStatusEnum
Name | Value
---- | -----
ACTIVE | "Active"
CLOSED | "Closed"
<a name="PaypalTypeEnum"></a>
## Enum: PaypalTypeEnum
Name | Value
---- | -----
EXPRESSCHECKOUT | "ExpressCheckout"
ADAPTIVEPAYMENTS | "AdaptivePayments"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
ACH | "ACH"
APPLEPAY | "ApplePay"
BANKTRANSFER | "BankTransfer"
CASH | "Cash"
CHECK | "Check"
CREDITCARD | "CreditCard"
CREDITCARDREFERENCETRANSACTION | "CreditCardReferenceTransaction"
DEBITCARD | "DebitCard"
OTHER | "Other"
PAYPAL | "PayPal"
WIRETRANSFER | "WireTransfer"
<file_sep>
# PUTBatchDebitMemosRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**debitMemos** | [**List<BatchDebitMemoType>**](BatchDebitMemoType.md) | Container for debit memo update details. | [optional]
<file_sep>
# AmendmentRatePlanData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ratePlan** | [**RatePlan**](RatePlan.md) | |
**ratePlanChargeData** | [**List<RatePlanChargeDataInRatePlanData>**](RatePlanChargeDataInRatePlanData.md) | | [optional]
**subscriptionProductFeatureList** | [**SubscriptionProductFeatureList**](SubscriptionProductFeatureList.md) | | [optional]
<file_sep>
# PUTCreditMemoItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The amount of the credit memo item. For tax-inclusive credit memo items, the amount indicates the credit memo item amount including tax. For tax-exclusive credit memo items, the amount indicates the credit memo item amount excluding tax | [optional]
**comment** | **String** | Comments about the credit memo item. | [optional]
**financeInformation** | [**PUTCreditMemoItemTypeFinanceInformation**](PUTCreditMemoItemTypeFinanceInformation.md) | | [optional]
**id** | **String** | The ID of the credit memo item. |
**serviceEndDate** | [**LocalDate**](LocalDate.md) | The service end date of the credit memo item. | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | The service start date of the credit memo item. | [optional]
**skuName** | **String** | The name of the SKU. | [optional]
**taxItems** | [**List<PutCreditMemoTaxItemType>**](PutCreditMemoTaxItemType.md) | Container for credit memo taxation items. | [optional]
**unitOfMeasure** | **String** | The definable unit that you measure when determining charges. | [optional]
<file_sep># QuotesDocumentApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**pOSTQuotesDocument**](QuotesDocumentApi.md#pOSTQuotesDocument) | **POST** /v1/quotes/document | Generate quotes document
<a name="pOSTQuotesDocument"></a>
# **pOSTQuotesDocument**
> POSTQuoteDocResponseType pOSTQuotesDocument(request, zuoraEntityIds)
Generate quotes document
The `document` call generates a quote document and returns the generated document URL. You can directly access the generated quote file through the returned URL. The `document` call should be only used from Zuora Quotes. ## File Size Limitation The maximum export file size is 2047MB. If you have large data requests that go over this limit, you will get the following 403 HTTP response code from Zuora: `security:max-object-size>2047MB</security:max-object-size>` Submit a request at [Zuora Global Support](http://support.zuora.com/) if you require additional assistance. We can work with you to determine if large file optimization is an option for you.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.QuotesDocumentApi;
QuotesDocumentApi apiInstance = new QuotesDocumentApi();
POSTQuoteDocType request = new POSTQuoteDocType(); // POSTQuoteDocType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTQuoteDocResponseType result = apiInstance.pOSTQuotesDocument(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling QuotesDocumentApi#pOSTQuotesDocument");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTQuoteDocType**](POSTQuoteDocType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTQuoteDocResponseType**](POSTQuoteDocResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# TimeSlicedNetMetricsForEvergreen
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**discountChargeNumber** | **String** | | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | | [optional]
**invoiceOwner** | **String** | The acount number of the billing account that is billed for the subscription. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | | [optional]
**subscriptionOwner** | **String** | The acount number of the billing account that owns the subscription. | [optional]
**termNumber** | [**BigDecimal**](BigDecimal.md) | | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Indicates whether this metrics is for a regular charge or a discount. charge. | [optional]
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
REGULAR | "Regular"
DISCOUNT | "Discount"
<file_sep>
# SubscribeResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | **String** | | [optional]
**accountNumber** | **String** | | [optional]
**chargeMetricsData** | [**SubscribeResultChargeMetricsData**](SubscribeResultChargeMetricsData.md) | | [optional]
**errors** | [**List<ActionsErrorResponse>**](ActionsErrorResponse.md) | | [optional]
**gatewayResponse** | **String** | | [optional]
**gatewayResponseCode** | **String** | | [optional]
**invoiceData** | [**List<InvoiceData>**](InvoiceData.md) | | [optional]
**invoiceId** | **String** | | [optional]
**invoiceNumber** | **String** | | [optional]
**invoiceResult** | [**SubscribeResultInvoiceResult**](SubscribeResultInvoiceResult.md) | | [optional]
**paymentId** | **String** | | [optional]
**paymentTransactionNumber** | **String** | | [optional]
**subscriptionId** | **String** | | [optional]
**subscriptionNumber** | **String** | | [optional]
**success** | **Boolean** | | [optional]
**totalMrr** | **Double** | | [optional]
**totalTcv** | **Double** | | [optional]
<file_sep># EventTriggersApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEEventTrigger**](EventTriggersApi.md#dELETEEventTrigger) | **DELETE** /events/event-triggers/{id} | Remove an event trigger
[**gETEventTrigger**](EventTriggersApi.md#gETEventTrigger) | **GET** /events/event-triggers/{id} | Get an event trigger by ID
[**gETEventTriggers**](EventTriggersApi.md#gETEventTriggers) | **GET** /events/event-triggers | Query event triggers
[**pOSTEventTrigger**](EventTriggersApi.md#pOSTEventTrigger) | **POST** /events/event-triggers | Create an event trigger
[**pUTEventTrigger**](EventTriggersApi.md#pUTEventTrigger) | **PUT** /events/event-triggers/{id} | Update an event trigger
<a name="dELETEEventTrigger"></a>
# **dELETEEventTrigger**
> dELETEEventTrigger(authorization, id, zuoraEntityIds, zuoraTrackId)
Remove an event trigger
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EventTriggersApi;
EventTriggersApi apiInstance = new EventTriggersApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
apiInstance.dELETEEventTrigger(authorization, id, zuoraEntityIds, zuoraTrackId);
} catch (ApiException e) {
System.err.println("Exception when calling EventTriggersApi#dELETEEventTrigger");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETEventTrigger"></a>
# **gETEventTrigger**
> EventTrigger gETEventTrigger(authorization, id, zuoraEntityIds, zuoraTrackId)
Get an event trigger by ID
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EventTriggersApi;
EventTriggersApi apiInstance = new EventTriggersApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
EventTrigger result = apiInstance.gETEventTrigger(authorization, id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EventTriggersApi#gETEventTrigger");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**EventTrigger**](EventTrigger.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETEventTriggers"></a>
# **gETEventTriggers**
> InlineResponse2001 gETEventTriggers(authorization, zuoraEntityIds, zuoraTrackId, baseObject, eventTypeName, active, start, limit)
Query event triggers
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EventTriggersApi;
EventTriggersApi apiInstance = new EventTriggersApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String baseObject = "baseObject_example"; // String | The Zuora object that trigger condition is defined upon. Should be specified in the pattern: ^[A-Z][\\\\w\\\\-]*$
String eventTypeName = "eventTypeName_example"; // String | The event type name. Should be specified in the pattern: ^[A-Za-z]{1,}[\\w\\-]*$
String active = "active_example"; // String | The status of the event trigger.
Integer start = 0; // Integer | The first index of the query result. Default to 0 if absent, and the minimum is 0.
Integer limit = 10; // Integer | The maximum number of data records to be returned. Default to 10 if absent.
try {
InlineResponse2001 result = apiInstance.gETEventTriggers(authorization, zuoraEntityIds, zuoraTrackId, baseObject, eventTypeName, active, start, limit);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EventTriggersApi#gETEventTriggers");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**baseObject** | **String**| The Zuora object that trigger condition is defined upon. Should be specified in the pattern: ^[A-Z][\\\\w\\\\-]*$ | [optional]
**eventTypeName** | **String**| The event type name. Should be specified in the pattern: ^[A-Za-z]{1,}[\\w\\-]*$ | [optional]
**active** | **String**| The status of the event trigger. | [optional]
**start** | **Integer**| The first index of the query result. Default to 0 if absent, and the minimum is 0. | [optional] [default to 0]
**limit** | **Integer**| The maximum number of data records to be returned. Default to 10 if absent. | [optional] [default to 10]
### Return type
[**InlineResponse2001**](InlineResponse2001.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTEventTrigger"></a>
# **pOSTEventTrigger**
> EventTrigger pOSTEventTrigger(authorization, postEventTriggerRequest, zuoraEntityIds, zuoraTrackId)
Create an event trigger
You can define an event trigger on any of the following objects: * Account * AccountingCode * AccountingPeriod * Amendment * BillingRun * Contact * CreditBalanceAdjustment * CreditMemo * CreditMemoApplication * CreditMemoApplicationItem * CreditMemoItem * DebitMemo * DebitMemoItem * Feature * Invoice * InvoiceAdjustment * InvoiceItem * InvoiceItemAdjustment * JournalEntry * JournalEntryItem * Order * OrderAction * Payment * PaymentApplication * PaymentMethod * PaymentPart * Product * ProductFeature * ProductRatePlan * ProductRatePlanCharge * RatePlan * RatePlanCharge * Refund * RefundApplication * RevenueEvent * RevenueEventItem * RevenueSchedule * RevenueScheduleItem * Subscription * SubscriptionProductFeature * TaxationItem * Usage The `baseObject` field specifies which object to define a trigger on. The `condition` field is a [JEXL](http://commons.apache.org/proper/commons-jexl/) expression that specifies when to trigger events. The expression can contain fields from the object that the trigger is defined on. **Note:** The condition cannot contain fields from [data source](https://knowledgecenter.zuora.com/DC_Developers/M_Export_ZOQL) objects that are joined to the object that the trigger is defined on. For example, the following condition causes an event to be triggered whenever an invoice is posted with an amount greater than 1000: ```changeType == 'UPDATE' && Invoice.Status == 'Posted' && Invoice.Status_old != 'Posted' && Invoice.Amount > 1000``` Where: * `changeType` is a keyword that specifies the type of change that occurred to the Invoice object. For all objects, the supported values of `changeType` are `INSERT`, `UPDATE`, and `DELETE`. * `Invoice.Status` is the value of the Invoice object's `Status` field after the change occurred. * `Invoice.Status_old` is the value of the Invoice object's `Status` field before the change occurred. In the above example, the value of `baseObject` would be `Invoice`. **Note:** The number of the event triggers that you can create depends on the [edition of Zuora Central Platform](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/C_Zuora_Editions) you are using.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EventTriggersApi;
EventTriggersApi apiInstance = new EventTriggersApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
PostEventTriggerRequest postEventTriggerRequest = new PostEventTriggerRequest(); // PostEventTriggerRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
EventTrigger result = apiInstance.pOSTEventTrigger(authorization, postEventTriggerRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EventTriggersApi#pOSTEventTrigger");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**postEventTriggerRequest** | [**PostEventTriggerRequest**](PostEventTriggerRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**EventTrigger**](EventTrigger.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTEventTrigger"></a>
# **pUTEventTrigger**
> EventTrigger pUTEventTrigger(authorization, id, putEventTriggerRequest, zuoraEntityIds, zuoraTrackId)
Update an event trigger
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.EventTriggersApi;
EventTriggersApi apiInstance = new EventTriggersApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID |
PutEventTriggerRequest putEventTriggerRequest = new PutEventTriggerRequest(); // PutEventTriggerRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
EventTrigger result = apiInstance.pUTEventTrigger(authorization, id, putEventTriggerRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EventTriggersApi#pUTEventTrigger");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| |
**putEventTriggerRequest** | [**PutEventTriggerRequest**](PutEventTriggerRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**EventTrigger**](EventTrigger.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# POSTPaymentRunRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | [**UUID**](UUID.md) | The ID of the customer account associated with the payment run. This field conflicts with each of the `batch`, `billCycleDay`, `currency`, `paymentGatewayId`, and `billingRunId` fields. If there are such conflicts, an error occurs and an error message is returned. | [optional]
**applyCreditBalance** | **Boolean** | **Note:** This field is only available if you have the Credit Balance feature enabled and the Invoice Settlement feature disabled. Whether to apply credit balances in the payment run. This field is only available when you have Invoice Settlement feature disabled. | [optional]
**autoApplyCreditMemo** | **Boolean** | **Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Whether to automatically apply a posted credit memo to one or more receivables in the payment run. | [optional]
**autoApplyUnappliedPayment** | **Boolean** | **Note:** The Invoice Settlement feature is in **Limited Availability**. This feature includes Unapplied Payments, Credit and Debit Memo, and Invoice Item Settlement. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Whether to automatically apply unapplied payments to one or more receivables in the payment run. | [optional]
**batch** | **String** | The alias name given to a batch. The batch name is a string of 50 characters or less. This field conflicts with the `accountId` field. If they are both specified in the request body, an error occurs and an error message is returned. | [optional]
**billCycleDay** | **Integer** | The billing cycle day (BCD), the day of the month when a bill run generates invoices for the account. The value must be equal to or less then 31, and 31 is mean the EOM. This field conflicts with the `accountId` field. If they are both specified in the request body, an error occurs and an error message is returned. | [optional]
**billingRunId** | [**UUID**](UUID.md) | The ID of a bill run. This field conflicts with the `accountId` field. If they are both specified in the request body, an error occurs and an error message is returned. | [optional]
**collectPayment** | **Boolean** | Whether to process electronic payments during the execution of payment runs. If the Payment user permission \"Process Electronic Payment\" is disabled, this field will be ignored. | [optional]
**consolidatedPayment** | **Boolean** | **Note:** The **Process Electronic Payment** permission also needs to be allowed for a Manage Payment Runs role to work. See [Payments Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/e_Payments_Roles) for more information. Whether to process a single payment for all receivables that are due on an account. | [optional]
**currency** | **String** | A currency defined in the web-based UI administrative settings. This field conflicts with the `accountId` field. If they are both specified in the request body, an error occurs and an error message is returned. | [optional]
**paymentGatewayId** | [**UUID**](UUID.md) | The ID of the gateway instance that processes the payment. This field conflicts with the `accountId` field. If they are both specified in the request body, an error occurs and an error message is returned. | [optional]
**processPaymentWithClosedPM** | **Boolean** | **Note:** The **Process Electronic Payment** permission also needs to be allowed for a Manage Payment Runs role to work. See [Payments Roles](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/A_Administrator_Settings/User_Roles/e_Payments_Roles) for more information. Whether to process payments even if the default payment method is closed. | [optional]
**runDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the scheduled payment run is to be executed, in `yyyy-mm-dd hh:mm:ss` format. The backend will ignore mintues and seconds in the field value. For example, if you specify `2017-03-01 11:30:37` for this value, this payment run will be run at 2017-03-01 11:00:00. You must specify either the `runDate` field or the `targetDate` field in the request body. If you specify the `runDate` field, the scheduced payment run is to be executed on the run date. If you specify the `targetDate` field, the payment run is executed immediately after it is created. | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | The target date used to determine which receivables to be paid in the payment run. The payments are collected for all receivables with the due date no later than the target date. You must specify either the `runDate` field or the `targetDate` field in the request body. If you specify the `runDate` field, the scheduced payment run is to be executed on the run date. If you specify the `targetDate` field, the payment run is executed immediately after it is created. | [optional]
<file_sep>
# GETJournalRunTransactionType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**type** | [**TypeEnum**](#TypeEnum) | Transaction type. Invoice Adjustment is deprecated on Production. Zuora recommends that you use the Invoice Item Adjustment instead. If you enable the Invoice Settlement feature, Debit Memo Item, Credit Memo Item, and Credit Memo Application Item are available, Payment and Refund will be replaced by Payment Application and Refund Application. If you enable both the Invoice Settlement feature and the Invoice Item Settlement feature, Payment and Refund will be replaced by Payment Application Item and Refund Application Item. | [optional]
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
INVOICE_ITEM | "Invoice Item"
TAXATION_ITEM | "Taxation Item"
INVOICE_ITEM_ADJUSTMENT_INVOICE_ | "Invoice Item Adjustment (Invoice)"
INVOICE_ITEM_ADJUSTMENT_TAX_ | "Invoice Item Adjustment (tax)"
INVOICE_ADJUSTMENT | "Invoice Adjustment"
ELECTRONIC_PAYMENT | "Electronic Payment"
EXTERNAL_PAYMENT | "External Payment"
ELECTRONIC_REFUND | "Electronic Refund"
EXTERNAL_REFUND | "External Refund"
ELECTRONIC_CREDIT_BALANCE_PAYMENT | "Electronic Credit Balance Payment"
EXTERNAL_CREDIT_BALANCE_PAYMENT | "External Credit Balance Payment"
ELECTRONIC_CREDIT_BALANCE_REFUND | "Electronic Credit Balance Refund"
EXTERNAL_CREDIT_BALANCE_REFUND | "External Credit Balance Refund"
CREDIT_BALANCE_ADJUSTMENT_APPLIED_FROM_CREDIT_BALANCE_ | "Credit Balance Adjustment (Applied from Credit Balance)"
CREDIT_BALANCE_ADJUSTMENT_TRANSFERRED_TO_CREDIT_BALANCE_ | "Credit Balance Adjustment (Transferred to Credit Balance)"
REVENUE_EVENT_ITEM | "Revenue Event Item"
DEBIT_MEMO_ITEM_CHARGE_ | "Debit Memo Item (Charge)"
DEBIT_MEMO_ITEM_TAX_ | "Debit Memo Item (tax)"
CREDIT_MEMO_ITEM_CHARGE_ | "Credit Memo Item (Charge)"
CREDIT_MEMO_ITEM_TAX_ | "Credit Memo Item (tax)"
CREDIT_MEMO_APPLICATION_ITEM | "Credit Memo Application Item"
ELECTRONIC_PAYMENT_APPLICATION | "Electronic Payment Application"
EXTERNAL_PAYMENT_APPLICATION | "External Payment Application"
ELECTRONIC_REFUND_APPLICATION | "Electronic Refund Application"
EXTERNAL_REFUND_APPLICATION | "External Refund Application"
ELECTRONIC_PAYMENT_APPLICATION_ITEM | "Electronic Payment Application Item"
EXTERNAL_PAYMENT_APPLICATION_ITEM | "External Payment Application Item"
ELECTRONIC_REFUND_APPLICATION_ITEM | "Electronic Refund Application Item"
EXTERNAL_REFUND_APPLICATION_ITEM | "External Refund Application Item"
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.GETInvoiceFileWrapper;
import de.keylight.zuora.client.model.GETPaymentsType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.TransactionsApi")
public class TransactionsApi {
private ApiClient apiClient;
public TransactionsApi() {
this(new ApiClient());
}
@Autowired
public TransactionsApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Get invoices
* Retrieves invoices for a specified account. Invoices are returned in reverse chronological order by **updatedDate**.
* <p><b>200</b> -
* @param accountKey Account number or account ID.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param pageSize Number of rows returned per page.
* @return GETInvoiceFileWrapper
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GETInvoiceFileWrapper gETTransactionInvoice(String accountKey, String zuoraEntityIds, Integer pageSize) throws RestClientException {
Object postBody = null;
// verify the required parameter 'accountKey' is set
if (accountKey == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'accountKey' when calling gETTransactionInvoice");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("account-key", accountKey);
String path = UriComponentsBuilder.fromPath("/v1/transactions/invoices/accounts/{account-key}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "pageSize", pageSize));
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GETInvoiceFileWrapper> returnType = new ParameterizedTypeReference<GETInvoiceFileWrapper>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Get payments
* Retrieves payments for a specified account. Payments are returned in reverse chronological order by **updatedDate**.
* <p><b>200</b> -
* @param accountKey Account number or account ID.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param pageSize Number of rows returned per page.
* @return GETPaymentsType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GETPaymentsType gETTransactionPayment(String accountKey, String zuoraEntityIds, Integer pageSize) throws RestClientException {
Object postBody = null;
// verify the required parameter 'accountKey' is set
if (accountKey == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'accountKey' when calling gETTransactionPayment");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("account-key", accountKey);
String path = UriComponentsBuilder.fromPath("/v1/transactions/payments/accounts/{account-key}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "pageSize", pageSize));
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GETPaymentsType> returnType = new ParameterizedTypeReference<GETPaymentsType>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep>
# UpdatePaymentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the payment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the payment was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**comment** | **String** | Comments about the payment. | [optional]
**financeInformation** | [**CreatePaymentTypeFinanceInformation**](CreatePaymentTypeFinanceInformation.md) | | [optional]
<file_sep>
# InlineResponse2001
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**data** | [**List<EventTrigger>**](EventTrigger.md) | | [optional]
**next** | **String** | The link to the next page. No value if it is last page. | [optional]
<file_sep>
# GetInvoiceAmountBreakdownByOrderResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**breakdowns** | [**List<InvoiceItemBreakdown>**](InvoiceItemBreakdown.md) | Invoice breakdown details. | [optional]
**currency** | **String** | Currency code. | [optional]
<file_sep>
# ChargePreviewMetricsTcb
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**discount** | [**BigDecimal**](BigDecimal.md) | Total contract billing amount of all discount charges which are applied to one specific recurring charge. This value is calculated from the rating results for the latest subscription version in the order. | [optional]
**discountDelta** | [**BigDecimal**](BigDecimal.md) | Delta discount TCB value between the base and the latest subscription version for specific recurring charge in the order. | [optional]
**regular** | [**BigDecimal**](BigDecimal.md) | | [optional]
**regularDelta** | [**BigDecimal**](BigDecimal.md) | Delta TCB value between the base and the latest subscription version in the order. | [optional]
<file_sep># BillingPreviewRunApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETBillingPreviewRun**](BillingPreviewRunApi.md#gETBillingPreviewRun) | **GET** /v1/billing-preview-runs/{billingPreviewRunId} | Get Billing Preview Run
[**pOSTBillingPreviewRun**](BillingPreviewRunApi.md#pOSTBillingPreviewRun) | **POST** /v1/billing-preview-runs | Create Billing Preview Run
<a name="gETBillingPreviewRun"></a>
# **gETBillingPreviewRun**
> GetBillingPreviewRunResponse gETBillingPreviewRun(billingPreviewRunId, zuoraEntityIds)
Get Billing Preview Run
**Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves a preview of future invoice items for multiple customer accounts through a billing preview run. If you have the Invoice Settlement feature enabled, you can also retrieve a preview of future credit memo items. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). A billing preview run asynchronously generates a downloadable CSV file containing a preview of invoice item data and credit memo item data for a batch of customer accounts.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillingPreviewRunApi;
BillingPreviewRunApi apiInstance = new BillingPreviewRunApi();
String billingPreviewRunId = "billingPreviewRunId_example"; // String | Id of the billing preview run.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GetBillingPreviewRunResponse result = apiInstance.gETBillingPreviewRun(billingPreviewRunId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillingPreviewRunApi#gETBillingPreviewRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**billingPreviewRunId** | **String**| Id of the billing preview run. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GetBillingPreviewRunResponse**](GetBillingPreviewRunResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTBillingPreviewRun"></a>
# **pOSTBillingPreviewRun**
> InlineResponse200 pOSTBillingPreviewRun(request, zuoraEntityIds)
Create Billing Preview Run
**Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates billing preview runs for multiple customer accounts. You can run up to 10 billing previews in batches concurrently. A single batch of customer accounts can only have one billing preview run at a time. So you can have up to 10 batches running at the same time. If you create a billing preview run for all customer batches, you cannot create another billing preview run until this preview run is completed.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillingPreviewRunApi;
BillingPreviewRunApi apiInstance = new BillingPreviewRunApi();
PostBillingPreviewRunParam request = new PostBillingPreviewRunParam(); // PostBillingPreviewRunParam |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
InlineResponse200 result = apiInstance.pOSTBillingPreviewRun(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillingPreviewRunApi#pOSTBillingPreviewRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**PostBillingPreviewRunParam**](PostBillingPreviewRunParam.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**InlineResponse200**](InlineResponse200.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# PutDebitMemoTaxItemTypeFinanceInformation
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**salesTaxPayableAccountingCode** | **String** | The accounting code for the sales taxes payable. | [optional]
<file_sep>
# PUTOrderActionTriggerDatesRequestTypeCharges
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeNumber** | **String** | Charge number of the charge which needs the triggering date to be provided. The charge's `triggerEvent` must have been set as `SpecificDate`. | [optional]
**specificTriggerDate** | [**LocalDate**](LocalDate.md) | Date in YYYY-MM-DD format. The specific trigger date you are to set for the charge. | [optional]
<file_sep>
# ProxyActionamendResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**results** | [**List<AmendResult>**](AmendResult.md) | | [optional]
<file_sep>
# PUTOrderActionTriggerDatesRequestTypeSubscriptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**orderActions** | [**List<PUTOrderActionTriggerDatesRequestTypeOrderActions>**](PUTOrderActionTriggerDatesRequestTypeOrderActions.md) | | [optional]
**subscriptionNumber** | **String** | Subscription number of a `Pending Activation` or `Pending Acceptance` subscription in the `Pending` order for which you are to update the triggering dates. For example, A-S00000001. |
<file_sep>
# GETDMTaxItemType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**appliedAmount** | **Double** | The applied amount of the debit memo taxation item. | [optional]
**creditAmount** | **Double** | The amount of credit memos applied to the debit memo. | [optional]
**exemptAmount** | **Double** | The amount of taxes or VAT for which the customer has an exemption. | [optional]
**financeInformation** | [**GETDMTaxItemTypeFinanceInformation**](GETDMTaxItemTypeFinanceInformation.md) | | [optional]
**id** | **String** | The ID of the debit memo taxation item. | [optional]
**jurisdiction** | **String** | The jurisdiction that applies the tax or VAT. This value is typically a state, province, county, or city. | [optional]
**locationCode** | **String** | The identifier for the location based on the value of the `taxCode` field. | [optional]
**name** | **String** | The name of the debit memo taxation item. | [optional]
**paymentAmount** | **Double** | The amount of payments applied to the debit memo. | [optional]
**refundAmount** | **Double** | The amount of the refund on the debit memo taxation item. | [optional]
**sourceTaxItemId** | **String** | The ID of the source taxation item. | [optional]
**taxAmount** | **Double** | The amount of taxation. | [optional]
**taxCode** | **String** | The tax code identifies which tax rules and tax rates to apply to a specific debit memo. | [optional]
**taxCodeDescription** | **String** | The description of the tax code. | [optional]
**taxDate** | [**LocalDate**](LocalDate.md) | The date that the tax is applied to the debit memo, in `yyyy-mm-dd` format. | [optional]
**taxRate** | **Double** | The tax rate applied to the debit memo. | [optional]
**taxRateDescription** | **String** | The description of the tax rate. | [optional]
**taxRateType** | [**TaxRateTypeEnum**](#TaxRateTypeEnum) | The type of the tax rate. | [optional]
**unappliedAmount** | **Double** | The unapplied amount of the debit memo taxation item. | [optional]
<a name="TaxRateTypeEnum"></a>
## Enum: TaxRateTypeEnum
Name | Value
---- | -----
PERCENTAGE | "Percentage"
FLATFEE | "FlatFee"
<file_sep># PaymentRunsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEPaymentRun**](PaymentRunsApi.md#dELETEPaymentRun) | **DELETE** /v1/payment-runs/{paymentRunId} | Delete payment run
[**gETPaymentRun**](PaymentRunsApi.md#gETPaymentRun) | **GET** /v1/payment-runs/{paymentRunId} | Get payment run
[**gETPaymentRunSummary**](PaymentRunsApi.md#gETPaymentRunSummary) | **GET** /v1/payment-runs/{paymentRunId}/summary | Get payment run summary
[**gETPaymentRuns**](PaymentRunsApi.md#gETPaymentRuns) | **GET** /v1/payment-runs | Get payment runs
[**pOSTPaymentRun**](PaymentRunsApi.md#pOSTPaymentRun) | **POST** /v1/payment-runs | Create payment run
[**pUTPaymentRun**](PaymentRunsApi.md#pUTPaymentRun) | **PUT** /v1/payment-runs/{paymentRunId} | Update payment run
<a name="dELETEPaymentRun"></a>
# **dELETEPaymentRun**
> CommonResponseType dELETEPaymentRun(paymentRunId)
Delete payment run
Deletes a payment run. Only payment runs with the Canceled or Error status can be deleted.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentRunsApi;
PaymentRunsApi apiInstance = new PaymentRunsApi();
UUID paymentRunId = new UUID(); // UUID | The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566.
try {
CommonResponseType result = apiInstance.dELETEPaymentRun(paymentRunId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentRunsApi#dELETEPaymentRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentRunId** | [**UUID**](.md)| The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566. |
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json
<a name="gETPaymentRun"></a>
# **gETPaymentRun**
> GETPaymentRunType gETPaymentRun(paymentRunId, zuoraEntityIds)
Get payment run
Retrives the information about a specific payment run.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentRunsApi;
PaymentRunsApi apiInstance = new PaymentRunsApi();
UUID paymentRunId = new UUID(); // UUID | The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPaymentRunType result = apiInstance.gETPaymentRun(paymentRunId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentRunsApi#gETPaymentRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentRunId** | [**UUID**](.md)| The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPaymentRunType**](GETPaymentRunType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json
<a name="gETPaymentRunSummary"></a>
# **gETPaymentRunSummary**
> GETPaymentRunSummaryResponse gETPaymentRunSummary(paymentRunId)
Get payment run summary
Retrives the summary of a payment run.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentRunsApi;
PaymentRunsApi apiInstance = new PaymentRunsApi();
UUID paymentRunId = new UUID(); // UUID | The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566.
try {
GETPaymentRunSummaryResponse result = apiInstance.gETPaymentRunSummary(paymentRunId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentRunsApi#gETPaymentRunSummary");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentRunId** | [**UUID**](.md)| The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566. |
### Return type
[**GETPaymentRunSummaryResponse**](GETPaymentRunSummaryResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json
<a name="gETPaymentRuns"></a>
# **gETPaymentRuns**
> GETPaymentRunCollectionType gETPaymentRuns(zuoraEntityIds, pageSize, createdById, createdDate, status, targetDate, updatedById, updatedDate, sort)
Get payment runs
Retrieves the information about all payment runs. You can define filterable fields to restrict the data returned in the response. ### Filtering You can use query parameters to restrict the data returned in the response. Each query parameter corresponds to one field in the response body. If the value of a filterable field is string, you can set the corresponding query parameter to `null` when filtering. Then, you can get the response data with this field value being `null`. Examples: - /v1/payment-runs?status=Processed - /v1/payment-runs?targetDate=2017-10-10&status=Pending - /v1/payment-runs?status=Completed&sort=+updatedDate
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentRunsApi;
PaymentRunsApi apiInstance = new PaymentRunsApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
String createdById = "createdById_example"; // String | This parameter filters the response based on the `createdById` field.
OffsetDateTime createdDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `createdDate` field.
String status = "status_example"; // String | This parameter filters the response based on the `status` field.
LocalDate targetDate = new LocalDate(); // LocalDate | This parameter filters the response based on the `targetDate` field.
String updatedById = "updatedById_example"; // String | This parameter filters the response based on the `updatedById` field.
OffsetDateTime updatedDate = new OffsetDateTime(); // OffsetDateTime | This parameter filters the response based on the `updatedDate` field.
String sort = "sort_example"; // String | This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by payment run number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - targetDate - status - createdDate - createdById - updatedDate - updatedById Examples: - /v1/payment-runs?sort=+createdDate - /v1/payment-runs?status=Processing&sort=-createdById,+targetDate
try {
GETPaymentRunCollectionType result = apiInstance.gETPaymentRuns(zuoraEntityIds, pageSize, createdById, createdDate, status, targetDate, updatedById, updatedDate, sort);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentRunsApi#gETPaymentRuns");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**createdById** | **String**| This parameter filters the response based on the `createdById` field. | [optional]
**createdDate** | **OffsetDateTime**| This parameter filters the response based on the `createdDate` field. | [optional]
**status** | **String**| This parameter filters the response based on the `status` field. | [optional] [enum: Pending, Processing, Completed, Error, Canceled]
**targetDate** | **LocalDate**| This parameter filters the response based on the `targetDate` field. | [optional]
**updatedById** | **String**| This parameter filters the response based on the `updatedById` field. | [optional]
**updatedDate** | **OffsetDateTime**| This parameter filters the response based on the `updatedDate` field. | [optional]
**sort** | **String**| This parameter restricts the order of the data returned in the response. You can use this parameter to supply a dimension you want to sort on. A sortable field uses the following form: *operator* *field_name* You can use at most two sortable fields in one URL path. Use a comma to separate sortable fields. For example: *operator* *field_name*, *operator* *field_name* *operator* is used to mark the order of sequencing. The operator is optional. If you only specify the sortable field without any operator, the response data is sorted in descending order by this field. - The `-` operator indicates an ascending order. - The `+` operator indicates a descending order. By default, the response data is displayed in descending order by payment run number. *field_name* indicates the name of a sortable field. The supported sortable fields of this operation are as below: - targetDate - status - createdDate - createdById - updatedDate - updatedById Examples: - /v1/payment-runs?sort=+createdDate - /v1/payment-runs?status=Processing&sort=-createdById,+targetDate | [optional]
### Return type
[**GETPaymentRunCollectionType**](GETPaymentRunCollectionType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json
<a name="pOSTPaymentRun"></a>
# **pOSTPaymentRun**
> GETPaymentRunType pOSTPaymentRun(body, zuoraEntityIds)
Create payment run
Creates a payment run. You can create a payment run to be executed immediately after it is created, or a scheduced payment run to be executed in future. The `accountId`, `batch`, `billCycleDay`, `currency`, `paymentGatewayId`, and `billingRunId` fields are used to determine which receivables to be paid in the payment run. If none of these fields is specified in the request body, the corresponding payment run collects payments for all accounts.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentRunsApi;
PaymentRunsApi apiInstance = new PaymentRunsApi();
POSTPaymentRunRequest body = new POSTPaymentRunRequest(); // POSTPaymentRunRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPaymentRunType result = apiInstance.pOSTPaymentRun(body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentRunsApi#pOSTPaymentRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**POSTPaymentRunRequest**](POSTPaymentRunRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPaymentRunType**](GETPaymentRunType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTPaymentRun"></a>
# **pUTPaymentRun**
> GETPaymentRunType pUTPaymentRun(paymentRunId, body, zuoraEntityIds)
Update payment run
Updates the information about an unexecuted payment run. Only pending payment runs can be updated. If none of the **accountId**, **batch**, **billCycleDay**, **currency**, **paymentGatewayId**, and **billingRunId** fields is specified in the request body, the corresponding payment run collects payments for all accounts.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentRunsApi;
PaymentRunsApi apiInstance = new PaymentRunsApi();
UUID paymentRunId = new UUID(); // UUID | The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566.
PUTPaymentRunRequest body = new PUTPaymentRunRequest(); // PUTPaymentRunRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPaymentRunType result = apiInstance.pUTPaymentRun(paymentRunId, body, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentRunsApi#pUTPaymentRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentRunId** | [**UUID**](.md)| The unique ID of a payment run. For example, 402890245f097f39015f0f074a2e0566. |
**body** | [**PUTPaymentRunRequest**](PUTPaymentRunRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPaymentRunType**](GETPaymentRunType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# GETProductRatePlanType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**billingPeriodNS** | [**BillingPeriodNSEnum**](#BillingPeriodNSEnum) | Billing period associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**classNS** | **String** | Class associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**departmentNS** | **String** | Department associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**includeChildrenNS** | [**IncludeChildrenNSEnum**](#IncludeChildrenNSEnum) | Specifies whether the corresponding item in NetSuite is visible under child subsidiaries. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the product rate plan's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**itemTypeNS** | [**ItemTypeNSEnum**](#ItemTypeNSEnum) | Type of item that is created in NetSuite for the product rate plan. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**locationNS** | **String** | Location associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**multiCurrencyPriceNS** | **String** | Multi-currency price associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**priceNS** | **String** | Price associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**subsidiaryNS** | **String** | Subsidiary associated with the corresponding item in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the product rate plan was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**description** | **String** | Rate plan description. | [optional]
**effectiveEndDate** | [**LocalDate**](LocalDate.md) | Final date the rate plan is active, as `yyyy-mm-dd`. After this date, the rate plan status is `Expired`. | [optional]
**effectiveStartDate** | [**LocalDate**](LocalDate.md) | First date the rate plan is active (i.e., available to be subscribed to), as `yyyy-mm-dd`. Before this date, the status is `NotStarted`. | [optional]
**id** | **String** | Unique product rate-plan charge ID. | [optional]
**name** | **String** | Name of the product rate-plan charge. (Not required to be unique.) | [optional]
**productRatePlanCharges** | [**List<GETProductRatePlanChargeType>**](GETProductRatePlanChargeType.md) | Field attributes describing the product rate plan charges: | [optional]
**status** | **String** | Possible vales are: `Active`, `Expired`, `NotStarted`. | [optional]
<a name="BillingPeriodNSEnum"></a>
## Enum: BillingPeriodNSEnum
Name | Value
---- | -----
MONTHLY | "Monthly"
QUARTERLY | "Quarterly"
ANNUAL | "Annual"
SEMI_ANNUAL | "Semi-Annual"
<a name="IncludeChildrenNSEnum"></a>
## Enum: IncludeChildrenNSEnum
Name | Value
---- | -----
YES | "Yes"
NO | "No"
<a name="ItemTypeNSEnum"></a>
## Enum: ItemTypeNSEnum
Name | Value
---- | -----
INVENTORY | "Inventory"
NON_INVENTORY | "Non Inventory"
SERVICE | "Service"
<file_sep>
# SubscribeRequestSubscribeOptionsExternalPaymentOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | | [optional]
**gatewayOrderId** | **String** | | [optional]
**paymentMethodId** | **String** | | [optional]
**referenceId** | **String** | | [optional]
<file_sep>
# GETRefundPaymentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the refund's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the refund was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**synctoNetSuiteNS** | **String** | Specifies whether the refund should be synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The ID of the account associated with this refund. Zuora associates the refund automatically with the account from the associated payment. | [optional]
**amount** | **Double** | The total amount of the refund. | [optional]
**cancelledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the refund was cancelled, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**comment** | **String** | Comments about the refund. | [optional]
**createdById** | **String** | The ID of the Zuora user who created the refund. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the refund was created, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 15:31:10. | [optional]
**creditMemoId** | **String** | The ID of the credit memo associated with the refund. | [optional]
**financeInformation** | [**GETRefundCreditMemoTypeFinanceInformation**](GETRefundCreditMemoTypeFinanceInformation.md) | | [optional]
**gatewayId** | **String** | The ID of the gateway instance that processes the refund. | [optional]
**gatewayResponse** | **String** | The message returned from the payment gateway for the refund. This message is gateway-dependent. | [optional]
**gatewayResponseCode** | **String** | The code returned from the payment gateway for the refund. This code is gateway-dependent. | [optional]
**gatewayState** | [**GatewayStateEnum**](#GatewayStateEnum) | The status of the refund in the gateway. | [optional]
**id** | **String** | The ID of the created refund. | [optional]
**markedForSubmissionOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when a refund was marked and waiting for batch submission to the payment process, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**methodType** | [**MethodTypeEnum**](#MethodTypeEnum) | How an external refund was issued to a customer. | [optional]
**number** | **String** | The unique identification number of the refund. | [optional]
**paymentId** | **String** | The ID of the payment that is refunded. | [optional]
**paymentMethodId** | **String** | The unique ID of the payment method that the customer used to make the refund. | [optional]
**paymentMethodSnapshotId** | **String** | The unique ID of the payment method snapshot, which is a copy of the particular payment method used in a transaction. | [optional]
**reasonCode** | **String** | A code identifying the reason for the transaction. | [optional]
**referenceId** | **String** | The transaction ID returned by the payment gateway for an electronic refund. Use this field to reconcile refunds between your gateway and Zuora Payments. | [optional]
**refundDate** | [**LocalDate**](LocalDate.md) | The date when the refund takes effect, in `yyyy-mm-dd` format. | [optional]
**refundTransactionTime** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the refund was issued, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**secondRefundReferenceId** | **String** | The transaction ID returned by the payment gateway if there is an additional transaction for the refund. Use this field to reconcile payments between your gateway and Zuora Payments. | [optional]
**settledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the refund was settled in the payment processor, in `yyyy-mm-dd hh:mm:ss` format. This field is used by the Spectrum gateway only and not applicable to other gateways. | [optional]
**softDescriptor** | **String** | A payment gateway-specific field that maps to Zuora for the gateways, Orbital, Vantiv and Verifi. | [optional]
**softDescriptorPhone** | **String** | A payment gateway-specific field that maps to Zuora for the gateways, Orbital, Vantiv and Verifi. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the refund. | [optional]
**submittedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the refund was submitted, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | The type of the refund. | [optional]
**updatedById** | **String** | The ID of the the Zuora user who last updated the refund. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the refund was last updated, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-02 15:36:10. | [optional]
<a name="GatewayStateEnum"></a>
## Enum: GatewayStateEnum
Name | Value
---- | -----
MARKEDFORSUBMISSION | "MarkedForSubmission"
SUBMITTED | "Submitted"
SETTLED | "Settled"
NOTSUBMITTED | "NotSubmitted"
FAILEDTOSETTLE | "FailedToSettle"
<a name="MethodTypeEnum"></a>
## Enum: MethodTypeEnum
Name | Value
---- | -----
ACH | "ACH"
CASH | "Cash"
CHECK | "Check"
CREDITCARD | "CreditCard"
PAYPAL | "PayPal"
WIRETRANSFER | "WireTransfer"
DEBITCARD | "DebitCard"
CREDITCARDREFERENCETRANSACTION | "CreditCardReferenceTransaction"
BANKTRANSFER | "BankTransfer"
OTHER | "Other"
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PROCESSED | "Processed"
CANCELED | "Canceled"
ERROR | "Error"
PROCESSING | "Processing"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
EXTERNAL | "External"
ELECTRONIC | "Electronic"
<file_sep># DescribeApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETDescribe**](DescribeApi.md#gETDescribe) | **GET** /v1/describe/{object} | Describe object
<a name="gETDescribe"></a>
# **gETDescribe**
> String gETDescribe(object, zuoraEntityIds)
Describe object
Provides a reference listing of each object that is available in your Zuora tenant. The information returned by this call is useful if you are using [CRUD: Create Export](https://www.zuora.com/developer/api-reference/#operation/Object_POSTExport) or the [AQuA API](https://knowledgecenter.zuora.com/DC_Developers/T_Aggregate_Query_API) to create a data source export. See [Export ZOQL](https://knowledgecenter.zuora.com/DC_Developers/M_Export_ZOQL) for more information. ## Response The response contains an XML document that lists the fields of the specified object. Each of the object's fields is represented by a `<field>` element in the XML document. Each `<field>` element contains the following elements: | Element | Description | |--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `<name>` | API name of the field. | | `<label>` | Name of the field in the Zuora user interface. | | `<type>` | Data type of the field. The possible data types are: `boolean`, `date`, `datetime`, `decimal`, `integer`, `picklist`, `text`, `timestamp`, and `ZOQL`. If the data type is `picklist`, the `<field>` element contains an `<options>` element that lists the possible values of the field. | | `<contexts>` | Specifies the availability of the field. If the `<contexts>` element lists the `export` context, the field is available for use in data source exports. | The `<field>` element contains other elements that provide legacy information about the field. This information is not directly related to the REST API. Response sample: ```xml <?xml version=\"1.0\" encoding=\"UTF-8\"?> <object> <name>ProductRatePlanCharge</name> <label>Product Rate Plan Charge</label> <fields> ... <field> <name>TaxMode</name> <label>Tax Mode</label> <type>picklist</type> <options> <option>TaxExclusive</option> <option>TaxInclusive</option> </options> <contexts> <context>export</context> </contexts> ... </field> ... </fields> </object> ``` It is strongly recommended that your integration checks `<contexts>` elements in the response. If your integration does not check `<contexts>` elements, your integration may process fields that are not available for use in data source exports. See [Changes to the Describe API](https://knowledgecenter.zuora.com/DC_Developers/M_Export_ZOQL/Changes_to_the_Describe_API) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.DescribeApi;
DescribeApi apiInstance = new DescribeApi();
String object = "object_example"; // String | API name of an object in your Zuora tenant. For example, `InvoiceItem`. See [Zuora Object Model](https://www.zuora.com/developer/api-reference/#section/Zuora-Object-Model) for the list of valid object names. Depending on the features enabled in your Zuora tenant, you may not be able to list the fields of some objects.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
String result = apiInstance.gETDescribe(object, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DescribeApi#gETDescribe");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**object** | **String**| API name of an object in your Zuora tenant. For example, `InvoiceItem`. See [Zuora Object Model](https://www.zuora.com/developer/api-reference/#section/Zuora-Object-Model) for the list of valid object names. Depending on the features enabled in your Zuora tenant, you may not be able to list the fields of some objects. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
**String**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: text/xml; charset=utf-8
<file_sep># BillRunApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEBillRun**](BillRunApi.md#objectDELETEBillRun) | **DELETE** /v1/object/bill-run/{id} | CRUD: Delete Bill Run
[**objectGETBillRun**](BillRunApi.md#objectGETBillRun) | **GET** /v1/object/bill-run/{id} | CRUD: Retrieve Bill Run
[**objectPOSTBillRun**](BillRunApi.md#objectPOSTBillRun) | **POST** /v1/object/bill-run | CRUD: Create Bill Run
[**objectPUTBillRun**](BillRunApi.md#objectPUTBillRun) | **PUT** /v1/object/bill-run/{id} | CRUD: Post or Cancel Bill Run
[**pOSTEmailBillingDocumentsfromBillRun**](BillRunApi.md#pOSTEmailBillingDocumentsfromBillRun) | **POST** /v1/bill-runs/{billRunId}/emails | Email billing documents generated from bill run
<a name="objectDELETEBillRun"></a>
# **objectDELETEBillRun**
> ProxyDeleteResponse objectDELETEBillRun(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Bill Run
**Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com). When deleting a bill run, the logic is the same as when using the UI to delete a bill run. The only required parameter is `BillRunId`. The Status for the bill run must be `Canceled` in order to delete a bill run.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillRunApi;
BillRunApi apiInstance = new BillRunApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEBillRun(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillRunApi#objectDELETEBillRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETBillRun"></a>
# **objectGETBillRun**
> ProxyGetBillRun objectGETBillRun(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Bill Run
**Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com). Business operations depending on the completion of the bill run will not be available while the bill run query returns `PostInProgress`. Upon completion of the bill run, a query will return `Posted`.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillRunApi;
BillRunApi apiInstance = new BillRunApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetBillRun result = apiInstance.objectGETBillRun(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillRunApi#objectGETBillRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetBillRun**](ProxyGetBillRun.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTBillRun"></a>
# **objectPOSTBillRun**
> ProxyCreateOrModifyResponse objectPOSTBillRun(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create Bill Run
**Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com). Creates an ad hoc bill run or a single account or multiple customer accounts. When creating a single account ad hoc bill run, your request must include `AccountId` and must not include `Batch` or `BillCycleDay`.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillRunApi;
BillRunApi apiInstance = new BillRunApi();
ProxyCreateBillRun createRequest = new ProxyCreateBillRun(); // ProxyCreateBillRun |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTBillRun(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillRunApi#objectPOSTBillRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateBillRun**](ProxyCreateBillRun.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTBillRun"></a>
# **objectPUTBillRun**
> ProxyCreateOrModifyResponse objectPUTBillRun(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Post or Cancel Bill Run
**Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com). ## Post a Bill Run Posting a bill run is an asynchronous operation. To post a bill run, the current bill run must have a status of `Completed`. When a bill run is posted, its status is changed to `PostInProgress`. Once all invoices for this bill run are posted then its status is changed to `Posted`. When you post a bill run and query the status of a bill run, you will get one of the following results `PostInProgress`, `Completed`, or `Posted`. If all invoices in the bill run are posted, then the status of the bill run is `Posted`. If one or more invoices fail to post, the status will change back to `Completed` and you will need to post the bill run again. ## Cancel a Bill Run Canceling a bill run is an asynchronous operation. When canceling a bill run, the logic is the same as when using the UI to cancel a bill run. You need to provide the `BillRunId`, and set the Status to `Canceled`. When canceling a bill run, consider the following: * Canceling a bill run with a `Completed` status. * Only the current bill run will be canceled. * Canceling a bill run with a `Pending` status. * When canceling an Ad-hoc bill run, only the current bill run will be canceled. * When canceling a scheduled bill, all scheduled bill runs will be canceled. The Cancel operation may not be successful. Its success depends on its current business validation. Only a bill run that has no posted invoices can be canceled. If any posted invoices belong to the bill run then an invalid value exception will be thrown with the message, \"The Bill Run cannot be Cancelled, There are Posted invoices.\"
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillRunApi;
BillRunApi apiInstance = new BillRunApi();
String id = "id_example"; // String | Object id
ProxyModifyBillRun modifyRequest = new ProxyModifyBillRun(); // ProxyModifyBillRun |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTBillRun(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillRunApi#objectPUTBillRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyBillRun**](ProxyModifyBillRun.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTEmailBillingDocumentsfromBillRun"></a>
# **pOSTEmailBillingDocumentsfromBillRun**
> CommonResponseType pOSTEmailBillingDocumentsfromBillRun(billRunId, request, zuoraEntityIds)
Email billing documents generated from bill run
Manually emails all the billing documents that are generated from a specified bill run to your customers. Bill runs can generate invoices and credit memos based on your [invoice and credit memo generation rule](https://knowledgecenter.zuora.com/CB_Billing/Invoice_Settlement/Credit_and_Debit_Memos/Rules_for_Generating_Invoices_and_Credit_Memos). Credit memos are only available if you have the Invoice Settlement feature enabled. Using this API operation, the billing documents are sent to the email addresses specified in the **To Email** field of the email templates. The email template used for each billing document is set in the **Delivery Options** panel of the **Edit notification** dialog from the Zuora UI. See [Edit Email Templates](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/Notifications/Create_Email_Templates) for more information about how to edit the **To Email** field in the email template. ## Notes - Even though no field is required in the Request body, you still need to specify `{}` in the request. Otherwise, an error will be returned. - You can only email posted billing documents. - You must activate the following notifications before emailing invoices and credit memos: - **Manual Email For Invoice | Manual Email For Invoice** - **Email Credit Memo | Manually email Credit Memo** - To include the invoice PDF in the email, select the **Include Invoice PDF** check box in the **Edit notification** dialog from the Zuora UI. To include the credit memo PDF in the email, select the **Include Credit Memo PDF** check box in the **Edit notification** dialog from the Zuora UI. See [Create and Edit Notifications](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/Notifications/C_Create_Notifications#section_2) for more information. - Zuora sends the email messages based on the email template you set. You can set the email template to use in the **Delivery Options** panel of the **Edit notification** dialog from the Zuora UI. By default, the following templates are used for billing documents: - Invoices: **Invoice Posted Default Email Template** - Credit memos: **Manual Email for Credit Memo Default Template** See [Create and Edit Email Templates](https://knowledgecenter.zuora.com/CF_Users_and_Administrators/Notifications/Create_Email_Templates) for more information.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.BillRunApi;
BillRunApi apiInstance = new BillRunApi();
String billRunId = "billRunId_example"; // String | The ID of the bill run. For example, 2c92c8f95d0c886e015d11287a8f0f8b.
POSTEmailBillingDocfromBillRunType request = new POSTEmailBillingDocfromBillRunType(); // POSTEmailBillingDocfromBillRunType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pOSTEmailBillingDocumentsfromBillRun(billRunId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling BillRunApi#pOSTEmailBillingDocumentsfromBillRun");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**billRunId** | **String**| The ID of the bill run. For example, 2c92c8f95d0c886e015d11287a8f0f8b. |
**request** | [**POSTEmailBillingDocfromBillRunType**](POSTEmailBillingDocfromBillRunType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# PreviewResultOrderMetrics
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**orderActions** | [**List<PreviewResultOrderActions>**](PreviewResultOrderActions.md) | | [optional]
**subscriptionNumber** | **String** | | [optional]
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.GETCustomExchangeRatesType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.CustomExchangeRatesApi")
public class CustomExchangeRatesApi {
private ApiClient apiClient;
public CustomExchangeRatesApi() {
this(new ApiClient());
}
@Autowired
public CustomExchangeRatesApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Get custom foreign currency exchange rates
* This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). This reference describes how to query custom foreign exchange rates from Zuora. You can use this API method to query exchange rates only if you use a custom exchange rate provider and upload rates with the Import Foreign Exchange Rates mass action.
* <p><b>200</b> -
* @param currency The target base currency of the tenant. The exchange rates in the response are calculated in relation to the target currency. The value must be a three-letter currency code, for example, USD.
* @param startDate Start date of the date range for which you want to get exchange rates. The date must be in yyyy-mm-dd format, for example, 2016-01-15. The start date cannot be later than the end date.
* @param endDate End date of the date range for which you want to get exchange rates. The date must be in yyyy-mm-dd format, for example, 2016-01-16. The end date can be a maximum of 90 days after the start date.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return GETCustomExchangeRatesType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GETCustomExchangeRatesType gETCustomExchangeRates(String currency, String startDate, String endDate, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'currency' is set
if (currency == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'currency' when calling gETCustomExchangeRates");
}
// verify the required parameter 'startDate' is set
if (startDate == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'startDate' when calling gETCustomExchangeRates");
}
// verify the required parameter 'endDate' is set
if (endDate == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'endDate' when calling gETCustomExchangeRates");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("currency", currency);
String path = UriComponentsBuilder.fromPath("/v1/custom-exchange-rates/{currency}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "startDate", startDate));
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "endDate", endDate));
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GETCustomExchangeRatesType> returnType = new ParameterizedTypeReference<GETCustomExchangeRatesType>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep>
# PUTSubscriptionResponseTypeCreditMemo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | Credit memo amount. | [optional]
**amountWithoutTax** | **Double** | Credit memo amount minus tax. | [optional]
**creditMemoItems** | [**List<POSTSubscriptionPreviewCreditMemoItemsType>**](POSTSubscriptionPreviewCreditMemoItemsType.md) | | [optional]
**taxAmount** | **Double** | Tax amount on the credit memo. | [optional]
<file_sep>
# RefundInvoicePayment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoiceId** | **String** | The ID of the invoice that the payment is applied to. |
**refundAmount** | **String** | The amount of the payment that is refunded. The value of this field is `0` if no refund is made against the payment. |
<file_sep>
# ProxyGetRefundTransactionLog
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**batchId** | **String** | | [optional]
**gateway** | **String** | | [optional]
**gatewayReasonCode** | **String** | | [optional]
**gatewayReasonCodeDescription** | **String** | | [optional]
**gatewayState** | **String** | | [optional]
**gatewayTransactionType** | **String** | | [optional]
**id** | **String** | Object identifier. | [optional]
**refundId** | **String** | | [optional]
**requestString** | **String** | | [optional]
**responseString** | **String** | | [optional]
**transactionDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional]
**transactionId** | **String** | | [optional]
<file_sep>
# GETAccountSummaryPaymentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**effectiveDate** | [**LocalDate**](LocalDate.md) | Effective date as `yyyy-mm-dd`. | [optional]
**id** | **String** | Payment ID. | [optional]
**paidInvoices** | [**List<GETAccountSummaryPaymentInvoiceType>**](GETAccountSummaryPaymentInvoiceType.md) | Container for paid invoices for this subscription. | [optional]
**paymentNumber** | **String** | Payment number. | [optional]
**paymentType** | **String** | Payment type; possible values are: `External`, `Electronic`. | [optional]
**status** | **String** | Payment status. Possible values are: `Draft`, `Processing`, `Processed`, `Error`, `Voided`, `Canceled`, `Posted`. | [optional]
<file_sep>
# DiscountPricingOverride
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**applyDiscountTo** | [**ApplyDiscountToEnum**](#ApplyDiscountToEnum) | Specifies which type of charge the discount charge applies to. | [optional]
**discountAmount** | [**BigDecimal**](BigDecimal.md) | Only applicable if the discount charge is a fixed-amount discount. | [optional]
**discountLevel** | [**DiscountLevelEnum**](#DiscountLevelEnum) | Application scope of the discount charge. For example, if the value of this field is `subscription` and the value of the `applyDiscountTo` field is `RECURRING`, the discount charge applies to all recurring charges in the same subscription as the discount charge. | [optional]
**discountPercentage** | [**BigDecimal**](BigDecimal.md) | Only applicable if the discount charge is a percentage discount. | [optional]
<a name="ApplyDiscountToEnum"></a>
## Enum: ApplyDiscountToEnum
Name | Value
---- | -----
ONETIME | "ONETIME"
RECURRING | "RECURRING"
USAGE | "USAGE"
ONETIMERECURRING | "ONETIMERECURRING"
ONETIMEUSAGE | "ONETIMEUSAGE"
RECURRINGUSAGE | "RECURRINGUSAGE"
ONETIMERECURRINGUSAGE | "ONETIMERECURRINGUSAGE"
<a name="DiscountLevelEnum"></a>
## Enum: DiscountLevelEnum
Name | Value
---- | -----
RATEPLAN | "rateplan"
SUBSCRIPTION | "subscription"
ACCOUNT | "account"
<file_sep># UsersApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETEntitiesUserAccessible**](UsersApi.md#gETEntitiesUserAccessible) | **GET** /v1/users/{username}/accessible-entities | Multi-entity: Get entities that a user can access
[**pUTAcceptUserAccess**](UsersApi.md#pUTAcceptUserAccess) | **PUT** /v1/users/{username}/accept-access | Multi-entity: Accept user access
[**pUTDenyUserAccess**](UsersApi.md#pUTDenyUserAccess) | **PUT** /v1/users/{username}/deny-access | Multi-entity: Deny user access
[**pUTSendUserAccessRequests**](UsersApi.md#pUTSendUserAccessRequests) | **PUT** /v1/users/{username}/request-access | Multi-entity: Send user access requests
<a name="gETEntitiesUserAccessible"></a>
# **gETEntitiesUserAccessible**
> GETEntitiesUserAccessibleResponseType gETEntitiesUserAccessible(username, zuoraEntityIds)
Multi-entity: Get entities that a user can access
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves detailed information about all the entities that a user has permission to access. ## User Access Permission You can make the call as any entity user.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsersApi;
UsersApi apiInstance = new UsersApi();
String username = "username_example"; // String | Specify the login user name that you want to retrieve.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETEntitiesUserAccessibleResponseType result = apiInstance.gETEntitiesUserAccessible(username, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsersApi#gETEntitiesUserAccessible");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| Specify the login user name that you want to retrieve. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETEntitiesUserAccessibleResponseType**](GETEntitiesUserAccessibleResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTAcceptUserAccess"></a>
# **pUTAcceptUserAccess**
> PUTAcceptUserAccessResponseType pUTAcceptUserAccess(username, zuoraEntityIds)
Multi-entity: Accept user access
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Accepts user access to an entity. ## User Access Permission You must make the calls as an administrator of the entity that you want to accept the user access to.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsersApi;
UsersApi apiInstance = new UsersApi();
String username = "username_example"; // String | Specify the login name of the user that you want to accept the access request for.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTAcceptUserAccessResponseType result = apiInstance.pUTAcceptUserAccess(username, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsersApi#pUTAcceptUserAccess");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| Specify the login name of the user that you want to accept the access request for. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTAcceptUserAccessResponseType**](PUTAcceptUserAccessResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTDenyUserAccess"></a>
# **pUTDenyUserAccess**
> PUTDenyUserAccessResponseType pUTDenyUserAccess(username, zuoraEntityIds)
Multi-entity: Deny user access
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Denies a user access to an entity. ## User Access Permission You must make the calls as an administrator of the entity that you want to deny the user access to.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsersApi;
UsersApi apiInstance = new UsersApi();
String username = "username_example"; // String | Specify the login name of the user that you want to deny the access.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTDenyUserAccessResponseType result = apiInstance.pUTDenyUserAccess(username, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsersApi#pUTDenyUserAccess");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| Specify the login name of the user that you want to deny the access. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTDenyUserAccessResponseType**](PUTDenyUserAccessResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTSendUserAccessRequests"></a>
# **pUTSendUserAccessRequests**
> PUTSendUserAccessRequestResponseType pUTSendUserAccessRequests(username, request, zuoraEntityIds)
Multi-entity: Send user access requests
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Sends access requests to the entities that a user wants to access. ## User Access Permission You must make the call as an administrator of the entity, in which the request user is created. Also, this administrator must have the permission to access the entities that the request user wants to access.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.UsersApi;
UsersApi apiInstance = new UsersApi();
String username = "username_example"; // String | Specify the login name of the user who wants to access other entities.
PUTSendUserAccessRequestType request = new PUTSendUserAccessRequestType(); // PUTSendUserAccessRequestType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTSendUserAccessRequestResponseType result = apiInstance.pUTSendUserAccessRequests(username, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsersApi#pUTSendUserAccessRequests");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| Specify the login name of the user who wants to access other entities. |
**request** | [**PUTSendUserAccessRequestType**](PUTSendUserAccessRequestType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTSendUserAccessRequestResponseType**](PUTSendUserAccessRequestResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# GETAccountSummaryTypeBasicInfoDefaultPaymentMethod
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**creditCardExpirationMonth** | **String** | Two-digit numeric card expiration month as `mm`. | [optional]
**creditCardExpirationYear** | **String** | Four-digit card expiration year as `yyyy`. | [optional]
**creditCardNumber** | **String** | Credit card number, 16 characters or less, displayed in masked format (e.g., ************1234). | [optional]
**creditCardType** | **String** | Possible values are: `Visa`, `MasterCard`, `AmericanExpress`, `Discover`. | [optional]
**id** | **String** | The ID of the credit card payment method associated with this account. | [optional]
**paymentMethodType** | **String** | | [optional]
<file_sep>
# OrderMetricsForEvergreen
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeNumber** | **String** | | [optional]
**mrr** | [**List<TimeSlicedNetMetricsForEvergreen>**](TimeSlicedNetMetricsForEvergreen.md) | | [optional]
**originRatePlanId** | **String** | | [optional]
**productRatePlanChargeId** | **String** | | [optional]
**productRatePlanId** | **String** | | [optional]
**quantity** | [**List<TimeSlicedMetricsForEvergreen>**](TimeSlicedMetricsForEvergreen.md) | | [optional]
**tcb** | [**List<TimeSlicedTcbNetMetricsForEvergreen>**](TimeSlicedTcbNetMetricsForEvergreen.md) | Total contracted billing which is the forecast value for the total invoice amount. | [optional]
**tcv** | [**List<TimeSlicedNetMetricsForEvergreen>**](TimeSlicedNetMetricsForEvergreen.md) | Total contracted value. | [optional]
<file_sep>
# POSTInvoiceCollectInvoicesType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoiceAmount** | **String** | The amount of the invoice. | [optional]
**invoiceId** | **String** | The ID of the invoice. | [optional]
**invoiceNumber** | **String** | The unique identification number of the invoice. | [optional]
<file_sep>
# POSTUsageResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**checkImportStatus** | **String** | The path for checking the status of the import. The possible status values at this path are `Pending`, `Processing`, `Completed`, `Canceled`, and `Failed`. Only `Completed` indicates that the file contents were imported successfully. | [optional]
**size** | **Long** | The size of the uploaded file in bytes. | [optional]
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
<file_sep>
# PreviewResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeMetrics** | [**List<PreviewResultChargeMetrics>**](PreviewResultChargeMetrics.md) | | [optional]
**creditMemos** | [**List<PreviewResultCreditMemos>**](PreviewResultCreditMemos.md) | This field is only available if you have the Invoice Settlement feature enabled. | [optional]
**invoices** | [**List<PreviewResultInvoices>**](PreviewResultInvoices.md) | | [optional]
**orderMetrics** | [**List<PreviewResultOrderMetrics>**](PreviewResultOrderMetrics.md) | | [optional]
<file_sep>
# POSTOrderRequestTypeSubscriptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**customFields** | [**SubscriptionObjectCustomFields**](SubscriptionObjectCustomFields.md) | | [optional]
**orderActions** | [**List<CreateOrderOrderAction>**](CreateOrderOrderAction.md) | The actions to be applied to the subscription. Order actions will be stored with the sequence when it was provided in the request. | [optional]
**subscriptionNumber** | **String** | Leave this empty to represent new subscription creation. Specify a subscription number to update an existing subscription. | [optional]
<file_sep>
# PreviewOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**previewThruType** | [**PreviewThruTypeEnum**](#PreviewThruTypeEnum) | The options on how the preview through date is calculated. Available for preview only. The 'TermEnd' option is invalid when any subscription included in this order is evergreen. If set the value of this field to 'SpecificDate', you must specify a specific date in the 'specificPreviewThruDate' field. | [optional]
**previewTypes** | [**List<PreviewTypesEnum>**](#List<PreviewTypesEnum>) | | [optional]
**specificPreviewThruDate** | [**LocalDate**](LocalDate.md) | The end date of the order preview. You can preview the invoice charges through the preview through date. (Invoice preview only) **Note:** This field is only applicable if the 'previewThruType' field is set to 'SpecificDate'. | [optional]
<a name="PreviewThruTypeEnum"></a>
## Enum: PreviewThruTypeEnum
Name | Value
---- | -----
SPECIFICDATE | "SpecificDate"
TERMEND | "TermEnd"
<a name="List<PreviewTypesEnum>"></a>
## Enum: List<PreviewTypesEnum>
Name | Value
---- | -----
CHARGEMETRICS | "ChargeMetrics"
BILLINGDOCS | "BillingDocs"
ORDERMETRICS | "OrderMetrics"
<file_sep>
# POSTTaxationItemListForCMType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**taxationItems** | [**List<POSTTaxationItemForCMType>**](POSTTaxationItemForCMType.md) | Container for taxation items. | [optional]
<file_sep>
# OrderAction
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**addProduct** | [**RatePlanOverride**](RatePlanOverride.md) | | [optional]
**cancelSubscription** | [**CancelSubscription**](CancelSubscription.md) | | [optional]
**createSubscription** | [**CreateSubscription**](CreateSubscription.md) | | [optional]
**customFields** | [**OrderActionObjectCustomFields**](OrderActionObjectCustomFields.md) | | [optional]
**orderItems** | [**List<OrderItem>**](OrderItem.md) | | [optional]
**orderMetrics** | [**List<OrderMetric>**](OrderMetric.md) | | [optional]
**ownerTransfer** | [**OwnerTransfer**](OwnerTransfer.md) | | [optional]
**removeProduct** | [**RemoveProduct**](RemoveProduct.md) | | [optional]
**sequence** | **Integer** | The sequence of the order actions processed in the order. | [optional]
**termsAndConditions** | [**TermsAndConditions**](TermsAndConditions.md) | | [optional]
**triggerDates** | [**List<TriggerDate>**](TriggerDate.md) | | [optional]
**type** | [**TypeEnum**](#TypeEnum) | Type of the order action. | [optional]
**updateProduct** | [**RatePlanUpdate**](RatePlanUpdate.md) | | [optional]
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
CREATESUBSCRIPTION | "CreateSubscription"
TERMSANDCONDITIONS | "TermsAndConditions"
ADDPRODUCT | "AddProduct"
UPDATEPRODUCT | "UpdateProduct"
REMOVEPRODUCT | "RemoveProduct"
RENEWSUBSCRIPTION | "RenewSubscription"
CANCELSUBSCRIPTION | "CancelSubscription"
OWNERTRANSFER | "OwnerTransfer"
<file_sep>
# CreditMemoApplyDebitMemoRequestType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **Double** | The credit memo amount to be applied to the debit memo. |
**debitMemoId** | **String** | The unique ID of the debit memo that the credit memo is applied to. |
**items** | [**List<CreditMemoApplyDebitMemoItemRequestType>**](CreditMemoApplyDebitMemoItemRequestType.md) | Container for items. | [optional]
<file_sep>
# SaveResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**errors** | [**List<ActionsErrorResponse>**](ActionsErrorResponse.md) | | [optional]
**id** | **String** | | [optional]
**success** | **Boolean** | | [optional]
<file_sep>
# OrderRatedResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**orderNumber** | **String** | | [optional]
**subscriptionRatedResults** | [**List<SubscriptionRatedResult>**](SubscriptionRatedResult.md) | An array of subscription changes included in this order. | [optional]
<file_sep>
# ProxyGetPayment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the payment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the payment was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The unique account ID for the customer that the payment is for. | [optional]
**accountingCode** | **String** | The aacccounting code for the payment. Accounting codes group transactions that contain similar accounting attributes. | [optional]
**amount** | **Double** | The amount of the payment. | [optional]
**appliedCreditBalanceAmount** | **Double** | The amount of the payment to apply to a credit balance. | [optional]
**authTransactionId** | **String** | The authorization transaction ID from the payment gateway. | [optional]
**bankIdentificationNumber** | **String** | The first six digits of the credit card or debit card used for the payment, when applicable. | [optional]
**cancelledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment was canceled. | [optional]
**comment** | **String** | Additional information related to the payment. | [optional]
**createdById** | **String** | The ID of the Zuora user who created the payment. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment was created. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the payment takes effect. | [optional]
**gateway** | **String** | The name of the gateway instance that processes the payment. | [optional]
**gatewayOrderId** | **String** | A merchant-specified natural key value that can be passed to the electronic payment gateway when a payment is created. If not specified, the payment number will be passed in instead. | [optional]
**gatewayResponse** | **String** | The message returned from the payment gateway for the payment. This message is gateway-dependent. | [optional]
**gatewayResponseCode** | **String** | The code returned from the payment gateway for the payment. This code is gateway-dependent. | [optional]
**gatewayState** | [**GatewayStateEnum**](#GatewayStateEnum) | The status of the payment in the gateway; use for reconciliation. | [optional]
**id** | **String** | The unique ID of a payment. For example, 2c92c095592623ea01596621ada84352. | [optional]
**markedForSubmissionOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when a payment was marked and waiting for batch submission to the payment process. | [optional]
**paymentMethodId** | **String** | The ID of the payment method used for the payment. | [optional]
**paymentMethodSnapshotId** | **String** | The unique ID of the payment method snapshot which is a copy of the particular payment method used in a transaction. | [optional]
**paymentNumber** | **String** | The unique identification number of the payment. For example, P-00000028. | [optional]
**referenceId** | **String** | The transaction ID returned by the payment gateway. Use this field to reconcile payments between your gateway and Zuora Payments. | [optional]
**refundAmount** | **Double** | The amount of the payment that is refunded. The value of this field is `0` if no refund is made against the payment. | [optional]
**secondPaymentReferenceId** | **String** | The transaction ID returned by the payment gateway if there is an additional transaction for the payment. Use this field to reconcile payments between your gateway and Zuora Payments. | [optional]
**settledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment was settled in the payment processor. This field is used by the Spectrum gateway only and not applicable to other gateways. | [optional]
**softDescriptor** | **String** | A payment gateway-specific field that maps to Zuora for the gateways, Orbital, Vantiv and Verifi. | [optional]
**softDescriptorPhone** | **String** | A payment gateway-specific field that maps to Zuora for the gateways, Orbital, Vantiv and Verifi. | [optional]
**source** | [**SourceEnum**](#SourceEnum) | How the payment was created, whether through the API, manually, import, or payment run. | [optional]
**sourceName** | **String** | The name of the source. The value is a Payment Run number or a file name. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the payment in Zuora. The value depends on the type of payment. For electronic payments, the status can be `Processed`, `Error`, or `Voided`. For external payments, the status can be `Processed` or `Canceled`. | [optional]
**submittedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment was submitted. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Indicates if the payment was transferred to an external accounting system. Use this field for integration with accounting systems, such as NetSuite. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | The type of the payment, whether the payment is external or electronic. | [optional]
**updatedById** | **String** | The ID of the Zuora user who last updated the payment. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the payment was last updated. | [optional]
<a name="GatewayStateEnum"></a>
## Enum: GatewayStateEnum
Name | Value
---- | -----
MARKEDFORSUBMISSION | "MarkedForSubmission"
SUBMITTED | "Submitted"
SETTLED | "Settled"
NOTSUBMITTED | "NotSubmitted"
FAILEDTOSETTLE | "FailedToSettle"
<a name="SourceEnum"></a>
## Enum: SourceEnum
Name | Value
---- | -----
PAYMENTRUN | "PaymentRun"
IMPORT | "Import"
MANUALLY | "Manually"
API | "API"
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
PROCESSED | "Processed"
ERROR | "Error"
VOIDED | "Voided"
CANCELED | "Canceled"
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
ERROR | "Error"
IGNORE | "Ignore"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
EXTERNAL | "External"
ELECTRONIC | "Electronic"
<file_sep>
# GETBillingDocumentsResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountId** | [**UUID**](UUID.md) | The ID of the customer account associated with the billing document. | [optional]
**amount** | **Double** | The total amount of the billing document. | [optional]
**balance** | **Double** | The balance of the billing document. | [optional]
**documentDate** | [**LocalDate**](LocalDate.md) | The date of the billing document. The date can be the invoice date for invoices, credit memo date for credit memos, or debit memo date for debit memos. | [optional]
**documentNumber** | **String** | The number of the billing document. | [optional]
**documentType** | [**DocumentTypeEnum**](#DocumentTypeEnum) | The type of the billing document. | [optional]
**id** | **String** | The ID of the billing document. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The current status of the billing document. | [optional]
<a name="DocumentTypeEnum"></a>
## Enum: DocumentTypeEnum
Name | Value
---- | -----
INVOICE | "Invoice"
CREDITMEMO | "CreditMemo"
DEBITMEMO | "DebitMemo"
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
DRAFT | "Draft"
POSTED | "Posted"
CANCELED | "Canceled"
ERROR | "Error"
<file_sep>
# POSTBillingPreviewInvoiceItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeAmount** | **String** | The amount of the charge. This amount doesn't include taxes regardless if the charge's tax mode is inclusive or exclusive. | [optional]
**chargeDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date when the invoice item was created. | [optional]
**chargeDescription** | **String** | Description of the charge. | [optional]
**chargeId** | **String** | Id of the charge. | [optional]
**chargeName** | **String** | Name of the charge. | [optional]
**chargeNumber** | **String** | Number of the charge. | [optional]
**chargeType** | **String** | The type of charge. Possible values are `OneTime`, `Recurring`, and `Usage`. | [optional]
**id** | **String** | Invoice item ID. | [optional]
**processingType** | **String** | Identifies the kind of charge. Possible values: * charge * discount * prepayment * tax | [optional]
**productName** | **String** | Name of the product associated with this item. | [optional]
**quantity** | **String** | Quantity of this item, in the configured unit of measure for the charge. | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | End date of the service period for this item, i.e., the last day of the service period, in `yyyy-mm-dd` format. | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | Start date of the service period for this item, in `yyyy-mm-dd` format. If the charge is a one-time fee, this is the date of that charge. | [optional]
**subscriptionId** | **String** | ID of the subscription associated with this item. | [optional]
**subscriptionName** | **String** | Name of the subscription associated with this item. | [optional]
**subscriptionNumber** | **String** | Number of the subscription associated with this item. | [optional]
**taxAmount** | **String** | Tax applied to the charge. This field returns `0` becasue the BillingPreview operation does not calculate taxes for charges in the subscription. | [optional]
**unitOfMeasure** | **String** | Unit used to measure consumption. | [optional]
<file_sep># PaymentMethodsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEPaymentMethods**](PaymentMethodsApi.md#dELETEPaymentMethods) | **DELETE** /v1/payment-methods/{payment-method-id} | Delete payment method
[**gETPaymentMethodsCreditCard**](PaymentMethodsApi.md#gETPaymentMethodsCreditCard) | **GET** /v1/payment-methods/credit-cards/accounts/{account-key} | Get credit card payment methods for account
[**objectDELETEPaymentMethod**](PaymentMethodsApi.md#objectDELETEPaymentMethod) | **DELETE** /v1/object/payment-method/{id} | CRUD: Delete payment method
[**objectGETPaymentMethod**](PaymentMethodsApi.md#objectGETPaymentMethod) | **GET** /v1/object/payment-method/{id} | CRUD: Get payment method
[**objectPOSTPaymentMethod**](PaymentMethodsApi.md#objectPOSTPaymentMethod) | **POST** /v1/object/payment-method | CRUD: Create payment method
[**objectPUTPaymentMethod**](PaymentMethodsApi.md#objectPUTPaymentMethod) | **PUT** /v1/object/payment-method/{id} | CRUD: Update payment method
[**pOSTCancelAuthorization**](PaymentMethodsApi.md#pOSTCancelAuthorization) | **POST** /v1/payment-methods/{payment-method-id}/voidAuthorize | Cancel authorization
[**pOSTCreateAuthorization**](PaymentMethodsApi.md#pOSTCreateAuthorization) | **POST** /v1/payment-methods/{payment-method-id}/authorize | Create authorization
[**pOSTPaymentMethods**](PaymentMethodsApi.md#pOSTPaymentMethods) | **POST** /v1/payment-methods | Create payment method
[**pOSTPaymentMethodsCreditCard**](PaymentMethodsApi.md#pOSTPaymentMethodsCreditCard) | **POST** /v1/payment-methods/credit-cards | Create credit card payment method
[**pOSTPaymentMethodsDecryption**](PaymentMethodsApi.md#pOSTPaymentMethodsDecryption) | **POST** /v1/payment-methods/decryption | Create Apple Pay payment method
[**pUTPaymentMethodsCreditCard**](PaymentMethodsApi.md#pUTPaymentMethodsCreditCard) | **PUT** /v1/payment-methods/credit-cards/{payment-method-id} | Update credit card payment method
[**pUTScrubPaymentMethods**](PaymentMethodsApi.md#pUTScrubPaymentMethods) | **PUT** /v1/payment-methods/{payment-method-id}/scrub | Scrub payment method
[**pUTVerifyPaymentMethods**](PaymentMethodsApi.md#pUTVerifyPaymentMethods) | **PUT** /v1/payment-methods/{payment-method-id}/verify | Verify payment method
<a name="dELETEPaymentMethods"></a>
# **dELETEPaymentMethods**
> CommonResponseType dELETEPaymentMethods(paymentMethodId, zuoraEntityIds)
Delete payment method
Deletes a credit card payment method from the specified customer account. If the specified payment method is the account's default payment method, the request will fail. In that case, you must first designate a different payment method for that customer to be the default.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String paymentMethodId = "paymentMethodId_example"; // String | Unique identifier of a payment method. (Since this ID is unique, and linked to a customer account in the system, no customer identifier is needed.)
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEPaymentMethods(paymentMethodId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#dELETEPaymentMethods");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentMethodId** | **String**| Unique identifier of a payment method. (Since this ID is unique, and linked to a customer account in the system, no customer identifier is needed.) |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETPaymentMethodsCreditCard"></a>
# **gETPaymentMethodsCreditCard**
> GETPaymentMethodsType gETPaymentMethodsCreditCard(accountKey, zuoraEntityIds, pageSize)
Get credit card payment methods for account
This REST API reference describes how to retrieve all credit card information for the specified customer account. ## Notes The response includes details credit or debit cards for the specified customer account. Card numbers are masked, e.g., \"************1234\". Cards are returned in reverse chronological order of last update. You can send requests for bank transfer payment methods types. The response will not include bank transfer details. The response only includes payment details on payment methods that are credit or debit cards.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String accountKey = "accountKey_example"; // String | Account number or account ID.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
try {
GETPaymentMethodsType result = apiInstance.gETPaymentMethodsCreditCard(accountKey, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#gETPaymentMethodsCreditCard");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| Account number or account ID. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
### Return type
[**GETPaymentMethodsType**](GETPaymentMethodsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectDELETEPaymentMethod"></a>
# **objectDELETEPaymentMethod**
> ProxyDeleteResponse objectDELETEPaymentMethod(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete payment method
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEPaymentMethod(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#objectDELETEPaymentMethod");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETPaymentMethod"></a>
# **objectGETPaymentMethod**
> ProxyGetPaymentMethod objectGETPaymentMethod(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Get payment method
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetPaymentMethod result = apiInstance.objectGETPaymentMethod(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#objectGETPaymentMethod");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetPaymentMethod**](ProxyGetPaymentMethod.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTPaymentMethod"></a>
# **objectPOSTPaymentMethod**
> ProxyCreateOrModifyResponse objectPOSTPaymentMethod(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create payment method
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
ProxyCreatePaymentMethod createRequest = new ProxyCreatePaymentMethod(); // ProxyCreatePaymentMethod |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTPaymentMethod(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#objectPOSTPaymentMethod");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreatePaymentMethod**](ProxyCreatePaymentMethod.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTPaymentMethod"></a>
# **objectPUTPaymentMethod**
> ProxyCreateOrModifyResponse objectPUTPaymentMethod(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update payment method
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String id = "id_example"; // String | Object id
ProxyModifyPaymentMethod modifyRequest = new ProxyModifyPaymentMethod(); // ProxyModifyPaymentMethod |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTPaymentMethod(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#objectPUTPaymentMethod");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyPaymentMethod**](ProxyModifyPaymentMethod.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTCancelAuthorization"></a>
# **pOSTCancelAuthorization**
> POSTVoidAuthorizeResponse pOSTCancelAuthorization(paymentMethodId, request, zuoraEntityIds)
Cancel authorization
**Note:** If you wish to enable this feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Allows you to cancel an authorization. The payment gateways that support this operation include Verifi, CyberSource 1.28, and CyberSource 1.97.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String paymentMethodId = "paymentMethodId_example"; // String | The unique ID of the payment method where the authorization is cancelled.
POSTVoidAuthorize request = new POSTVoidAuthorize(); // POSTVoidAuthorize |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTVoidAuthorizeResponse result = apiInstance.pOSTCancelAuthorization(paymentMethodId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pOSTCancelAuthorization");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentMethodId** | **String**| The unique ID of the payment method where the authorization is cancelled. |
**request** | [**POSTVoidAuthorize**](POSTVoidAuthorize.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTVoidAuthorizeResponse**](POSTVoidAuthorizeResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTCreateAuthorization"></a>
# **pOSTCreateAuthorization**
> POSTAuthorizeResponse pOSTCreateAuthorization(paymentMethodId, request, zuoraEntityIds)
Create authorization
**Note:** If you wish to enable this feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Enables you to authorize the availability of funds for a transaction but delay the capture of funds until a later time. The payment gateways that support this operation include Verifi, CyberSource 1.28, and CyberSource 1.97.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String paymentMethodId = "paymentMethodId_example"; // String | The unique ID of the payment method where the authorization is created.
POSTDelayAuthorizeCapture request = new POSTDelayAuthorizeCapture(); // POSTDelayAuthorizeCapture |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTAuthorizeResponse result = apiInstance.pOSTCreateAuthorization(paymentMethodId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pOSTCreateAuthorization");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentMethodId** | **String**| The unique ID of the payment method where the authorization is created. |
**request** | [**POSTDelayAuthorizeCapture**](POSTDelayAuthorizeCapture.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTAuthorizeResponse**](POSTAuthorizeResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTPaymentMethods"></a>
# **pOSTPaymentMethods**
> POSTPaymentMethodResponse pOSTPaymentMethods(request, zuoraEntityIds)
Create payment method
You can use this operation to create a payment method for a customer account. This operation supports the payment methods listed below. ### PayPal Express Checkout The following request body fields are specific to this payment method: * `BAID` (required) * `email` (required) ### PayPal Native Express Checkout The following request body fields are specific to this payment method: * `BAID` (required) * `email` (optional) ### PayPal Adaptive The following request body fields are specific to this payment method: * `preapprovalKey` (required) * `email` (required)
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
POSTPaymentMethodRequest request = new POSTPaymentMethodRequest(); // POSTPaymentMethodRequest |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTPaymentMethodResponse result = apiInstance.pOSTPaymentMethods(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pOSTPaymentMethods");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTPaymentMethodRequest**](POSTPaymentMethodRequest.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTPaymentMethodResponse**](POSTPaymentMethodResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTPaymentMethodsCreditCard"></a>
# **pOSTPaymentMethodsCreditCard**
> POSTPaymentMethodResponseType pOSTPaymentMethodsCreditCard(request, zuoraEntityIds)
Create credit card payment method
This REST API reference describes how to create a new credit card payment method for a customer account. This API call is CORS Enabled. Use client-side JavaScript to invoke the call. **Note**: If you use this operation to create credit card payment methods instead of using the [iFrame of Hosted Payment Pages](https://knowledgecenter.zuora.com/CB_Billing/LA_Hosted_Payment_Pages/C_Hosted_Payment_Pages/B_Implementing_Hosted_Payment_Pages_on_Your_Website/C_Embed_and_Submit_the_iFrame), you are subject to PCI-compliance audit requirements.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
POSTPaymentMethodType request = new POSTPaymentMethodType(); // POSTPaymentMethodType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTPaymentMethodResponseType result = apiInstance.pOSTPaymentMethodsCreditCard(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pOSTPaymentMethodsCreditCard");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTPaymentMethodType**](POSTPaymentMethodType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTPaymentMethodResponseType**](POSTPaymentMethodResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTPaymentMethodsDecryption"></a>
# **pOSTPaymentMethodsDecryption**
> POSTPaymentMethodResponseDecryption pOSTPaymentMethodsDecryption(request, zuoraEntityIds)
Create Apple Pay payment method
The decryption API endpoint can conditionally perform 3 tasks in one atomic call: * Decrypt Apple Pay Payment token * Create Credit Card Payment Method in Zuora with decrypted Apple Pay information * Process Payment on a specified Invoice (optional)
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
POSTPaymentMethodDecryption request = new POSTPaymentMethodDecryption(); // POSTPaymentMethodDecryption |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTPaymentMethodResponseDecryption result = apiInstance.pOSTPaymentMethodsDecryption(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pOSTPaymentMethodsDecryption");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTPaymentMethodDecryption**](POSTPaymentMethodDecryption.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTPaymentMethodResponseDecryption**](POSTPaymentMethodResponseDecryption.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTPaymentMethodsCreditCard"></a>
# **pUTPaymentMethodsCreditCard**
> PUTPaymentMethodResponseType pUTPaymentMethodsCreditCard(paymentMethodId, request, zuoraEntityIds)
Update credit card payment method
Updates an existing credit card payment method for the specified customer account.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String paymentMethodId = "paymentMethodId_example"; // String | Unique ID of the payment method to update.
PUTPaymentMethodType request = new PUTPaymentMethodType(); // PUTPaymentMethodType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTPaymentMethodResponseType result = apiInstance.pUTPaymentMethodsCreditCard(paymentMethodId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pUTPaymentMethodsCreditCard");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentMethodId** | **String**| Unique ID of the payment method to update. |
**request** | [**PUTPaymentMethodType**](PUTPaymentMethodType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTPaymentMethodResponseType**](PUTPaymentMethodResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTScrubPaymentMethods"></a>
# **pUTScrubPaymentMethods**
> CommonResponseType pUTScrubPaymentMethods(paymentMethodId, zuoraEntityIds)
Scrub payment method
**Note:** If you wish to enable this feature, submit a request at [Zuora Global Support](http://support.zuora.com/). This operation enables you to replace all sensitive data in a payment method, related payment method snapshot table, and four related log tables with dummy values that will be stored in Zuora databases. This operation will scrub the sensitive data and soft-delete the specified payment method at the same time.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String paymentMethodId = "paymentMethodId_example"; // String | The ID of the payment method where you want to scrub the sensitive data.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTScrubPaymentMethods(paymentMethodId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pUTScrubPaymentMethods");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentMethodId** | **String**| The ID of the payment method where you want to scrub the sensitive data. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTVerifyPaymentMethods"></a>
# **pUTVerifyPaymentMethods**
> PUTVerifyPaymentMethodResponseType pUTVerifyPaymentMethods(paymentMethodId, body)
Verify payment method
Sends an authorization request to the corresponding payment gateway to verify the payment method, even though no changes are made for the payment method. Supported payment methods are Credit Cards and Paypal. Zuora now supports performing a standalone zero dollar verification or one dollar authorization for credit cards. It also supports a billing agreement status check on PayPal payment methods. If a payment method is created by Hosted Payment Pages and is not assigned to any billing account, the payment method cannot be verified through this operation.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.PaymentMethodsApi;
PaymentMethodsApi apiInstance = new PaymentMethodsApi();
String paymentMethodId = "paymentMethodId_example"; // String | The ID of the payment method to be verified.
PUTVerifyPaymentMethodType body = new PUTVerifyPaymentMethodType(); // PUTVerifyPaymentMethodType |
try {
PUTVerifyPaymentMethodResponseType result = apiInstance.pUTVerifyPaymentMethods(paymentMethodId, body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PaymentMethodsApi#pUTVerifyPaymentMethods");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**paymentMethodId** | **String**| The ID of the payment method to be verified. |
**body** | [**PUTVerifyPaymentMethodType**](PUTVerifyPaymentMethodType.md)| |
### Return type
[**PUTVerifyPaymentMethodResponseType**](PUTVerifyPaymentMethodResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# ZObjectUpdate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **String** | |
**fieldsToNull** | **String** | | [optional]
<file_sep>
# ChargeMetricsData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**chargeMetrics** | [**List<NewChargeMetrics>**](NewChargeMetrics.md) | | [optional]
<file_sep>
# POSTJournalEntryType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accountingPeriodName** | **String** | Name of the accounting period. The open-ended accounting period is named `Open-Ended`. |
**currency** | **String** | The type of currency used. Currency must be active. |
**journalEntryDate** | [**LocalDate**](LocalDate.md) | Date of the journal entry. |
**journalEntryItems** | [**List<POSTJournalEntryItemType>**](POSTJournalEntryItemType.md) | Key name that represents the list of journal entry items. |
**notes** | **String** | The number associated with the revenue event. Character limit: 2,000 | [optional]
**segments** | [**List<POSTJournalEntrySegmentType>**](POSTJournalEntrySegmentType.md) | List of segments that apply to the summary journal entry. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Status shows whether the journal entry has been transferred to an accounting system. | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
NO | "No"
PROCESSING | "Processing"
YES | "Yes"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# PreviewAccountInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**billCycleDay** | **Integer** | Day of the month that the account prefers billing periods to begin on. If set to 0, the bill cycle day will be set as \"AutoSet\". |
**currency** | **String** | ISO 3-letter currency code (uppercase). For example, USD. |
**customFields** | [**AccountObjectCustomFields**](AccountObjectCustomFields.md) | | [optional]
**soldToContact** | [**PreviewContactInfo**](PreviewContactInfo.md) | | [optional]
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.GetBillingPreviewRunResponse;
import de.keylight.zuora.client.model.InlineResponse200;
import de.keylight.zuora.client.model.PostBillingPreviewRunParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.BillingPreviewRunApi")
public class BillingPreviewRunApi {
private ApiClient apiClient;
public BillingPreviewRunApi() {
this(new ApiClient());
}
@Autowired
public BillingPreviewRunApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Get Billing Preview Run
* **Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves a preview of future invoice items for multiple customer accounts through a billing preview run. If you have the Invoice Settlement feature enabled, you can also retrieve a preview of future credit memo items. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). A billing preview run asynchronously generates a downloadable CSV file containing a preview of invoice item data and credit memo item data for a batch of customer accounts.
* <p><b>200</b> -
* @param billingPreviewRunId Id of the billing preview run.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return GetBillingPreviewRunResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GetBillingPreviewRunResponse gETBillingPreviewRun(String billingPreviewRunId, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'billingPreviewRunId' is set
if (billingPreviewRunId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'billingPreviewRunId' when calling gETBillingPreviewRun");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("billingPreviewRunId", billingPreviewRunId);
String path = UriComponentsBuilder.fromPath("/v1/billing-preview-runs/{billingPreviewRunId}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GetBillingPreviewRunResponse> returnType = new ParameterizedTypeReference<GetBillingPreviewRunResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Create Billing Preview Run
* **Note:** This feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates billing preview runs for multiple customer accounts. You can run up to 10 billing previews in batches concurrently. A single batch of customer accounts can only have one billing preview run at a time. So you can have up to 10 batches running at the same time. If you create a billing preview run for all customer batches, you cannot create another billing preview run until this preview run is completed.
* <p><b>200</b> -
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return InlineResponse200
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public InlineResponse200 pOSTBillingPreviewRun(PostBillingPreviewRunParam request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTBillingPreviewRun");
}
String path = UriComponentsBuilder.fromPath("/v1/billing-preview-runs").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<InlineResponse200> returnType = new ParameterizedTypeReference<InlineResponse200>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep>
# ContactObjectCustomFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
<file_sep># OperationsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**pOSTBillingPreview**](OperationsApi.md#pOSTBillingPreview) | **POST** /v1/operations/billing-preview | Create billing preview
[**pOSTTransactionInvoicePayment**](OperationsApi.md#pOSTTransactionInvoicePayment) | **POST** /v1/operations/invoice-collect | Invoice and collect
<a name="pOSTBillingPreview"></a>
# **pOSTBillingPreview**
> BillingPreviewResult pOSTBillingPreview(request, zuoraEntityIds)
Create billing preview
**Note:** The Billing Preview feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Generates a preview of future invoice items for one customer account. Use the BillingPreview call to calculate how much a single customer will be invoiced from the most recent invoice to a specific end of term date in the future. Additionally, you can use the BillingPreview service to access real-time data on an individual customer's usage consumption. The BillingPreview call does not calculate taxes for charges in the subscription. If you have the Invoice Settlement feature enabled, you can also generate a preview of future credit memo items for one customer account. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/).
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OperationsApi;
OperationsApi apiInstance = new OperationsApi();
PostBillingPreviewParam request = new PostBillingPreviewParam(); // PostBillingPreviewParam |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
BillingPreviewResult result = apiInstance.pOSTBillingPreview(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OperationsApi#pOSTBillingPreview");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**PostBillingPreviewParam**](PostBillingPreviewParam.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**BillingPreviewResult**](BillingPreviewResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTTransactionInvoicePayment"></a>
# **pOSTTransactionInvoicePayment**
> POSTInvoiceCollectResponseType pOSTTransactionInvoicePayment(request, zuoraEntityIds, zuoraVersion)
Invoice and collect
Generates and posts invoices and credit memos and collects payments for posted invoices. Credit memos are only available if you have the Invoice Settlement feature enabled and negative charges exist. Credit memos will not be applied to invoices. If draft invoices and credit memos exist when you run this operation, this operation will post the invoices and credit memos. Note that draft credit memos created from an invoice or a product rate plan charge will not be posted. You can use this operation to generate invoices and collect payments on the posted invoices, or else simply collect payment on a specified existing invoice. The customer's default payment method is used, and the full amount due is collected. The operation depends on the parameters you specify. - To generate one or more new invoices for that customer and collect payment on the generated and other unpaid invoice(s), leave the **invoiceId** field empty. - To collect payment on an existing invoice, specify the invoice ID. The operation is atomic; if any part is unsuccessful, the entire operation is rolled back. When an error occurs, gateway reason codes and error messages are returned the error response of this operation. The following items are some gateway response code examples. - Orbital: `05 Do Not Honor`; `14 Invalid Credit Card Number` - Vantiv: `301 Invalid Account Number`; `304 Lost/Stolen Card` - CyberSource2: `202 Expired card`; `231 Invalid account number` For more reason code information, see the corresponding payment gateway documentation. ## Notes Timeouts may occur when using this method on an account that has an extremely high number of subscriptions.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.OperationsApi;
OperationsApi apiInstance = new OperationsApi();
POSTInvoiceCollectType request = new POSTInvoiceCollectType(); // POSTInvoiceCollectType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * documentDate * targetDate If you have the Invoice Settlement feature enabled, you need to specify this parameter. Otherwise, an error is returned. See [Zuora REST API Versions](https://www.zuora.com/developer/api-reference/#section/API-Versions) for more information.
try {
POSTInvoiceCollectResponseType result = apiInstance.pOSTTransactionInvoicePayment(request, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OperationsApi#pOSTTransactionInvoicePayment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTInvoiceCollectType**](POSTInvoiceCollectType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You need to set this parameter if you use the following fields: * documentDate * targetDate If you have the Invoice Settlement feature enabled, you need to specify this parameter. Otherwise, an error is returned. See [Zuora REST API Versions](https://www.zuora.com/developer/api-reference/#section/API-Versions) for more information. | [optional]
### Return type
[**POSTInvoiceCollectResponseType**](POSTInvoiceCollectResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# CreatePaymentType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the payment's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**originNS** | **String** | Origin of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the payment was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**transactionNS** | **String** | Related transaction in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The ID of the customer account that the payment is created for. | [optional]
**amount** | **Double** | The total amount of the payment. |
**comment** | **String** | Additional information related to the payment. | [optional]
**currency** | **String** | A currency defined in the web-based UI administrative settings. |
**debitMemos** | [**List<PaymentDebitMemoApplicationCreateRequestType>**](PaymentDebitMemoApplicationCreateRequestType.md) | Container for debit memos. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the payment takes effect, in `yyyy-mm-dd` format. | [optional]
**financeInformation** | [**CreatePaymentTypeFinanceInformation**](CreatePaymentTypeFinanceInformation.md) | | [optional]
**gatewayId** | **String** | The ID of the gateway instance that processes the payment. When creating a payment, the ID must be a valid gateway instance name and this gateway must support the specific payment method. If not specified, the default gateway on the Account will be used. | [optional]
**invoices** | [**List<PaymentInvoiceApplicationCreateRequestType>**](PaymentInvoiceApplicationCreateRequestType.md) | Container for invoices. | [optional]
**paymentMethodId** | **String** | The unique ID of the payment method that the customer used to make the payment. If no payment method ID is specified in the request body, the default payment method for the customer account is used automatically. If the default payment method is different from the type of payments that you want to create, an error occurs. | [optional]
**referenceId** | **String** | The transaction ID returned by the payment gateway. Use this field to reconcile payments between your gateway and Zuora Payments. | [optional]
**type** | [**TypeEnum**](#TypeEnum) | The type of the payment. |
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
EXTERNAL | "External"
ELECTRONIC | "Electronic"
<file_sep>
# InvoicePaymentData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoicePayment** | [**List<InvoicePayment>**](InvoicePayment.md) | |
<file_sep>
# POSTPublicEmailTemplateRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**active** | **Boolean** | The status of the email template. The default value is true. | [optional]
**bccEmailAddress** | **String** | The email bcc address. | [optional]
**ccEmailAddress** | **String** | The email CC address. | [optional]
**ccEmailType** | [**CcEmailTypeEnum**](#CcEmailTypeEnum) | Email CC type: * When EventType is CDC/External and 'ReferenceObjectType' in EventType is associated to Account, ccEmailType can be ALL values in enum. * When EventType is CDC/External and 'ReferenceObjectType' in EventType is not associated to Account, ccEmailType MUST be TenantAdmin, RunOwner or SpecificEmail. * When EventType is CDC/External and 'ReferenceObjectType' in EventType is EMPTY, ccEmailType MUST be TenantAdmin, RunOwner or SpecificEmail. | [optional]
**description** | **String** | The description of the email template. | [optional]
**emailBody** | **String** | The email body. You can add merge fields in the email object using angle brackets. You can also embed HTML tags if 'isHtml' is true. |
**emailSubject** | **String** | The email subject. Users can add merge fields in the email subject using angle brackets. |
**encodingType** | [**EncodingTypeEnum**](#EncodingTypeEnum) | The endcode type of the email body. | [optional]
**eventTypeName** | **String** | The name of event type |
**fromEmailAddress** | **String** | If fromEmailType is SpecificEmail, this field is required. | [optional]
**fromEmailType** | [**FromEmailTypeEnum**](#FromEmailTypeEnum) | The type of the email. |
**fromName** | **String** | The name of the email sender. | [optional]
**isHtml** | **Boolean** | Specifies whether the style of email body is HTML. The default value is false. | [optional]
**name** | **String** | The name of the email template, a unique name in a tenant. |
**replyToEmailAddress** | **String** | If replyToEmailType is SpecificEmail, this field is required. | [optional]
**replyToEmailType** | [**ReplyToEmailTypeEnum**](#ReplyToEmailTypeEnum) | Type of the replyTo email. | [optional]
**toEmailAddress** | **String** | If toEmailType is SpecificEmail, this field is required. | [optional]
**toEmailType** | [**ToEmailTypeEnum**](#ToEmailTypeEnum) | Email receive type. * When EventType is CDC/External and 'ReferenceObjectType' in EventType is associated to Account, toEmailType can be ALL values in enum. * When EventType is CDC/External and 'ReferenceObjectType' in EventType is not associated to Account, toEmailType MUST be TenantAdmin, RunOwner or SpecificEmail. * When EventType is CDC/External and 'ReferenceObjectType' in EventType is EMPTY, toEmailType MUST be TenantAdmin, RunOwner or SpecificEmail. |
<a name="CcEmailTypeEnum"></a>
## Enum: CcEmailTypeEnum
Name | Value
---- | -----
BILLTOCONTACT | "BillToContact"
SOLDTOCONTACT | "SoldToContact"
SPECIFICEMAILS | "SpecificEmails"
TENANTADMIN | "TenantAdmin"
BILLTOANDSOLDTOCONTACTS | "BillToAndSoldToContacts"
RUNOWNER | "RunOwner"
ALLCONTACTS | "AllContacts"
INVOICEOWNERBILLTOCONTACT | "InvoiceOwnerBillToContact"
INVOICEOWNERSOLDTOCONTACT | "InvoiceOwnerSoldToContact"
INVOICEOWNERBILLTOANDSOLDTOCONTACTS | "InvoiceOwnerBillToAndSoldToContacts"
INVOICEOWNERALLCONTACTS | "InvoiceOwnerAllContacts"
<a name="EncodingTypeEnum"></a>
## Enum: EncodingTypeEnum
Name | Value
---- | -----
UTF8 | "UTF8"
SHIFT_JIS | "Shift_JIS"
ISO_2022_JP | "ISO_2022_JP"
EUC_JP | "EUC_JP"
X_SJIS_0213 | "X_SJIS_0213"
<a name="FromEmailTypeEnum"></a>
## Enum: FromEmailTypeEnum
Name | Value
---- | -----
TENANTEMAIL | "TenantEmail"
SPECIFICEMAIL | "SpecificEmail"
<a name="ReplyToEmailTypeEnum"></a>
## Enum: ReplyToEmailTypeEnum
Name | Value
---- | -----
TENANTEMAIL | "TenantEmail"
SPECIFICEMAIL | "SpecificEmail"
<a name="ToEmailTypeEnum"></a>
## Enum: ToEmailTypeEnum
Name | Value
---- | -----
BILLTOCONTACT | "BillToContact"
SOLDTOCONTACT | "SoldToContact"
SPECIFICEMAILS | "SpecificEmails"
TENANTADMIN | "TenantAdmin"
BILLTOANDSOLDTOCONTACTS | "BillToAndSoldToContacts"
RUNOWNER | "RunOwner"
ALLCONTACTS | "AllContacts"
INVOICEOWNERBILLTOCONTACT | "InvoiceOwnerBillToContact"
INVOICEOWNERSOLDTOCONTACT | "InvoiceOwnerSoldToContact"
INVOICEOWNERBILLTOANDSOLDTOCONTACTS | "InvoiceOwnerBillToAndSoldToContacts"
INVOICEOWNERALLCONTACTS | "InvoiceOwnerAllContacts"
<file_sep>
# PreviewResultCreditMemos
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**amountWithoutTax** | [**BigDecimal**](BigDecimal.md) | | [optional]
**creditMemoItems** | [**List<InvoiceItemPreviewResult>**](InvoiceItemPreviewResult.md) | | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | | [optional]
**taxAmount** | [**BigDecimal**](BigDecimal.md) | | [optional]
<file_sep># ContactsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectDELETEContact**](ContactsApi.md#objectDELETEContact) | **DELETE** /v1/object/contact/{id} | CRUD: Delete Contact
[**objectGETContact**](ContactsApi.md#objectGETContact) | **GET** /v1/object/contact/{id} | CRUD: Retrieve Contact
[**objectPOSTContact**](ContactsApi.md#objectPOSTContact) | **POST** /v1/object/contact | CRUD: Create Contact
[**objectPUTContact**](ContactsApi.md#objectPUTContact) | **PUT** /v1/object/contact/{id} | CRUD: Update Contact
<a name="objectDELETEContact"></a>
# **objectDELETEContact**
> ProxyDeleteResponse objectDELETEContact(id, zuoraEntityIds, zuoraTrackId)
CRUD: Delete Contact
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ContactsApi;
ContactsApi apiInstance = new ContactsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyDeleteResponse result = apiInstance.objectDELETEContact(id, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ContactsApi#objectDELETEContact");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyDeleteResponse**](ProxyDeleteResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectGETContact"></a>
# **objectGETContact**
> ProxyGetContact objectGETContact(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Contact
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ContactsApi;
ContactsApi apiInstance = new ContactsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetContact result = apiInstance.objectGETContact(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ContactsApi#objectGETContact");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetContact**](ProxyGetContact.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTContact"></a>
# **objectPOSTContact**
> ProxyCreateOrModifyResponse objectPOSTContact(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create Contact
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ContactsApi;
ContactsApi apiInstance = new ContactsApi();
ProxyCreateContact createRequest = new ProxyCreateContact(); // ProxyCreateContact |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTContact(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ContactsApi#objectPOSTContact");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateContact**](ProxyCreateContact.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPUTContact"></a>
# **objectPUTContact**
> ProxyCreateOrModifyResponse objectPUTContact(id, modifyRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Update Contact
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ContactsApi;
ContactsApi apiInstance = new ContactsApi();
String id = "id_example"; // String | Object id
ProxyModifyContact modifyRequest = new ProxyModifyContact(); // ProxyModifyContact |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPUTContact(id, modifyRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ContactsApi#objectPUTContact");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**modifyRequest** | [**ProxyModifyContact**](ProxyModifyContact.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# OneTimePerUnitPricingOverride
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**listPrice** | [**BigDecimal**](BigDecimal.md) | Per-unit price of the charge. | [optional]
**quantity** | [**BigDecimal**](BigDecimal.md) | Number of units purchased. | [optional]
<file_sep># AccountingCodesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEAccountingCode**](AccountingCodesApi.md#dELETEAccountingCode) | **DELETE** /v1/accounting-codes/{ac-id} | Delete accounting code
[**gETAccountingCode**](AccountingCodesApi.md#gETAccountingCode) | **GET** /v1/accounting-codes/{ac-id} | Query an accounting code
[**gETAllAccountingCodes**](AccountingCodesApi.md#gETAllAccountingCodes) | **GET** /v1/accounting-codes | Get all accounting codes
[**pOSTAccountingCode**](AccountingCodesApi.md#pOSTAccountingCode) | **POST** /v1/accounting-codes | Create accounting code
[**pUTAccountingCode**](AccountingCodesApi.md#pUTAccountingCode) | **PUT** /v1/accounting-codes/{ac-id} | Update an accounting code
[**pUTActivateAccountingCode**](AccountingCodesApi.md#pUTActivateAccountingCode) | **PUT** /v1/accounting-codes/{ac-id}/activate | Activate accounting code
[**pUTDeactivateAccountingCode**](AccountingCodesApi.md#pUTDeactivateAccountingCode) | **PUT** /v1/accounting-codes/{ac-id}/deactivate | Deactivate accounting code
<a name="dELETEAccountingCode"></a>
# **dELETEAccountingCode**
> CommonResponseType dELETEAccountingCode(acId, zuoraEntityIds)
Delete accounting code
This reference describes how to delete an accounting code through the REST API. ## Prerequisites If you have Zuora Finance enabled on your tenant, then you must have the Delete Unused Accounting Code permission. ## Limitations You can only delete accounting codes that have never been associated with any transactions. An accounting code must be deactivated before you can delete it.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountingCodesApi;
AccountingCodesApi apiInstance = new AccountingCodesApi();
String acId = "acId_example"; // String | ID of the accounting code you want to delete.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETEAccountingCode(acId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#dELETEAccountingCode");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**acId** | **String**| ID of the accounting code you want to delete. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAccountingCode"></a>
# **gETAccountingCode**
> GETAccountingCodeItemType gETAccountingCode(acId, zuoraEntityIds)
Query an accounting code
This reference describes how to query an accounting code through the REST API.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountingCodesApi;
AccountingCodesApi apiInstance = new AccountingCodesApi();
String acId = "acId_example"; // String | ID of the accounting code you want to query.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETAccountingCodeItemType result = apiInstance.gETAccountingCode(acId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#gETAccountingCode");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**acId** | **String**| ID of the accounting code you want to query. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETAccountingCodeItemType**](GETAccountingCodeItemType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETAllAccountingCodes"></a>
# **gETAllAccountingCodes**
> GETAccountingCodesType gETAllAccountingCodes(zuoraEntityIds, pageSize)
Get all accounting codes
This reference describes how to query all accounting codes in your chart of accounts through the REST API.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountingCodesApi;
AccountingCodesApi apiInstance = new AccountingCodesApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 300; // Integer | Number of rows returned per page.
try {
GETAccountingCodesType result = apiInstance.gETAllAccountingCodes(zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#gETAllAccountingCodes");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 300]
### Return type
[**GETAccountingCodesType**](GETAccountingCodesType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTAccountingCode"></a>
# **pOSTAccountingCode**
> POSTAccountingCodeResponseType pOSTAccountingCode(request, zuoraEntityIds)
Create accounting code
This reference describes how to create a new accounting code through the REST API. The accounting code will be active as soon as it has been created. ## Prerequisites If you have Zuora Finance enabled on your tenant, you must have the Configure Accounting Codes permission.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountingCodesApi;
AccountingCodesApi apiInstance = new AccountingCodesApi();
POSTAccountingCodeType request = new POSTAccountingCodeType(); // POSTAccountingCodeType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTAccountingCodeResponseType result = apiInstance.pOSTAccountingCode(request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#pOSTAccountingCode");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**request** | [**POSTAccountingCodeType**](POSTAccountingCodeType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTAccountingCodeResponseType**](POSTAccountingCodeResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTAccountingCode"></a>
# **pUTAccountingCode**
> CommonResponseType pUTAccountingCode(acId, request, zuoraEntityIds)
Update an accounting code
This reference describes how to update an existing accounting code through the REST API. ## Prerequisites If you have Zuora Finance enabled on your tenant, you must have the Manage Accounting Code permission. ## Limitations You can only update accounting codes that are not already associated with any transactions.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountingCodesApi;
AccountingCodesApi apiInstance = new AccountingCodesApi();
String acId = "acId_example"; // String | ID of the accounting code you want to update.
PUTAccountingCodeType request = new PUTAccountingCodeType(); // PUTAccountingCodeType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTAccountingCode(acId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#pUTAccountingCode");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**acId** | **String**| ID of the accounting code you want to update. |
**request** | [**PUTAccountingCodeType**](PUTAccountingCodeType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTActivateAccountingCode"></a>
# **pUTActivateAccountingCode**
> CommonResponseType pUTActivateAccountingCode(acId, zuoraEntityIds)
Activate accounting code
This reference describes how to activate an accounting code through the REST API. Prerequisites ------------- If you have Zuora Finance enabled on your tenant, you must have the Manage Accounting Code permission.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountingCodesApi;
AccountingCodesApi apiInstance = new AccountingCodesApi();
String acId = "acId_example"; // String | ID of the accounting code you want to activate.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTActivateAccountingCode(acId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#pUTActivateAccountingCode");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**acId** | **String**| ID of the accounting code you want to activate. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTDeactivateAccountingCode"></a>
# **pUTDeactivateAccountingCode**
> CommonResponseType pUTDeactivateAccountingCode(acId, zuoraEntityIds)
Deactivate accounting code
This reference describes how to deactivate an accounting code through the REST API. ## Prerequisites If you have Zuora Finance enabled on your tenant, you must have the Manage Accounting Code permission. ## Limitations You can only deactivate accounting codes that are not associated with any transactions. You cannot disable accounting codes of type AccountsReceivable.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.AccountingCodesApi;
AccountingCodesApi apiInstance = new AccountingCodesApi();
String acId = "acId_example"; // String | ID of the accounting code you want to deactivate.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTDeactivateAccountingCode(acId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AccountingCodesApi#pUTDeactivateAccountingCode");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**acId** | **String**| ID of the accounting code you want to deactivate. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# InvoiceProcessingOptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoiceDate** | [**LocalDate**](LocalDate.md) | The invoice date. | [optional]
**invoiceTargetDate** | [**LocalDate**](LocalDate.md) | The date that determines which charges to bill. Charges prior to this date or on this date are billed on the resulting invoices. |
<file_sep>
# PUTWriteOffInvoiceRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**memoDate** | [**LocalDate**](LocalDate.md) | The date when the credit memo was created, in `yyyy-mm-dd` format. The memo date must be later than or equal to the invoice date. The default value is the date when you write off the invoice. | [optional]
<file_sep>
# PostOrderResponseTypeSubscriptions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**status** | [**StatusEnum**](#StatusEnum) | Status of the subscription. `Pending Activation` and `Pending Acceptance` are only applicable for an order that contains a `CreateSubscription` order action. | [optional]
**subscriptionNumber** | **String** | Subscription number of the subscription included in this order. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
ACTIVE | "Active"
PENDING_ACTIVATION | "Pending Activation"
PENDING_ACCEPTANCE | "Pending Acceptance"
CANCELLED | "Cancelled"
<file_sep># ExportsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**objectGETExport**](ExportsApi.md#objectGETExport) | **GET** /v1/object/export/{id} | CRUD: Retrieve Export
[**objectPOSTExport**](ExportsApi.md#objectPOSTExport) | **POST** /v1/object/export | CRUD: Create Export
<a name="objectGETExport"></a>
# **objectGETExport**
> ProxyGetExport objectGETExport(id, zuoraEntityIds, zuoraTrackId, fields)
CRUD: Retrieve Export
Use this operation to check the status of a data source export and access the exported data. When you export data from Zuora, each exported file is available for download for 7 days. Data source exports (Export objects) older than 90 days are automatically deleted.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ExportsApi;
ExportsApi apiInstance = new ExportsApi();
String id = "id_example"; // String | Object id
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String fields = "fields_example"; // String | Object fields to return
try {
ProxyGetExport result = apiInstance.objectGETExport(id, zuoraEntityIds, zuoraTrackId, fields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ExportsApi#objectGETExport");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| Object id |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**fields** | **String**| Object fields to return | [optional]
### Return type
[**ProxyGetExport**](ProxyGetExport.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="objectPOSTExport"></a>
# **objectPOSTExport**
> ProxyCreateOrModifyResponse objectPOSTExport(createRequest, zuoraEntityIds, zuoraTrackId)
CRUD: Create Export
Use this operation to create a data source export. After you have created a data source export, use [CRUD: Retrieve Export](https://www.zuora.com/developer/api-reference/#operation/Object_GETExport) to check the status of the data source export and access the exported data. When you export data from Zuora, each exported file is available for download for 7 days. Data source exports (Export objects) older than 90 days are automatically deleted.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.ExportsApi;
ExportsApi apiInstance = new ExportsApi();
ProxyCreateExport createRequest = new ProxyCreateExport(); // ProxyCreateExport |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
try {
ProxyCreateOrModifyResponse result = apiInstance.objectPOSTExport(createRequest, zuoraEntityIds, zuoraTrackId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ExportsApi#objectPOSTExport");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRequest** | [**ProxyCreateExport**](ProxyCreateExport.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
### Return type
[**ProxyCreateOrModifyResponse**](ProxyCreateOrModifyResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># CatalogApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETCatalog**](CatalogApi.md#gETCatalog) | **GET** /v1/catalog/products | Get product catalog
[**gETProduct**](CatalogApi.md#gETProduct) | **GET** /v1/catalog/product/{product-id} | Get product
[**pOSTCatalog**](CatalogApi.md#pOSTCatalog) | **POST** /v1/catalog/products/{product-id}/share | Multi-entity: Share a product with an Entity
<a name="gETCatalog"></a>
# **gETCatalog**
> GETCatalogType gETCatalog(zuoraEntityIds, pageSize, zuoraVersion)
Get product catalog
Retrieves the entire product catalog, including all products, features, and their corresponding rate plans, charges. Products are returned in reverse chronological order on the UpdatedDate field. With rate plans and rate plan charges, the REST API has a maximum array size.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.CatalogApi;
CatalogApi apiInstance = new CatalogApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 10; // Integer | Number of rows returned per page.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the `productRatePlans` field.
try {
GETCatalogType result = apiInstance.gETCatalog(zuoraEntityIds, pageSize, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling CatalogApi#gETCatalog");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 10]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the `productRatePlans` field. | [optional]
### Return type
[**GETCatalogType**](GETCatalogType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETProduct"></a>
# **gETProduct**
> GETProductType gETProduct(productId, zuoraEntityIds, zuoraVersion)
Get product
Retrieves detailed information about a specific product, including information about its product rate plans and charges.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.CatalogApi;
CatalogApi apiInstance = new CatalogApi();
String productId = "productId_example"; // String | The unique ID of the product you want to retrieve. For example, 8a808255575bdae4015774e9602e16fe.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
String zuoraVersion = "zuoraVersion_example"; // String | The minor version of the Zuora REST API. You only need to set this parameter if you use the `productRatePlans` field.
try {
GETProductType result = apiInstance.gETProduct(productId, zuoraEntityIds, zuoraVersion);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling CatalogApi#gETProduct");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**productId** | **String**| The unique ID of the product you want to retrieve. For example, 8a808255575bdae4015774e9602e16fe. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**zuoraVersion** | **String**| The minor version of the Zuora REST API. You only need to set this parameter if you use the `productRatePlans` field. | [optional]
### Return type
[**GETProductType**](GETProductType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTCatalog"></a>
# **pOSTCatalog**
> CommonResponseType pOSTCatalog(productId, request, zuoraEntityIds)
Multi-entity: Share a product with an Entity
**Note:** The Multi-entity feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Shares a product with a target entity. Zuora synchronizes the shared products to the target entity after sharing. For more information about product sharing, see [Products Sharing Across Entities](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity/C_Business_Objects_Sharing_Across_Entities/B_Products_Sharing_Across_Entities). Note that: - You must finish all the [prerequisites](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity/C_Business_Objects_Sharing_Across_Entities/B_Products_Sharing_Across_Entities/Share_Products) before sharing products with other entities. - Only source entity administrators have permission to share products with other entities. You must make the call as a source entity administrator. - Currently, you can only share a product with one entity at a time. An error occurs if you try to share a product to more than one entity.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.CatalogApi;
CatalogApi apiInstance = new CatalogApi();
String productId = "productId_example"; // String | The unique ID of the product you want to share. For example, 8a808255575bdae4015774e9602e16fe.
POSTCatalogType request = new POSTCatalogType(); // POSTCatalogType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pOSTCatalog(productId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling CatalogApi#pOSTCatalog");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**productId** | **String**| The unique ID of the product you want to share. For example, 8a808255575bdae4015774e9602e16fe. |
**request** | [**POSTCatalogType**](POSTCatalogType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# SubscriptionObjectNSFields
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the subscription's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**projectNS** | **String** | The NetSuite project that the subscription was created from. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**salesOrderNS** | **String** | The NetSuite sales order than the subscription was created from. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the subscription was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
<file_sep>
# ProxyModifyInvoiceAdjustment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**reasonCode** | **String** | A code identifying the reason for the transaction. Must be an existing reason code or empty. If you do not specify a value, Zuora uses the default reason code. **Character limit**: 32 **V****alues**: a valid reason code | [optional]
**status** | **String** | The status of the invoice adjustment. This field is required in the Query call, but is automatically generated in other calls. **Character limit**: 9 **Values**: `Canceled`, `Processed` | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Indicates the status of the adjustment's transfer to an external accounting system, such as NetSuite. | [optional]
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
NO | "No"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.ProxyGetSubscriptionProductFeature;
import de.keylight.zuora.client.model.ProxyNoDataResponse;
import de.keylight.zuora.client.model.ProxyUnauthorizedResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.SubscriptionProductFeaturesApi")
public class SubscriptionProductFeaturesApi {
private ApiClient apiClient;
public SubscriptionProductFeaturesApi() {
this(new ApiClient());
}
@Autowired
public SubscriptionProductFeaturesApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* CRUD: Retrieve SubscriptionProductFeature
*
* <p><b>200</b> -
* <p><b>401</b> -
* <p><b>404</b> -
* @param id Object id
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param zuoraTrackId A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
* @param fields Object fields to return
* @return ProxyGetSubscriptionProductFeature
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ProxyGetSubscriptionProductFeature objectGETSubscriptionProductFeature(String id, String zuoraEntityIds, String zuoraTrackId, String fields) throws RestClientException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling objectGETSubscriptionProductFeature");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", id);
String path = UriComponentsBuilder.fromPath("/v1/object/subscription-product-feature/{id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "fields", fields));
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
if (zuoraTrackId != null)
headerParams.add("Zuora-Track-Id", apiClient.parameterToString(zuoraTrackId));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<ProxyGetSubscriptionProductFeature> returnType = new ParameterizedTypeReference<ProxyGetSubscriptionProductFeature>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep># NotificationsApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETEDeleteEmailTemplate**](NotificationsApi.md#dELETEDeleteEmailTemplate) | **DELETE** /notifications/email-templates/{id} | Delete an email template
[**dELETEDeleteNotificationDefinition**](NotificationsApi.md#dELETEDeleteNotificationDefinition) | **DELETE** /notifications/notification-definitions/{id} | Delete a notification definition
[**gETCalloutHistory**](NotificationsApi.md#gETCalloutHistory) | **GET** /v1/notification-history/callout | Get callout notification histories
[**gETEmailHistory**](NotificationsApi.md#gETEmailHistory) | **GET** /v1/notification-history/email | Get email notification histories
[**gETGetEmailTemplate**](NotificationsApi.md#gETGetEmailTemplate) | **GET** /notifications/email-templates/{id} | Get an email template
[**gETGetNotificationDefinition**](NotificationsApi.md#gETGetNotificationDefinition) | **GET** /notifications/notification-definitions/{id} | Get a notification definition
[**gETQueryEmailTemplates**](NotificationsApi.md#gETQueryEmailTemplates) | **GET** /notifications/email-templates | Query email templates
[**gETQueryNotificationDefinitions**](NotificationsApi.md#gETQueryNotificationDefinitions) | **GET** /notifications/notification-definitions | Query notification definitions
[**pOSTCreateEmailTemplate**](NotificationsApi.md#pOSTCreateEmailTemplate) | **POST** /notifications/email-templates | Create an email template
[**pOSTCreateNotificationDefinition**](NotificationsApi.md#pOSTCreateNotificationDefinition) | **POST** /notifications/notification-definitions | Create a notification definition
[**pUTUpdateEmailTemplate**](NotificationsApi.md#pUTUpdateEmailTemplate) | **PUT** /notifications/email-templates/{id} | Update an email template
[**pUTUpdateNotificationDefinition**](NotificationsApi.md#pUTUpdateNotificationDefinition) | **PUT** /notifications/notification-definitions/{id} | Update a notification definition
<a name="dELETEDeleteEmailTemplate"></a>
# **dELETEDeleteEmailTemplate**
> dELETEDeleteEmailTemplate(authorization, id, zuoraTrackId, zuoraEntityIds)
Delete an email template
Deletes an email template.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID | The ID of the email template to be deleted.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
apiInstance.dELETEDeleteEmailTemplate(authorization, id, zuoraTrackId, zuoraEntityIds);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#dELETEDeleteEmailTemplate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| The ID of the email template to be deleted. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="dELETEDeleteNotificationDefinition"></a>
# **dELETEDeleteNotificationDefinition**
> dELETEDeleteNotificationDefinition(authorization, id, zuoraTrackId, zuoraEntityIds)
Delete a notification definition
Deletes a notification definition.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID | The ID of the notification definition to be deleted.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
apiInstance.dELETEDeleteNotificationDefinition(authorization, id, zuoraTrackId, zuoraEntityIds);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#dELETEDeleteNotificationDefinition");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| The ID of the notification definition to be deleted. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETCalloutHistory"></a>
# **gETCalloutHistory**
> GETCalloutHistoryVOsType gETCalloutHistory(zuoraEntityIds, pageSize, endTime, startTime, objectId, failedOnly, eventCategory, includeResponseContent)
Get callout notification histories
This REST API reference describes how to get a notification history for callouts.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
OffsetDateTime endTime = new OffsetDateTime(); // OffsetDateTime | The final date and time of records to be returned. Defaults to now. Use format yyyy-MM-ddTHH:mm:ss.
OffsetDateTime startTime = new OffsetDateTime(); // OffsetDateTime | The initial date and time of records to be returned. Defaults to (end time - 1 day). Use format yyyy-MM-ddTHH:mm:ss.
String objectId = "objectId_example"; // String | The ID of an object that triggered a callout notification.
Boolean failedOnly = true; // Boolean | If `true`, only return failed records. If `false`, return all records in the given date range. The default value is `true`.
String eventCategory = "eventCategory_example"; // String | Category of records to be returned by event category.
Boolean includeResponseContent = true; // Boolean |
try {
GETCalloutHistoryVOsType result = apiInstance.gETCalloutHistory(zuoraEntityIds, pageSize, endTime, startTime, objectId, failedOnly, eventCategory, includeResponseContent);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#gETCalloutHistory");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**endTime** | **OffsetDateTime**| The final date and time of records to be returned. Defaults to now. Use format yyyy-MM-ddTHH:mm:ss. | [optional]
**startTime** | **OffsetDateTime**| The initial date and time of records to be returned. Defaults to (end time - 1 day). Use format yyyy-MM-ddTHH:mm:ss. | [optional]
**objectId** | **String**| The ID of an object that triggered a callout notification. | [optional]
**failedOnly** | **Boolean**| If `true`, only return failed records. If `false`, return all records in the given date range. The default value is `true`. | [optional]
**eventCategory** | **String**| Category of records to be returned by event category. | [optional]
**includeResponseContent** | **Boolean**| | [optional]
### Return type
[**GETCalloutHistoryVOsType**](GETCalloutHistoryVOsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETEmailHistory"></a>
# **gETEmailHistory**
> GETEmailHistoryVOsType gETEmailHistory(zuoraEntityIds, pageSize, endTime, startTime, objectId, failedOnly, eventCategory)
Get email notification histories
This REST API reference describes how to get a notification history for notification emails. ## Notes Request parameters and their values may be appended with a \"?\" following the HTTPS GET request. Additional request parameter are separated by \"&\". For example: `GET https://rest.zuora.com/v1/notification-history/email?startTime=2015-01-12T00:00:00&endTime=2015-01-15T00:00:00&failedOnly=false&eventCategory=1000&pageSize=1`
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 20; // Integer | Number of rows returned per page.
OffsetDateTime endTime = new OffsetDateTime(); // OffsetDateTime | The end date and time of records to be returned. Defaults to now. Use format yyyy-MM-ddTHH:mm:ss. The maximum date range (endTime - startTime) is three days.
OffsetDateTime startTime = new OffsetDateTime(); // OffsetDateTime | The initial date and time of records to be returned. Defaults to (end time - 1 day). Use format yyyy-MM-ddTHH:mm:ss. The maximum date range (endTime - startTime) is three days.
String objectId = "objectId_example"; // String | The Id of an object that triggered an email notification.
Boolean failedOnly = true; // Boolean | If `true`, only returns failed records. When `false`, returns all records in the given date range. Defaults to `true` when not specified.
String eventCategory = "eventCategory_example"; // String | Category of records to be returned by event category.
try {
GETEmailHistoryVOsType result = apiInstance.gETEmailHistory(zuoraEntityIds, pageSize, endTime, startTime, objectId, failedOnly, eventCategory);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#gETEmailHistory");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 20]
**endTime** | **OffsetDateTime**| The end date and time of records to be returned. Defaults to now. Use format yyyy-MM-ddTHH:mm:ss. The maximum date range (endTime - startTime) is three days. | [optional]
**startTime** | **OffsetDateTime**| The initial date and time of records to be returned. Defaults to (end time - 1 day). Use format yyyy-MM-ddTHH:mm:ss. The maximum date range (endTime - startTime) is three days. | [optional]
**objectId** | **String**| The Id of an object that triggered an email notification. | [optional]
**failedOnly** | **Boolean**| If `true`, only returns failed records. When `false`, returns all records in the given date range. Defaults to `true` when not specified. | [optional]
**eventCategory** | **String**| Category of records to be returned by event category. | [optional]
### Return type
[**GETEmailHistoryVOsType**](GETEmailHistoryVOsType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETGetEmailTemplate"></a>
# **gETGetEmailTemplate**
> GETPublicEmailTemplateResponse gETGetEmailTemplate(authorization, id, zuoraTrackId, zuoraEntityIds)
Get an email template
Queries the email template of the specified ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID | The ID of the email template.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPublicEmailTemplateResponse result = apiInstance.gETGetEmailTemplate(authorization, id, zuoraTrackId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#gETGetEmailTemplate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| The ID of the email template. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPublicEmailTemplateResponse**](GETPublicEmailTemplateResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETGetNotificationDefinition"></a>
# **gETGetNotificationDefinition**
> GETPublicNotificationDefinitionResponse gETGetNotificationDefinition(authorization, id, zuoraTrackId, zuoraEntityIds)
Get a notification definition
Queries the notification definition of the given ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID | The ID of the notification definition.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPublicNotificationDefinitionResponse result = apiInstance.gETGetNotificationDefinition(authorization, id, zuoraTrackId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#gETGetNotificationDefinition");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| The ID of the notification definition. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPublicNotificationDefinitionResponse**](GETPublicNotificationDefinitionResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETQueryEmailTemplates"></a>
# **gETQueryEmailTemplates**
> InlineResponse2003 gETQueryEmailTemplates(authorization, zuoraTrackId, zuoraEntityIds, start, limit, eventTypeName, name)
Query email templates
Queries email templates.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer start = 1; // Integer | The first index of the query result.
Integer limit = 20; // Integer | The maximum number of results the query should return.
String eventTypeName = "eventTypeName_example"; // String | The name of the event.
String name = "name_example"; // String | The name of the email template.
try {
InlineResponse2003 result = apiInstance.gETQueryEmailTemplates(authorization, zuoraTrackId, zuoraEntityIds, start, limit, eventTypeName, name);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#gETQueryEmailTemplates");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**start** | **Integer**| The first index of the query result. | [optional] [default to 1]
**limit** | **Integer**| The maximum number of results the query should return. | [optional] [default to 20]
**eventTypeName** | **String**| The name of the event. | [optional]
**name** | **String**| The name of the email template. | [optional]
### Return type
[**InlineResponse2003**](InlineResponse2003.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETQueryNotificationDefinitions"></a>
# **gETQueryNotificationDefinitions**
> InlineResponse2002 gETQueryNotificationDefinitions(authorization, zuoraTrackId, zuoraEntityIds, start, limit, profileId, eventTypeName, emailTemplateId)
Query notification definitions
Queries notification definitions with the specified filters.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer start = 1; // Integer | The first index of the query result.
Integer limit = 20; // Integer | The maximum number of results the query should return.
UUID profileId = new UUID(); // UUID | Id of the profile.
String eventTypeName = "eventTypeName_example"; // String | The name of the event.
UUID emailTemplateId = new UUID(); // UUID | The ID of the email template.
try {
InlineResponse2002 result = apiInstance.gETQueryNotificationDefinitions(authorization, zuoraTrackId, zuoraEntityIds, start, limit, profileId, eventTypeName, emailTemplateId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#gETQueryNotificationDefinitions");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**start** | **Integer**| The first index of the query result. | [optional] [default to 1]
**limit** | **Integer**| The maximum number of results the query should return. | [optional] [default to 20]
**profileId** | [**UUID**](.md)| Id of the profile. | [optional]
**eventTypeName** | **String**| The name of the event. | [optional]
**emailTemplateId** | [**UUID**](.md)| The ID of the email template. | [optional]
### Return type
[**InlineResponse2002**](InlineResponse2002.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTCreateEmailTemplate"></a>
# **pOSTCreateEmailTemplate**
> GETPublicEmailTemplateResponse pOSTCreateEmailTemplate(authorization, poSTPublicEmailTemplateRequest, zuoraTrackId, zuoraEntityIds)
Create an email template
Creates an email template.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
POSTPublicEmailTemplateRequest poSTPublicEmailTemplateRequest = new POSTPublicEmailTemplateRequest(); // POSTPublicEmailTemplateRequest | The request body to create an email template.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPublicEmailTemplateResponse result = apiInstance.pOSTCreateEmailTemplate(authorization, poSTPublicEmailTemplateRequest, zuoraTrackId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#pOSTCreateEmailTemplate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**poSTPublicEmailTemplateRequest** | [**POSTPublicEmailTemplateRequest**](POSTPublicEmailTemplateRequest.md)| The request body to create an email template. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPublicEmailTemplateResponse**](GETPublicEmailTemplateResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTCreateNotificationDefinition"></a>
# **pOSTCreateNotificationDefinition**
> GETPublicNotificationDefinitionResponse pOSTCreateNotificationDefinition(authorization, entity, zuoraTrackId, zuoraEntityIds)
Create a notification definition
Creates a notification definition. If a filter rule is specified, it will be evaluated to see if the notification definition is qualified to handle the incoming events during runtime. If the notification is qualified, it will send the email and invoke the callout if it has an email template or a callout.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
POSTPublicNotificationDefinitionRequest entity = new POSTPublicNotificationDefinitionRequest(); // POSTPublicNotificationDefinitionRequest | The request body used to create the notification definition.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPublicNotificationDefinitionResponse result = apiInstance.pOSTCreateNotificationDefinition(authorization, entity, zuoraTrackId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#pOSTCreateNotificationDefinition");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**entity** | [**POSTPublicNotificationDefinitionRequest**](POSTPublicNotificationDefinitionRequest.md)| The request body used to create the notification definition. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPublicNotificationDefinitionResponse**](GETPublicNotificationDefinitionResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUpdateEmailTemplate"></a>
# **pUTUpdateEmailTemplate**
> GETPublicEmailTemplateResponse pUTUpdateEmailTemplate(authorization, id, puTPublicEmailTemplateRequest, zuoraTrackId, zuoraEntityIds)
Update an email template
Updates an email template.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID | The ID of the email template to be updated.
PUTPublicEmailTemplateRequest puTPublicEmailTemplateRequest = new PUTPublicEmailTemplateRequest(); // PUTPublicEmailTemplateRequest | The request body to update an email template.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPublicEmailTemplateResponse result = apiInstance.pUTUpdateEmailTemplate(authorization, id, puTPublicEmailTemplateRequest, zuoraTrackId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#pUTUpdateEmailTemplate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| The ID of the email template to be updated. |
**puTPublicEmailTemplateRequest** | [**PUTPublicEmailTemplateRequest**](PUTPublicEmailTemplateRequest.md)| The request body to update an email template. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPublicEmailTemplateResponse**](GETPublicEmailTemplateResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTUpdateNotificationDefinition"></a>
# **pUTUpdateNotificationDefinition**
> GETPublicNotificationDefinitionResponse pUTUpdateNotificationDefinition(authorization, id, puTPublicNotificationDefinitionRequest, zuoraTrackId, zuoraEntityIds)
Update a notification definition
Updates a notification definition.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.NotificationsApi;
NotificationsApi apiInstance = new NotificationsApi();
String authorization = "authorization_example"; // String | `Bearer {token}` for a valid OAuth token.
UUID id = new UUID(); // UUID | The ID of the notification definition to be updated.
PUTPublicNotificationDefinitionRequest puTPublicNotificationDefinitionRequest = new PUTPublicNotificationDefinitionRequest(); // PUTPublicNotificationDefinitionRequest | The request body of the notification definition to be updated.
String zuoraTrackId = "zuoraTrackId_example"; // String | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`).
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETPublicNotificationDefinitionResponse result = apiInstance.pUTUpdateNotificationDefinition(authorization, id, puTPublicNotificationDefinitionRequest, zuoraTrackId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NotificationsApi#pUTUpdateNotificationDefinition");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**authorization** | **String**| `Bearer {token}` for a valid OAuth token. |
**id** | [**UUID**](.md)| The ID of the notification definition to be updated. |
**puTPublicNotificationDefinitionRequest** | [**PUTPublicNotificationDefinitionRequest**](PUTPublicNotificationDefinitionRequest.md)| The request body of the notification definition to be updated. |
**zuoraTrackId** | **String**| A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). | [optional]
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETPublicNotificationDefinitionResponse**](GETPublicNotificationDefinitionResponse.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# Contact
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**address1** | **String** | First line of the contact's address. This is often a street address or a business name. | [optional]
**address2** | **String** | Second line of the contact's address. | [optional]
**city** | **String** | City of the contact's address. | [optional]
**country** | **String** | Country of the contact's address. | [optional]
**county** | **String** | County of the contact's address. | [optional]
**fax** | **String** | Fax number of the contact. | [optional]
**firstName** | **String** | First name of the contact. |
**homePhone** | **String** | Home phone number of the contact. | [optional]
**lastName** | **String** | Last name of the contact. |
**mobilePhone** | **String** | Mobile phone number of the contact. | [optional]
**nickname** | **String** | Nickname of the contact. | [optional]
**otherPhone** | **String** | Additional phone number of the contact. Use the `otherPhoneType` field to specify the type of phone number. | [optional]
**otherPhoneType** | [**OtherPhoneTypeEnum**](#OtherPhoneTypeEnum) | Specifies the type of phone number in the `otherPhone` field. | [optional]
**personalEmail** | **String** | Personal email address of the contact. | [optional]
**postalCode** | **String** | ZIP code or other postal code of the contact's address. | [optional]
**state** | **String** | State or province of the contact's address. | [optional]
**taxRegion** | **String** | Region defined in your taxation rules. Only applicable if you use Zuora Tax. | [optional]
**workEmail** | **String** | Business email address of the contact. | [optional]
**workPhone** | **String** | Business phone number of the contact. | [optional]
<a name="OtherPhoneTypeEnum"></a>
## Enum: OtherPhoneTypeEnum
Name | Value
---- | -----
WORK | "Work"
MOBILE | "Mobile"
HOME | "Home"
OTHER | "Other"
<file_sep>
# GETAccountSummaryPaymentInvoiceType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**appliedPaymentAmount** | **String** | Amount of payment applied to the invoice. | [optional]
**invoiceId** | **String** | Invoice ID. | [optional]
**invoiceNumber** | **String** | Invoice number. | [optional]
<file_sep>
# UnapplyCreditMemoType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**debitMemos** | [**List<CreditMemoUnapplyDebitMemoRequestType>**](CreditMemoUnapplyDebitMemoRequestType.md) | Container for debit memos that the credit memo is unapplied from. | [optional]
**effectiveDate** | [**LocalDate**](LocalDate.md) | The date when the credit memo is unapplied. | [optional]
**invoices** | [**List<CreditMemoUnapplyInvoiceRequestType>**](CreditMemoUnapplyInvoiceRequestType.md) | Container for invoices that the credit memo is unapplied from. | [optional]
<file_sep>
# POSTAccountingPeriodType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**endDate** | [**LocalDate**](LocalDate.md) | The end date of the accounting period in yyyy-mm-dd format, for example, \"2016-02-19\". |
**fiscalYear** | **String** | Fiscal year of the accounting period in yyyy format, for example, \"2016\". |
**fiscalQuarter** | **Long** | | [optional]
**name** | **String** | Name of the accounting period. Accounting period name must be unique. Maximum of 100 characters. |
**notes** | **String** | Notes about the accounting period. Maximum of 255 characters. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The start date of the accounting period in yyyy-mm-dd format, for example, \"2016-02-19\". |
<file_sep>
# ChargePreviewMetricsCmrr
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**discount** | [**BigDecimal**](BigDecimal.md) | Total discountCmrr of all discount charges which are applied to one specific recurring charge. This value is calculated from the rating results for the latest subscription version in the order. Only selects the applied discount charge when its endDateCondition is \"Subscription_End\". | [optional]
**discountDelta** | [**BigDecimal**](BigDecimal.md) | Delta discountCmrr value between the order base and the latest subscription version. | [optional]
**regular** | [**BigDecimal**](BigDecimal.md) | | [optional]
**regularDelta** | [**BigDecimal**](BigDecimal.md) | | [optional]
<file_sep>
# POSTPaymentMethodResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | Indicates whether the call succeeded. | [optional]
**id** | **String** | Internal ID of the payment method that was created. | [optional]
**reasons** | [**List<POSTPaymentMethodResponseReasons>**](POSTPaymentMethodResponseReasons.md) | | [optional]
<file_sep>
# InvoicePayment
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | **String** | The amount of the payment to apply to an invoice. |
**invoiceId** | **String** | The ID of the invoice that the payment is applied to. |
**paymentId** | **String** | The ID of the payment. | [optional]
<file_sep>
# ChargeOverrideBilling
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**billCycleDay** | **Integer** | Day of the month that each billing period begins on. Only applicable if the value of the `billCycleType` field is `SpecificDayofMonth`. | [optional]
**billCycleType** | [**BillCycleTypeEnum**](#BillCycleTypeEnum) | Specifies how Zuora determines the day that each billing period begins on. * `DefaultFromCustomer` - Each billing period begins on the bill cycle day of the account that owns the subscription. * `SpecificDayofMonth` - Use the `billCycleDay` field to specify the day of the month that each billing period begins on. * `SubscriptionStartDay` - Each billing period begins on the same day of the month as the start date of the subscription. * `ChargeTriggerDay` - Each billing period begins on the same day of the month as the date when the charge becomes active. * `SpecificDayofWeek` - Use the `weeklyBillCycleDay` field to specify the day of the week that each billing period begins on. | [optional]
**billingPeriod** | [**BillingPeriodEnum**](#BillingPeriodEnum) | Billing frequency of the charge. The value of this field controls the duration of each billing period. If the value of this field is `Specific_Months` or `Specific_Weeks`, use the `specificBillingPeriod` field to specify the duration of each billing period. | [optional]
**billingPeriodAlignment** | [**BillingPeriodAlignmentEnum**](#BillingPeriodAlignmentEnum) | Specifies how Zuora determines when to start new billing periods. You can use this field to align the billing periods of different charges. * `AlignToCharge` - Zuora starts a new billing period on the first billing day that falls on or after the date when the charge becomes active. * `AlignToSubscriptionStart` - Zuora starts a new billing period on the first billing day that falls on or after the start date of the subscription. * `AlignToTermStart` - For each term of the subscription, Zuora starts a new billing period on the first billing day that falls on or after the start date of the term. See the `billCycleType` field for information about how Zuora determines the billing day. | [optional]
**billingTiming** | [**BillingTimingEnum**](#BillingTimingEnum) | Specifies whether to invoice for a billing period on the first day of the billing period (billing in advance) or the first day of the next billing period (billing in arrears). | [optional]
**specificBillingPeriod** | **Integer** | Duration of each billing period in months or weeks, depending on the value of the `billingPeriod` field. Only applicable if the value of the `billingPeriod` field is `Specific_Months` or `Specific_Weeks`. | [optional]
**weeklyBillCycleDay** | [**WeeklyBillCycleDayEnum**](#WeeklyBillCycleDayEnum) | Day of the week that each billing period begins on. Only applicable if the value of the `billCycleType` field is `SpecificDayofWeek`. | [optional]
<a name="BillCycleTypeEnum"></a>
## Enum: BillCycleTypeEnum
Name | Value
---- | -----
DEFAULTFROMCUSTOMER | "DefaultFromCustomer"
SPECIFICDAYOFMONTH | "SpecificDayofMonth"
SUBSCRIPTIONSTARTDAY | "SubscriptionStartDay"
CHARGETRIGGERDAY | "ChargeTriggerDay"
SPECIFICDAYOFWEEK | "SpecificDayofWeek"
<a name="BillingPeriodEnum"></a>
## Enum: BillingPeriodEnum
Name | Value
---- | -----
MONTH | "Month"
QUARTER | "Quarter"
SEMI_ANNUAL | "Semi_Annual"
ANNUAL | "Annual"
EIGHTEEN_MONTHS | "Eighteen_Months"
TWO_YEARS | "Two_Years"
THREE_YEARS | "Three_Years"
FIVE_YEARS | "Five_Years"
SPECIFIC_MONTHS | "Specific_Months"
SUBSCRIPTION_TERM | "Subscription_Term"
WEEK | "Week"
SPECIFIC_WEEKS | "Specific_Weeks"
<a name="BillingPeriodAlignmentEnum"></a>
## Enum: BillingPeriodAlignmentEnum
Name | Value
---- | -----
ALIGNTOCHARGE | "AlignToCharge"
ALIGNTOSUBSCRIPTIONSTART | "AlignToSubscriptionStart"
ALIGNTOTERMSTART | "AlignToTermStart"
<a name="BillingTimingEnum"></a>
## Enum: BillingTimingEnum
Name | Value
---- | -----
ADVANCE | "IN_ADVANCE"
ARREARS | "IN_ARREARS"
<a name="WeeklyBillCycleDayEnum"></a>
## Enum: WeeklyBillCycleDayEnum
Name | Value
---- | -----
SUNDAY | "Sunday"
MONDAY | "Monday"
TUESDAY | "Tuesday"
WEDNESDAY | "Wednesday"
THURSDAY | "Thursday"
FRIDAY | "Friday"
SATURDAY | "Saturday"
<file_sep># GetFilesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**gETFiles**](GetFilesApi.md#gETFiles) | **GET** /v1/files/{file-id} | Get files
<a name="gETFiles"></a>
# **gETFiles**
> gETFiles(fileId, zuoraEntityIds)
Get files
Retrieve files such as export results, invoices, and accounting period reports. **Note:** The maximum file size is 2047MB. If you have a data request that exceeds this limit, Zuora returns the following 403 response: `<security:max-object-size>2047MB</security:max-object-size>`. Submit a request at <a href=\"http://support.zuora.com/\" target=\"_blank\">Zuora Global Support</a> to determine if large file optimization is an option for you.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.GetFilesApi;
GetFilesApi apiInstance = new GetFilesApi();
String fileId = "fileId_example"; // String | The Zuora ID of the file to retrieve.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
apiInstance.gETFiles(fileId, zuoraEntityIds);
} catch (ApiException e) {
System.err.println("Exception when calling GetFilesApi#gETFiles");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**fileId** | **String**| The Zuora ID of the file to retrieve. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep># RevenueSchedulesApi
All URIs are relative to *https://rest.zuora.com*
Method | HTTP request | Description
------------- | ------------- | -------------
[**dELETERS**](RevenueSchedulesApi.md#dELETERS) | **DELETE** /v1/revenue-schedules/{rs-number} | Delete revenue schedule
[**gETRS**](RevenueSchedulesApi.md#gETRS) | **GET** /v1/revenue-schedules/{rs-number} | Get revenue schedule details
[**gETRSbyCreditMemoItem**](RevenueSchedulesApi.md#gETRSbyCreditMemoItem) | **GET** /v1/revenue-schedules/credit-memo-items/{cmi-id} | Get revenue schedule by credit memo item ID
[**gETRSbyDebitMemoItem**](RevenueSchedulesApi.md#gETRSbyDebitMemoItem) | **GET** /v1/revenue-schedules/debit-memo-items/{dmi-id} | Get revenue schedule by debit memo item ID
[**gETRSbyInvoiceItem**](RevenueSchedulesApi.md#gETRSbyInvoiceItem) | **GET** /v1/revenue-schedules/invoice-items/{invoice-item-id} | Get revenue schedule by invoice item ID
[**gETRSbyInvoiceItemAdjustment**](RevenueSchedulesApi.md#gETRSbyInvoiceItemAdjustment) | **GET** /v1/revenue-schedules/invoice-item-adjustments/{invoice-item-adj-key} | Get revenue schedule by invoice item adjustment
[**gETRSbyProductChargeAndBillingAccount**](RevenueSchedulesApi.md#gETRSbyProductChargeAndBillingAccount) | **GET** /v1/revenue-schedules/product-charges/{charge-key}/{account-key} | Get all revenue schedules of product charge by charge ID and billing account ID
[**gETRSforSubscCharge**](RevenueSchedulesApi.md#gETRSforSubscCharge) | **GET** /v1/revenue-schedules/subscription-charges/{charge-key} | Get revenue schedule by subscription charge
[**pOSTRSforCreditMemoItemDistributeByDateRange**](RevenueSchedulesApi.md#pOSTRSforCreditMemoItemDistributeByDateRange) | **POST** /v1/revenue-schedules/credit-memo-items/{cmi-id}/distribute-revenue-with-date-range | Create revenue schedule for credit memo item (distribute by date range)
[**pOSTRSforCreditMemoItemManualDistribution**](RevenueSchedulesApi.md#pOSTRSforCreditMemoItemManualDistribution) | **POST** /v1/revenue-schedules/credit-memo-items/{cmi-id} | Create revenue schedule for credit memo item (manual distribution)
[**pOSTRSforDebitMemoItemDistributeByDateRange**](RevenueSchedulesApi.md#pOSTRSforDebitMemoItemDistributeByDateRange) | **POST** /v1/revenue-schedules/debit-memo-items/{dmi-id}/distribute-revenue-with-date-range | Create revenue schedule for debit memo item (distribute by date range)
[**pOSTRSforDebitMemoItemManualDistribution**](RevenueSchedulesApi.md#pOSTRSforDebitMemoItemManualDistribution) | **POST** /v1/revenue-schedules/debit-memo-items/{dmi-id} | Create revenue schedule for debit memo item (manual distribution)
[**pOSTRSforInvoiceItemAdjustmentDistributeByDateRange**](RevenueSchedulesApi.md#pOSTRSforInvoiceItemAdjustmentDistributeByDateRange) | **POST** /v1/revenue-schedules/invoice-item-adjustments/{invoice-item-adj-key}/distribute-revenue-with-date-range | Create revenue schedule for Invoice Item Adjustment (distribute by date range)
[**pOSTRSforInvoiceItemAdjustmentManualDistribution**](RevenueSchedulesApi.md#pOSTRSforInvoiceItemAdjustmentManualDistribution) | **POST** /v1/revenue-schedules/invoice-item-adjustments/{invoice-item-adj-key} | Create revenue schedule for Invoice Item Adjustment (manual distribution)
[**pOSTRSforInvoiceItemDistributeByDateRange**](RevenueSchedulesApi.md#pOSTRSforInvoiceItemDistributeByDateRange) | **POST** /v1/revenue-schedules/invoice-items/{invoice-item-id}/distribute-revenue-with-date-range | Create revenue schedule for Invoice Item (distribute by date range)
[**pOSTRSforInvoiceItemManualDistribution**](RevenueSchedulesApi.md#pOSTRSforInvoiceItemManualDistribution) | **POST** /v1/revenue-schedules/invoice-items/{invoice-item-id} | Create revenue schedule for Invoice Item (manual distribution)
[**pOSTRSforSubscCharge**](RevenueSchedulesApi.md#pOSTRSforSubscCharge) | **POST** /v1/revenue-schedules/subscription-charges/{charge-key} | Create revenue schedule on subscription charge
[**pUTRSBasicInfo**](RevenueSchedulesApi.md#pUTRSBasicInfo) | **PUT** /v1/revenue-schedules/{rs-number}/basic-information | Update revenue schedule basic information
[**pUTRevenueAcrossAP**](RevenueSchedulesApi.md#pUTRevenueAcrossAP) | **PUT** /v1/revenue-schedules/{rs-number}/distribute-revenue-across-accounting-periods | Distribute revenue across accounting periods
[**pUTRevenueByRecognitionStartandEndDates**](RevenueSchedulesApi.md#pUTRevenueByRecognitionStartandEndDates) | **PUT** /v1/revenue-schedules/{rs-number}/distribute-revenue-with-date-range | Distribute revenue by recognition start and end dates
[**pUTRevenueSpecificDate**](RevenueSchedulesApi.md#pUTRevenueSpecificDate) | **PUT** /v1/revenue-schedules/{rs-number}/distribute-revenue-on-specific-date | Distribute revenue on specific date
<a name="dELETERS"></a>
# **dELETERS**
> CommonResponseType dELETERS(rsNumber, zuoraEntityIds)
Delete revenue schedule
Deletes a revenue schedule by specifying its revenue schedule number ## Prerequisites You must have the Delete Custom Revenue Schedule permissions in Zuora Finance.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number of the revenue schedule you want to delete, for example, RS-00000256. To be deleted, the revenue schedule: * Must be using a custom unlimited recognition rule. * Cannot have any revenue in a closed accounting period. * Cannot be included in a summary journal entry. * Cannot have a revenue schedule date in a closed accounting period.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.dELETERS(rsNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#dELETERS");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number of the revenue schedule you want to delete, for example, RS-00000256. To be deleted, the revenue schedule: * Must be using a custom unlimited recognition rule. * Cannot have any revenue in a closed accounting period. * Cannot be included in a summary journal entry. * Cannot have a revenue schedule date in a closed accounting period. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRS"></a>
# **gETRS**
> GETRSDetailType gETRS(rsNumber, zuoraEntityIds)
Get revenue schedule details
Retrieves the details of a revenue schedule by specifying the revenue schedule number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRSDetailType result = apiInstance.gETRS(rsNumber, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#gETRS");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRSDetailType**](GETRSDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRSbyCreditMemoItem"></a>
# **gETRSbyCreditMemoItem**
> GETRSDetailType gETRSbyCreditMemoItem(cmiId)
Get revenue schedule by credit memo item ID
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the details about a revenue schedule by specifying a valid credit memo item ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String cmiId = "cmiId_example"; // String | The unique ID of a credit memo item. You can get the credit memo item ID from the response of [Get credit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_CreditMemoItems).
try {
GETRSDetailType result = apiInstance.gETRSbyCreditMemoItem(cmiId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#gETRSbyCreditMemoItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cmiId** | **String**| The unique ID of a credit memo item. You can get the credit memo item ID from the response of [Get credit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_CreditMemoItems). |
### Return type
[**GETRSDetailType**](GETRSDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRSbyDebitMemoItem"></a>
# **gETRSbyDebitMemoItem**
> GETRSDetailType gETRSbyDebitMemoItem(dmiId)
Get revenue schedule by debit memo item ID
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the details about a revenue schedule by specifying a valid debit memo item ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String dmiId = "dmiId_example"; // String | The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems).
try {
GETRSDetailType result = apiInstance.gETRSbyDebitMemoItem(dmiId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#gETRSbyDebitMemoItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**dmiId** | **String**| The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems). |
### Return type
[**GETRSDetailType**](GETRSDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRSbyInvoiceItem"></a>
# **gETRSbyInvoiceItem**
> GETRSDetailType gETRSbyInvoiceItem(invoiceItemId, zuoraEntityIds)
Get revenue schedule by invoice item ID
Retrieves the details of a revenue schedule by specifying the invoice item ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String invoiceItemId = "invoiceItemId_example"; // String | A valid Invoice Item ID.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRSDetailType result = apiInstance.gETRSbyInvoiceItem(invoiceItemId, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#gETRSbyInvoiceItem");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceItemId** | **String**| A valid Invoice Item ID. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRSDetailType**](GETRSDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRSbyInvoiceItemAdjustment"></a>
# **gETRSbyInvoiceItemAdjustment**
> GETRSDetailType gETRSbyInvoiceItemAdjustment(invoiceItemAdjKey, zuoraEntityIds)
Get revenue schedule by invoice item adjustment
Retrieves the details of a revenue schedule by specifying a valid invoice item adjustment identifier. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String invoiceItemAdjKey = "invoiceItemAdjKey_example"; // String | ID or number of the Invoice Item Adjustment, for example, e20b07fd416dcfcf0141c81164fd0a72.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
GETRSDetailType result = apiInstance.gETRSbyInvoiceItemAdjustment(invoiceItemAdjKey, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#gETRSbyInvoiceItemAdjustment");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceItemAdjKey** | **String**| ID or number of the Invoice Item Adjustment, for example, <KEY>. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**GETRSDetailType**](GETRSDetailType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRSbyProductChargeAndBillingAccount"></a>
# **gETRSbyProductChargeAndBillingAccount**
> GETRSDetailsByProductChargeType gETRSbyProductChargeAndBillingAccount(accountKey, chargeKey, pageSize)
Get all revenue schedules of product charge by charge ID and billing account ID
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Retrieves the details about all revenue schedules of a product rate plan charge by specifying the charge ID and billing account ID.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String accountKey = "accountKey_example"; // String | The account number or account ID.
String chargeKey = "chargeKey_example"; // String | The unique ID of a product rate plan charge. For example, <KEY>.
Integer pageSize = 8; // Integer | Number of rows returned per page.
try {
GETRSDetailsByProductChargeType result = apiInstance.gETRSbyProductChargeAndBillingAccount(accountKey, chargeKey, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#gETRSbyProductChargeAndBillingAccount");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**accountKey** | **String**| The account number or account ID. |
**chargeKey** | **String**| The unique ID of a product rate plan charge. For example, <KEY>. |
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 8]
### Return type
[**GETRSDetailsByProductChargeType**](GETRSDetailsByProductChargeType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="gETRSforSubscCharge"></a>
# **gETRSforSubscCharge**
> GETRSDetailsByChargeType gETRSforSubscCharge(chargeKey, zuoraEntityIds, pageSize)
Get revenue schedule by subscription charge
Retrieves the revenue schedule details by specifying subscription charge ID. Request and response field descriptions and sample code are provided
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String chargeKey = "chargeKey_example"; // String | ID of the subscription rate plan charge; for example, 402892793e173340013e173b81000012.
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
Integer pageSize = 8; // Integer | Number of rows returned per page.
try {
GETRSDetailsByChargeType result = apiInstance.gETRSforSubscCharge(chargeKey, zuoraEntityIds, pageSize);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#gETRSforSubscCharge");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**chargeKey** | **String**| ID of the subscription rate plan charge; for example, 402892793e173340013e173b81000012. |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
**pageSize** | **Integer**| Number of rows returned per page. | [optional] [default to 8]
### Return type
[**GETRSDetailsByChargeType**](GETRSDetailsByChargeType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforCreditMemoItemDistributeByDateRange"></a>
# **pOSTRSforCreditMemoItemDistributeByDateRange**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforCreditMemoItemDistributeByDateRange(cmiId, body)
Create revenue schedule for credit memo item (distribute by date range)
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates a revenue schedule for a credit memo item, and automatically distribute the revenue by specifying the recognition start and end dates.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String cmiId = "cmiId_example"; // String | The unique ID of a credit memo item. You can get the credit memo item ID from the response of [Get credit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_CreditMemoItems).
POSTRevenueScheduleByTransactionRatablyType body = new POSTRevenueScheduleByTransactionRatablyType(); // POSTRevenueScheduleByTransactionRatablyType |
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforCreditMemoItemDistributeByDateRange(cmiId, body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforCreditMemoItemDistributeByDateRange");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cmiId** | **String**| The unique ID of a credit memo item. You can get the credit memo item ID from the response of [Get credit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_CreditMemoItems). |
**body** | [**POSTRevenueScheduleByTransactionRatablyType**](POSTRevenueScheduleByTransactionRatablyType.md)| |
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforCreditMemoItemManualDistribution"></a>
# **pOSTRSforCreditMemoItemManualDistribution**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforCreditMemoItemManualDistribution(cmiId, body)
Create revenue schedule for credit memo item (manual distribution)
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates a revenue schedule for a credit memo item, and manually distribute the revenue.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String cmiId = "cmiId_example"; // String | The unique ID of a credit memo item. You can get the credit memo item ID from the response of [Get credit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_CreditMemoItems).
POSTRevenueScheduleByTransactionType body = new POSTRevenueScheduleByTransactionType(); // POSTRevenueScheduleByTransactionType |
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforCreditMemoItemManualDistribution(cmiId, body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforCreditMemoItemManualDistribution");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cmiId** | **String**| The unique ID of a credit memo item. You can get the credit memo item ID from the response of [Get credit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_CreditMemoItems). |
**body** | [**POSTRevenueScheduleByTransactionType**](POSTRevenueScheduleByTransactionType.md)| |
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforDebitMemoItemDistributeByDateRange"></a>
# **pOSTRSforDebitMemoItemDistributeByDateRange**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforDebitMemoItemDistributeByDateRange(dmiId, body)
Create revenue schedule for debit memo item (distribute by date range)
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates a revenue schedule for a debit memo item, and automatically distribute the revenue by specifying the recognition start and end dates.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String dmiId = "dmiId_example"; // String | The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems).
POSTRevenueScheduleByTransactionRatablyType body = new POSTRevenueScheduleByTransactionRatablyType(); // POSTRevenueScheduleByTransactionRatablyType |
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforDebitMemoItemDistributeByDateRange(dmiId, body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforDebitMemoItemDistributeByDateRange");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**dmiId** | **String**| The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems). |
**body** | [**POSTRevenueScheduleByTransactionRatablyType**](POSTRevenueScheduleByTransactionRatablyType.md)| |
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforDebitMemoItemManualDistribution"></a>
# **pOSTRSforDebitMemoItemManualDistribution**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforDebitMemoItemManualDistribution(dmiId, body)
Create revenue schedule for debit memo item (manual distribution)
**Note:** This feature is only available if you have the Invoice Settlement feature enabled. The Invoice Settlement feature is in **Limited Availability**. If you wish to have access to the feature, submit a request at [Zuora Global Support](http://support.zuora.com/). Creates a revenue schedule for a debit memo item, and manually distribute the revenue.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String dmiId = "dmiId_example"; // String | The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems).
POSTRevenueScheduleByTransactionType body = new POSTRevenueScheduleByTransactionType(); // POSTRevenueScheduleByTransactionType |
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforDebitMemoItemManualDistribution(dmiId, body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforDebitMemoItemManualDistribution");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**dmiId** | **String**| The unique ID of a debit memo item. You can get the debit memo item ID from the response of [Get debit memo items](https://www.zuora.com/developer/api-reference/#operation/GET_DebitMemoItems). |
**body** | [**POSTRevenueScheduleByTransactionType**](POSTRevenueScheduleByTransactionType.md)| |
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforInvoiceItemAdjustmentDistributeByDateRange"></a>
# **pOSTRSforInvoiceItemAdjustmentDistributeByDateRange**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforInvoiceItemAdjustmentDistributeByDateRange(invoiceItemAdjKey, request, zuoraEntityIds)
Create revenue schedule for Invoice Item Adjustment (distribute by date range)
Creates a revenue schedule for an Invoice Item Adjustment and distribute the revenue by specifying the recognition start and end dates.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String invoiceItemAdjKey = "invoiceItemAdjKey_example"; // String | ID or number of the Invoice Item Adjustment, for example, <KEY>. If the specified Invoice Item Adjustment is already associated with a revenue schedule, the call will fail.
POSTRevenueScheduleByDateRangeType request = new POSTRevenueScheduleByDateRangeType(); // POSTRevenueScheduleByDateRangeType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforInvoiceItemAdjustmentDistributeByDateRange(invoiceItemAdjKey, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforInvoiceItemAdjustmentDistributeByDateRange");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceItemAdjKey** | **String**| ID or number of the Invoice Item Adjustment, for example, <KEY>. If the specified Invoice Item Adjustment is already associated with a revenue schedule, the call will fail. |
**request** | [**POSTRevenueScheduleByDateRangeType**](POSTRevenueScheduleByDateRangeType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforInvoiceItemAdjustmentManualDistribution"></a>
# **pOSTRSforInvoiceItemAdjustmentManualDistribution**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforInvoiceItemAdjustmentManualDistribution(invoiceItemAdjKey, request, zuoraEntityIds)
Create revenue schedule for Invoice Item Adjustment (manual distribution)
Creates a revenue schedule for an Invoice Item Adjustment and manually distribute the revenue.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String invoiceItemAdjKey = "invoiceItemAdjKey_example"; // String | ID or number of the Invoice Item Adjustment, for example, e20b07fd416dcfcf0141c81164fd0a72. If the specified Invoice Item Adjustment is already associated with a revenue schedule, the call will fail.
POSTRevenueScheduleByTransactionType request = new POSTRevenueScheduleByTransactionType(); // POSTRevenueScheduleByTransactionType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforInvoiceItemAdjustmentManualDistribution(invoiceItemAdjKey, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforInvoiceItemAdjustmentManualDistribution");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceItemAdjKey** | **String**| ID or number of the Invoice Item Adjustment, for example, <KEY>. If the specified Invoice Item Adjustment is already associated with a revenue schedule, the call will fail. |
**request** | [**POSTRevenueScheduleByTransactionType**](POSTRevenueScheduleByTransactionType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforInvoiceItemDistributeByDateRange"></a>
# **pOSTRSforInvoiceItemDistributeByDateRange**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforInvoiceItemDistributeByDateRange(invoiceItemId, request, zuoraEntityIds)
Create revenue schedule for Invoice Item (distribute by date range)
Creates a revenue schedule for an Invoice Item and distribute the revenue by specifying the recognition start and end dates.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String invoiceItemId = "invoiceItemId_example"; // String | ID of the Invoice Item, for example, e20b07fd416dcfcf0141c81164fd0a75. If the specified Invoice Item is already associated with a revenue schedule, the call will fail.
POSTRevenueScheduleByDateRangeType request = new POSTRevenueScheduleByDateRangeType(); // POSTRevenueScheduleByDateRangeType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforInvoiceItemDistributeByDateRange(invoiceItemId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforInvoiceItemDistributeByDateRange");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceItemId** | **String**| ID of the Invoice Item, for example, e20b07fd416dcfcf0141c81164fd0a75. If the specified Invoice Item is already associated with a revenue schedule, the call will fail. |
**request** | [**POSTRevenueScheduleByDateRangeType**](POSTRevenueScheduleByDateRangeType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforInvoiceItemManualDistribution"></a>
# **pOSTRSforInvoiceItemManualDistribution**
> POSTRevenueScheduleByTransactionResponseType pOSTRSforInvoiceItemManualDistribution(invoiceItemId, request, zuoraEntityIds)
Create revenue schedule for Invoice Item (manual distribution)
Creates a revenue schedule for an Invoice Item and manually distribute the revenue.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String invoiceItemId = "invoiceItemId_example"; // String | ID of the Invoice Item, for example, e20b07fd416dcfcf0141c81164fd0a75. If the specified Invoice Item is already associated with a revenue schedule, the call will fail.
POSTRevenueScheduleByTransactionType request = new POSTRevenueScheduleByTransactionType(); // POSTRevenueScheduleByTransactionType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTRevenueScheduleByTransactionResponseType result = apiInstance.pOSTRSforInvoiceItemManualDistribution(invoiceItemId, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforInvoiceItemManualDistribution");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoiceItemId** | **String**| ID of the Invoice Item, for example, e20b07fd416dcfcf0141c81164fd0a75. If the specified Invoice Item is already associated with a revenue schedule, the call will fail. |
**request** | [**POSTRevenueScheduleByTransactionType**](POSTRevenueScheduleByTransactionType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTRevenueScheduleByTransactionResponseType**](POSTRevenueScheduleByTransactionResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pOSTRSforSubscCharge"></a>
# **pOSTRSforSubscCharge**
> POSTRevenueScheduleByChargeResponseType pOSTRSforSubscCharge(chargeKey, request, zuoraEntityIds)
Create revenue schedule on subscription charge
Creates a revenue schedule by specifying the subscription charge. This method is for custom unlimited revenue recognition only.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String chargeKey = "chargeKey_example"; // String | ID of the subscription rate plan charge; for example, 402892793e173340013e173b81000012.
POSTRevenueScheduleByChargeType request = new POSTRevenueScheduleByChargeType(); // POSTRevenueScheduleByChargeType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
POSTRevenueScheduleByChargeResponseType result = apiInstance.pOSTRSforSubscCharge(chargeKey, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pOSTRSforSubscCharge");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**chargeKey** | **String**| ID of the subscription rate plan charge; for example, 402892793e173340013e173b81000012. |
**request** | [**POSTRevenueScheduleByChargeType**](POSTRevenueScheduleByChargeType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**POSTRevenueScheduleByChargeResponseType**](POSTRevenueScheduleByChargeResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTRSBasicInfo"></a>
# **pUTRSBasicInfo**
> CommonResponseType pUTRSBasicInfo(rsNumber, request, zuoraEntityIds)
Update revenue schedule basic information
Retrieves basic information of a revenue schedule by specifying the revenue schedule number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
PUTRSBasicInfoType request = new PUTRSBasicInfoType(); // PUTRSBasicInfoType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
CommonResponseType result = apiInstance.pUTRSBasicInfo(rsNumber, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pUTRSBasicInfo");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**request** | [**PUTRSBasicInfoType**](PUTRSBasicInfoType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**CommonResponseType**](CommonResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTRevenueAcrossAP"></a>
# **pUTRevenueAcrossAP**
> PUTRevenueScheduleResponseType pUTRevenueAcrossAP(rsNumber, request, zuoraEntityIds)
Distribute revenue across accounting periods
Distributes revenue by specifying the revenue schedule number. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
PUTAllocateManuallyType request = new PUTAllocateManuallyType(); // PUTAllocateManuallyType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTRevenueScheduleResponseType result = apiInstance.pUTRevenueAcrossAP(rsNumber, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pUTRevenueAcrossAP");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**request** | [**PUTAllocateManuallyType**](PUTAllocateManuallyType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTRevenueScheduleResponseType**](PUTRevenueScheduleResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTRevenueByRecognitionStartandEndDates"></a>
# **pUTRevenueByRecognitionStartandEndDates**
> PUTRevenueScheduleResponseType pUTRevenueByRecognitionStartandEndDates(rsNumber, request, zuoraEntityIds)
Distribute revenue by recognition start and end dates
Distributes revenue by specifying the recognition start and end dates. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. Specify the revenue schedule whose revenue you want to distribute. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
PUTRSTermType request = new PUTRSTermType(); // PUTRSTermType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTRevenueScheduleResponseType result = apiInstance.pUTRevenueByRecognitionStartandEndDates(rsNumber, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pUTRevenueByRecognitionStartandEndDates");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. Specify the revenue schedule whose revenue you want to distribute. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**request** | [**PUTRSTermType**](PUTRSTermType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTRevenueScheduleResponseType**](PUTRevenueScheduleResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<a name="pUTRevenueSpecificDate"></a>
# **pUTRevenueSpecificDate**
> PUTRevenueScheduleResponseType pUTRevenueSpecificDate(rsNumber, request, zuoraEntityIds)
Distribute revenue on specific date
Distributes revenue on a specific recognition date. Request and response field descriptions and sample code are provided.
### Example
```java
// Import classes:
//import de.keylight.zuora.client.invoker.ApiException;
//import de.keylight.zuora.client.api.RevenueSchedulesApi;
RevenueSchedulesApi apiInstance = new RevenueSchedulesApi();
String rsNumber = "rsNumber_example"; // String | Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\".
PUTSpecificDateAllocationType request = new PUTSpecificDateAllocationType(); // PUTSpecificDateAllocationType |
String zuoraEntityIds = "zuoraEntityIds_example"; // String | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
try {
PUTRevenueScheduleResponseType result = apiInstance.pUTRevenueSpecificDate(rsNumber, request, zuoraEntityIds);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RevenueSchedulesApi#pUTRevenueSpecificDate");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**rsNumber** | **String**| Revenue schedule number. The revenue schedule number is always prefixed with \"RS\", for example, \"RS-00000001\". |
**request** | [**PUTSpecificDateAllocationType**](PUTSpecificDateAllocationType.md)| |
**zuoraEntityIds** | **String**| An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. | [optional]
### Return type
[**PUTRevenueScheduleResponseType**](PUTRevenueScheduleResponseType.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json; charset=utf-8
- **Accept**: application/json; charset=utf-8
<file_sep>
# AmendmentRatePlanChargeData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ratePlanCharge** | [**AmendmentRatePlanChargeDataRatePlanCharge**](AmendmentRatePlanChargeDataRatePlanCharge.md) | |
**ratePlanChargeTier** | [**List<AmendmentRatePlanChargeTier>**](AmendmentRatePlanChargeTier.md) | | [optional]
<file_sep>
# TimeSlicedMetricsForEvergreen
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | | [optional]
**invoiceOwner** | **String** | The acount number of the billing account that is billed for the subscription. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | | [optional]
**subscriptionOwner** | **String** | The acount number of the billing account that owns the subscription. | [optional]
**termNumber** | [**BigDecimal**](BigDecimal.md) | | [optional]
<file_sep>
# InvoiceItemPreviewResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**additionalInfo** | [**InvoiceItemPreviewResultAdditionalInfo**](InvoiceItemPreviewResultAdditionalInfo.md) | | [optional]
**amountWithoutTax** | [**BigDecimal**](BigDecimal.md) | | [optional]
**appliedToChargeNumber** | **String** | Available when the chargeNumber of the charge that discount applies to was specified in the request or when the order is amending an existing subscription. | [optional]
**chargeDescription** | **String** | | [optional]
**chargeName** | **String** | | [optional]
**chargeNumber** | **String** | Available when the chargeNumber was specified in the request or when the order is amending an existing subscription. | [optional]
**processingType** | [**ProcessingTypeEnum**](#ProcessingTypeEnum) | | [optional]
**productName** | **String** | | [optional]
**productRatePlanChargeId** | **String** | | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | | [optional]
**subscriptionNumber** | **String** | | [optional]
**taxAmount** | [**BigDecimal**](BigDecimal.md) | | [optional]
<a name="ProcessingTypeEnum"></a>
## Enum: ProcessingTypeEnum
Name | Value
---- | -----
CHARGE | "Charge"
DISCOUNT | "Discount"
TAX | "Tax"
<file_sep>
# PUTSubscriptionSuspendResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**creditMemoId** | **String** | The credit memo ID, if a credit memo is generated during the subscription process. **Note:** This field is only available if you have the Invoice Settlements feature enabled. | [optional]
**invoiceId** | **String** | Invoice ID, if an invoice is generated during the subscription process. | [optional]
**paidAmount** | **String** | Payment amount, if a payment is collected. | [optional]
**paymentId** | **String** | Payment ID, if a payment is collected. | [optional]
**resumeDate** | [**LocalDate**](LocalDate.md) | The date when subscription resumption takes effect, in the format yyyy-mm-dd. | [optional]
**subscriptionId** | **String** | The subscription ID. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**suspendDate** | [**LocalDate**](LocalDate.md) | The date when subscription suspension takes effect, in the format yyyy-mm-dd. | [optional]
**termEndDate** | [**LocalDate**](LocalDate.md) | The date when the new subscription term ends, in the format yyyy-mm-dd. | [optional]
**totalDeltaTcv** | **String** | Change in the total contracted value of the subscription as a result of the update. | [optional]
<file_sep>
# ProxyModifyProduct
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the product's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**itemTypeNS** | [**ItemTypeNSEnum**](#ItemTypeNSEnum) | Type of item that is created in NetSuite for the product. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the product was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**allowFeatureChanges** | **Boolean** | Controls whether to allow your users to add or remove features while creating or amending a subscription. **Character** **limit**: n/a **Values**: true, false (default) | [optional]
**category** | **String** | Category of the product. Used by Zuora Quotes Guided Product Selector. **Character** **limit**: 100 **Values**: One of the following: - Base Products - Add On Services - Miscellaneous Products | [optional]
**description** | **String** | A descriptionof the product. **Character limit**: 500 **Values**: a string of 500 characters or fewer | [optional]
**effectiveEndDate** | [**LocalDate**](LocalDate.md) | The date when the product expires and can't be subscribed to anymore, in `yyyy-mm-dd` format. **Character limit**: 29 | [optional]
**effectiveStartDate** | [**LocalDate**](LocalDate.md) | The date when the product becomes available and can be subscribed to, in `yyyy-mm-dd` format. **Character limit**: 29 | [optional]
**name** | **String** | The name of the product. This information is displayed in the product catalog pages in the web-based UI. **Character limit**: 100 **Values**: a string of 100 characters or fewer | [optional]
**SKU** | **String** | The unique SKU for the product. **Character limit**: 50 **Values**: one of the following: - leave null for automatic generated - an alphanumeric string of 50 characters or fewer | [optional]
<a name="ItemTypeNSEnum"></a>
## Enum: ItemTypeNSEnum
Name | Value
---- | -----
INVENTORY | "Inventory"
NON_INVENTORY | "Non Inventory"
SERVICE | "Service"
<file_sep>
# PUTOrderActionTriggerDatesRequestTypeOrderActions
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**charges** | [**List<PUTOrderActionTriggerDatesRequestTypeCharges>**](PUTOrderActionTriggerDatesRequestTypeCharges.md) | | [optional]
**sequence** | **Integer** | Identifies which order action will have its triggering dates updated. Currently, you can only update the triggering dates of `CreateSubscription` order actions. This means that you must set `sequence` to 0, as there is only one `CreateSubscription` order action that affects each subscription. |
**triggerDates** | [**List<PUTOrderActionTriggerDatesRequestTypeTriggerDates>**](PUTOrderActionTriggerDatesRequestTypeTriggerDates.md) | Container for the service activation and customer acceptance dates of the order action. | [optional]
<file_sep>
# BillingUpdate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**billingPeriodAlignment** | [**BillingPeriodAlignmentEnum**](#BillingPeriodAlignmentEnum) | | [optional]
<a name="BillingPeriodAlignmentEnum"></a>
## Enum: BillingPeriodAlignmentEnum
Name | Value
---- | -----
ALIGNTOCHARGE | "AlignToCharge"
ALIGNTOSUBSCRIPTIONSTART | "AlignToSubscriptionStart"
ALIGNTOTERMSTART | "AlignToTermStart"
<file_sep>package de.keylight.zuora.client.api;
import de.keylight.zuora.client.invoker.ApiClient;
import de.keylight.zuora.client.model.CommonResponseType;
import de.keylight.zuora.client.model.GETAccountingCodeItemType;
import de.keylight.zuora.client.model.GETAccountingCodesType;
import de.keylight.zuora.client.model.POSTAccountingCodeResponseType;
import de.keylight.zuora.client.model.POSTAccountingCodeType;
import de.keylight.zuora.client.model.PUTAccountingCodeType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-10-15T21:22:57.945+02:00")
@Component("de.keylight.zuora.client.api.AccountingCodesApi")
public class AccountingCodesApi {
private ApiClient apiClient;
public AccountingCodesApi() {
this(new ApiClient());
}
@Autowired
public AccountingCodesApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Delete accounting code
* This reference describes how to delete an accounting code through the REST API. ## Prerequisites If you have Zuora Finance enabled on your tenant, then you must have the Delete Unused Accounting Code permission. ## Limitations You can only delete accounting codes that have never been associated with any transactions. An accounting code must be deactivated before you can delete it.
* <p><b>200</b> -
* @param acId ID of the accounting code you want to delete.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return CommonResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public CommonResponseType dELETEAccountingCode(String acId, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'acId' is set
if (acId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'acId' when calling dELETEAccountingCode");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("ac-id", acId);
String path = UriComponentsBuilder.fromPath("/v1/accounting-codes/{ac-id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<CommonResponseType> returnType = new ParameterizedTypeReference<CommonResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Query an accounting code
* This reference describes how to query an accounting code through the REST API.
* <p><b>200</b> -
* @param acId ID of the accounting code you want to query.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return GETAccountingCodeItemType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GETAccountingCodeItemType gETAccountingCode(String acId, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'acId' is set
if (acId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'acId' when calling gETAccountingCode");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("ac-id", acId);
String path = UriComponentsBuilder.fromPath("/v1/accounting-codes/{ac-id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GETAccountingCodeItemType> returnType = new ParameterizedTypeReference<GETAccountingCodeItemType>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Get all accounting codes
* This reference describes how to query all accounting codes in your chart of accounts through the REST API.
* <p><b>200</b> -
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @param pageSize Number of rows returned per page.
* @return GETAccountingCodesType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public GETAccountingCodesType gETAllAccountingCodes(String zuoraEntityIds, Integer pageSize) throws RestClientException {
Object postBody = null;
String path = UriComponentsBuilder.fromPath("/v1/accounting-codes").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "pageSize", pageSize));
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<GETAccountingCodesType> returnType = new ParameterizedTypeReference<GETAccountingCodesType>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Create accounting code
* This reference describes how to create a new accounting code through the REST API. The accounting code will be active as soon as it has been created. ## Prerequisites If you have Zuora Finance enabled on your tenant, you must have the Configure Accounting Codes permission.
* <p><b>200</b> -
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return POSTAccountingCodeResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public POSTAccountingCodeResponseType pOSTAccountingCode(POSTAccountingCodeType request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pOSTAccountingCode");
}
String path = UriComponentsBuilder.fromPath("/v1/accounting-codes").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<POSTAccountingCodeResponseType> returnType = new ParameterizedTypeReference<POSTAccountingCodeResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Update an accounting code
* This reference describes how to update an existing accounting code through the REST API. ## Prerequisites If you have Zuora Finance enabled on your tenant, you must have the Manage Accounting Code permission. ## Limitations You can only update accounting codes that are not already associated with any transactions.
* <p><b>200</b> -
* @param acId ID of the accounting code you want to update.
* @param request
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return CommonResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public CommonResponseType pUTAccountingCode(String acId, PUTAccountingCodeType request, String zuoraEntityIds) throws RestClientException {
Object postBody = request;
// verify the required parameter 'acId' is set
if (acId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'acId' when calling pUTAccountingCode");
}
// verify the required parameter 'request' is set
if (request == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'request' when calling pUTAccountingCode");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("ac-id", acId);
String path = UriComponentsBuilder.fromPath("/v1/accounting-codes/{ac-id}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<CommonResponseType> returnType = new ParameterizedTypeReference<CommonResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Activate accounting code
* This reference describes how to activate an accounting code through the REST API. Prerequisites ------------- If you have Zuora Finance enabled on your tenant, you must have the Manage Accounting Code permission.
* <p><b>200</b> -
* @param acId ID of the accounting code you want to activate.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return CommonResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public CommonResponseType pUTActivateAccountingCode(String acId, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'acId' is set
if (acId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'acId' when calling pUTActivateAccountingCode");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("ac-id", acId);
String path = UriComponentsBuilder.fromPath("/v1/accounting-codes/{ac-id}/activate").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<CommonResponseType> returnType = new ParameterizedTypeReference<CommonResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Deactivate accounting code
* This reference describes how to deactivate an accounting code through the REST API. ## Prerequisites If you have Zuora Finance enabled on your tenant, you must have the Manage Accounting Code permission. ## Limitations You can only deactivate accounting codes that are not associated with any transactions. You cannot disable accounting codes of type AccountsReceivable.
* <p><b>200</b> -
* @param acId ID of the accounting code you want to deactivate.
* @param zuoraEntityIds An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header.
* @return CommonResponseType
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public CommonResponseType pUTDeactivateAccountingCode(String acId, String zuoraEntityIds) throws RestClientException {
Object postBody = null;
// verify the required parameter 'acId' is set
if (acId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'acId' when calling pUTDeactivateAccountingCode");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("ac-id", acId);
String path = UriComponentsBuilder.fromPath("/v1/accounting-codes/{ac-id}/deactivate").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
if (zuoraEntityIds != null)
headerParams.add("Zuora-Entity-Ids", apiClient.parameterToString(zuoraEntityIds));
final String[] accepts = {
"application/json; charset=utf-8"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json; charset=utf-8"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<CommonResponseType> returnType = new ParameterizedTypeReference<CommonResponseType>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
}
<file_sep>
# RatedItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | | [optional]
**serviceEndDate** | [**LocalDate**](LocalDate.md) | | [optional]
**serviceStartDate** | [**LocalDate**](LocalDate.md) | | [optional]
<file_sep>
# PutInvoiceResponseType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**integrationIdNS** | **String** | ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**integrationStatusNS** | **String** | Status of the invoice's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**syncDateNS** | **String** | Date when the invoice was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). | [optional]
**accountId** | **String** | The ID of the customer account associated with the invoice. | [optional]
**amount** | [**BigDecimal**](BigDecimal.md) | The total amount of the invoice. | [optional]
**autoPay** | **Boolean** | Whether invoices are automatically picked up for processing in the corresponding payment run. | [optional]
**balance** | [**BigDecimal**](BigDecimal.md) | The balance of the invoice. | [optional]
**cancelledById** | **String** | The ID of the Zuora user who cancelled the invoice. | [optional]
**cancelledOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the invoice was cancelled, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**comment** | **String** | Comments about the invoice. | [optional]
**createdById** | **String** | The ID of the Zuora user who created the invoice. | [optional]
**createdDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the invoice was created, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-01 15:31:10. | [optional]
**creditBalanceAdjustmentAmount** | [**BigDecimal**](BigDecimal.md) | **Note:** This filed is only available if you have the Credit Balance feature enabled and the Invoice Settlement feature disabled. The currency amount of the adjustment applied to the customer's credit balance. | [optional]
**currency** | **String** | A currency defined in the web-based UI administrative settings. | [optional]
**dueDate** | [**LocalDate**](LocalDate.md) | The date by which the payment for this invoice is due. | [optional]
**id** | **String** | The unique ID of the invoice. | [optional]
**invoiceDate** | [**LocalDate**](LocalDate.md) | The date on which to generate the invoice. | [optional]
**number** | **String** | The unique identification number of the invoice. | [optional]
**postedById** | **String** | The ID of the Zuora user who posted the invoice. | [optional]
**postedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the invoice was posted, in `yyyy-mm-dd hh:mm:ss` format. | [optional]
**status** | [**StatusEnum**](#StatusEnum) | The status of the invoice. | [optional]
**success** | **Boolean** | Returns `true` if the request was processed successfully. | [optional]
**targetDate** | [**LocalDate**](LocalDate.md) | The target date for the invoice, in `yyyy-mm-dd` format. For example, 2017-07-20. | [optional]
**taxAmount** | [**BigDecimal**](BigDecimal.md) | The amount of taxation. | [optional]
**totalTaxExemptAmount** | [**BigDecimal**](BigDecimal.md) | The total amount of taxes or VAT for which the customer has an exemption. | [optional]
**transferredToAccounting** | [**TransferredToAccountingEnum**](#TransferredToAccountingEnum) | Whether the invoice was transferred to an external accounting system. | [optional]
**updatedById** | **String** | The ID of the Zuora user who last updated the invoice. | [optional]
**updatedDate** | [**OffsetDateTime**](OffsetDateTime.md) | The date and time when the invoice was last updated, in `yyyy-mm-dd hh:mm:ss` format. For example, 2017-03-02 15:36:10. | [optional]
<a name="StatusEnum"></a>
## Enum: StatusEnum
Name | Value
---- | -----
DRAFT | "Draft"
POSTED | "Posted"
CANCELED | "Canceled"
ERROR | "Error"
<a name="TransferredToAccountingEnum"></a>
## Enum: TransferredToAccountingEnum
Name | Value
---- | -----
PROCESSING | "Processing"
YES | "Yes"
ERROR | "Error"
IGNORE | "Ignore"
<file_sep>
# InvoiceData
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**invoice** | [**InvoiceDataInvoice**](InvoiceDataInvoice.md) | | [optional]
**invoiceItem** | [**List<InvoiceItem>**](InvoiceItem.md) | | [optional]
<file_sep>
# TimeSlicedElpNetMetrics
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**amount** | [**BigDecimal**](BigDecimal.md) | The extended list price which is calculated by the original product catalog list price multiplied by the delta quantity. | [optional]
**endDate** | [**LocalDate**](LocalDate.md) | The latest date that the metric applies. | [optional]
**generatedReason** | [**GeneratedReasonEnum**](#GeneratedReasonEnum) | Specify the reason why the metrics are generated by the certain order action. | [optional]
**invoiceOwner** | **String** | The acount number of the billing account that is billed for the subscription. | [optional]
**orderItemId** | **String** | The ID of the order item referenced by the order metrics. | [optional]
**startDate** | [**LocalDate**](LocalDate.md) | The earliest date that the metric applies. | [optional]
**subscriptionOwner** | **String** | The acount number of the billing account that owns the subscription. | [optional]
**tax** | [**BigDecimal**](BigDecimal.md) | The tax amount in the metric when the tax permission is enabled. | [optional]
**termNumber** | [**BigDecimal**](BigDecimal.md) | | [optional]
**type** | [**TypeEnum**](#TypeEnum) | The type for ELP is always \"Regular\". | [optional]
<a name="GeneratedReasonEnum"></a>
## Enum: GeneratedReasonEnum
Name | Value
---- | -----
INCREASEQUANTITY | "IncreaseQuantity"
DECREASEQUANTITY | "DecreaseQuantity"
CHANGEPRICE | "ChangePrice"
EXTENSION | "Extension"
CONTRACTION | "Contraction"
<a name="TypeEnum"></a>
## Enum: TypeEnum
Name | Value
---- | -----
REGULAR | "Regular"
DISCOUNT | "Discount"
<file_sep>
# PUTScheduleRIDetailType
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**revenueItems** | [**List<RevenueScheduleItemType>**](RevenueScheduleItemType.md) | Revenue items are listed in ascending order by the accounting period start date. Include at least one custom field. |
<file_sep>
# GETPublicNotificationDefinitionResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**active** | **Boolean** | The status of the notification definition. The default value is true. | [optional]
**callout** | [**GETPublicNotificationDefinitionResponseCallout**](GETPublicNotificationDefinitionResponseCallout.md) | | [optional]
**calloutActive** | **Boolean** | The status of the callout action. The default value is false. | [optional]
**communicationProfileId** | [**UUID**](UUID.md) | The profile that the notification definition belongs to. | [optional]
**createdBy** | [**UUID**](UUID.md) | The ID of the user who created the notification definition. | [optional]
**createdOn** | [**OffsetDateTime**](OffsetDateTime.md) | The time when the notification definition was created. Specified in the UTC timezone in the ISO860 format (YYYY-MM-DDThh:mm:ss.sTZD). E.g. 1997-07-16T19:20:30.45+00:00 | [optional]
**description** | **String** | Description of the notification definition | [optional]
**emailActive** | **Boolean** | The status of the email action. The default value is false. | [optional]
**emailTemplateId** | [**UUID**](UUID.md) | The ID of the email template. In the request, there should be at least one email template or callout. | [optional]
**eventTypeName** | **String** | The name of the event type. | [optional]
**filterRule** | [**GETPublicNotificationDefinitionResponseFilterRule**](GETPublicNotificationDefinitionResponseFilterRule.md) | | [optional]
**filterRuleParams** | [**FilterRuleParameterValues**](FilterRuleParameterValues.md) | | [optional]
**id** | [**UUID**](UUID.md) | The filter rule associated with this notification definition. | [optional]
**name** | **String** | The name of the notification definition. | [optional]
**updatedBy** | [**UUID**](UUID.md) | The ID of the user who updated the notification definition. | [optional]
**updatedOn** | [**OffsetDateTime**](OffsetDateTime.md) | The time when the notification was updated. Specified in the UTC timezone in the ISO860 format (YYYY-MM-DDThh:mm:ss.sTZD). E.g. 1997-07-16T19:20:30.45+00:00 | [optional]
| 2fd41847ebcfa7a0b00246d24a74b80681f7df15 | [
"Markdown",
"Java",
"Gradle"
] | 354 | Markdown | keylightberlin/zuora-sdk | d45612fe646aa814145ddaf50ef4b6f008e662a6 | fb0f352b48a0a27d9da79370702570052be4fa14 |
refs/heads/master | <repo_name>Aaroneld/portfolio<file_sep>/src/portfolio.js
import React from 'react'
import "./App"
function Portfolio () {
return (
<div className="portfolio-div">
<h2>Portfolio</h2>
<div className="project-div">
<h3>Mock Marketing Page</h3>
<p>description</p>
<p>role I played</p>
<a href="#">link to deploy</a>
<a href="#">link to repo</a>
</div>
</div>
)
}
export default Portfolio;<file_sep>/src/intro.js
import React from 'react'
import "./App"
import myPhoto from "./images/myphoto.jpg"
function Intro () {
return (
<div className="intro-div">
<img src={myPhoto}></img>
<div className="intro-text">
<h2><NAME></h2>
<p><EMAIL> -
(518) 703-3243 - <a href="github.com/Aaroneld">
github
</a>
</p>
</div>
</div>
)
}
export default Intro; | fcd6971e7e9d450027a9cf5f44baacccb4d16915 | [
"JavaScript"
] | 2 | JavaScript | Aaroneld/portfolio | 13ab5f57db7c00b771957cdb0785faa6a0540ac2 | 827fb372a92c04ce595914d1f8a5ae87e46a1f47 |
refs/heads/master | <file_sep>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include<windows.h>
#include <glut.h>
#include<dos.h>
#include<math.h>
#define BLACK 0
void *font = GLUT_BITMAP_TIMES_ROMAN_24;
void *fonts[] =
{
GLUT_BITMAP_9_BY_15,
GLUT_BITMAP_TIMES_ROMAN_10,
GLUT_BITMAP_TIMES_ROMAN_24
};
void selectFont(int newfont)
{
font = fonts[newfont];
glutPostRedisplay();
}
void output(int x, int y, char *string)
{
int len, i;
glRasterPos2f(x, y);
len = (int) strlen(string);
for (i = 0; i < len; i++)
{
glutBitmapCharacter(font, string[i]);
}
}
void
tick(void)
{
glutPostRedisplay();
}
static GLfloat translate[]={0.0,0.0,0.0};
static GLfloat translate1[]={0.0,0.0,0.0};
int wallx=0.0, wally=0.0, boxx=0.0,boxy=0.0;
int flag=0;
int xc=0.0;
int anglel_l=0.0, anglel_r=0.0;
int _anglel=0.0, _angler=0.0;
GLint sqr[3][20]={{100.0,300.0,300.0,100.0,180.0,220.0,220.0,180.0,100.0,140.0,200.0,100.0,200.0,260.0,300.0,200.0,200.0,180.0,220.0,200.0},{100.0,100.0,300.0,300.0,300.0,300.0,420.0,420.0,440.0,380.0,440.0,440.0,440.0,380.0,440.0,440.0,440.0,420.0,420.0,440.0},{1.0,1.0,1.0,1.0}};
GLint l_arm[3][7]= {{100.0,20.0,20.0,60.0,60.0,100.0,100.0},{260.0,260.0,180.0,180.0,220.0,220.0,260.0},{1.0,1.0,1.0}};
GLint r_arm[3][7]= {{300.0,380.0,380.0,340.0,340.0,300.0,300.0},{260.0,260.0,180.0,180.0,220.0,220.0,260.0},{1.0,1.0,1.0}};
GLint limbs_l[3][7]= {{100.0,60.0,60.0,100.0,60.0,20.0,60.0},{120.0,120.0,20.0,20.0,120.0,20.0,20.0},{1.0,1.0,1.0}};
GLint limbs_r[3][7]= {{300.0,340.0,340.0,300.0,340.0,380.0,340.0},{120.0,120.0,20.0,20.0,120.0,20.0,20.0},{1.0,1.0,1.0}};
GLfloat s_arm[3][8]={{30.0,50.0,50.0,20.0,350.0,370.0,380.0,350.0},{180.0,180.0,140.0,140.0,180.0,180.0,140.0,140.0},{1.0,1.0,1.0}};
GLfloat rect[3][10]={{100.0,100.0,300.0,300.0,100.0,180.0,180.0,220.0,220.0,180.0},{220.0,300.0,300.0,220.0,220.0,100.0,220.0,220.0,100.0,100.0,},{1.0,1.0,1.0}};
GLfloat w_box[3][4]={{380.0,380.0,520.0,520.0},{100.0,240.0,240.0,100.0},{1.0,1.0,1.0}};
GLfloat can[3][4] ={{380.0,380.0,440.0,440.0},{380.0,480.0,480.0,380.0},{1.0,1.0,1.0}};
GLfloat roadvertex[][2]={{0.0,0.0},{0.0,120.0},{1280.0,120.0},{1280.0,0.0}};
GLint house[][2]={{560,300},{560,450},{620,450},{620,300}};
GLint house1[][2]={{560,120},{560,300},{620,300},{620,120}};
GLint house2[][2]={{0,120},{0,350},{50,350},{50,120}};// 1st building
GLint house3[][2]={{70,120},{70,380},{130,380},{130,120}};// 3rd building
GLint house4[][2]={{25,120},{25,420},{100,420},{100,120}};// 2nd building
GLint house5[][2]={{140,120},{140,280},{190,280},{190,120}};// 5th building
GLint house6[][2]={{110,120},{110,320},{170,320},{170,120}};// 4th building
void box()
{
glPushMatrix();
glTranslatef(boxx,boxy,0.0);
glColor3f(0.81,0.71,0.23);
glBegin(GL_POLYGON);
glTexCoord2f(0.0,0.0);
glVertex2f(w_box[0][0], w_box[1][0]);
glTexCoord2f(1.0,0.0);
glVertex2f(w_box[0][1], w_box[1][1]);
glTexCoord2f(1.0,1.0);
glVertex2f(w_box[0][2], w_box[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(w_box[0][3], w_box[1][3]);
glEnd();
glPopMatrix();
}
void road()
{
glColor3f(0.3,0.3,0.3);
glPushMatrix(); // to draw road
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(roadvertex[0][0],roadvertex[0][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(roadvertex[1][0],roadvertex[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(roadvertex[2][0],roadvertex[2][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(roadvertex[3][0],roadvertex[3][1]);
glEnd();
glPopMatrix();
}
void drawhouse2() // 1st building
{
glColor3f(0.79279,0.88288,1.0);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(house2[0][0],house2[0][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house2[1][0],house2[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(house2[2][0],house2[2][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house2[3][0],house2[3][1]);
glEnd();
}
void drawhouse3() //3rd building
{
glColor3f(1.0,0.93725,0.83529);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(house3[0][0],house3[0][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house3[1][0],house3[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(house3[2][0],house3[2][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house3[3][0],house3[3][1]);
glEnd();
}
void drawhouse4() //2nd building
{
glColor3f(1.0,0.82882,0.60810);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(house4[0][0],house4[0][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house4[1][0],house4[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(house4[2][0],house4[2][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house4[3][0],house4[3][1]);
glEnd();
}
void drawhouse5() //5th building
{
glColor3f(1.0,0.96,0.92);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(house5[0][0],house5[0][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house5[1][0],house5[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(house5[2][0],house5[2][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house5[3][0],house5[3][1]);
glEnd();
}
void drawhouse6() //4th building
{
glColor3f(1.0,0.67213,0.39344);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(house6[0][0],house6[0][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house6[1][0],house6[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(house6[2][0],house6[2][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house6[3][0],house6[3][1]);
glEnd();
}
void drawhouse()
{
glColor3f(0.329412,0.329412,0.329412);
glPushMatrix();
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(house[0][0],house[0][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house[1][0],house[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(house[2][0],house[2][1]);
glTexCoord2f(0.0,1.0);
glVertex2f(house[3][0],house[3][1]);
glEnd();
glPopMatrix();
}
void windtow()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2i(570,440);
glVertex2i(610,440);
glVertex2i(610,430);
glVertex2i(570,430);
glEnd();
}
void windtow2()
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2i(570,290);
glVertex2i(610,290);
glVertex2i(610,280);
glVertex2i(570,280);
glEnd();
}
void window() //window 1st buliding
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2i(5,340);
glVertex2i(40,340);
glVertex2i(40,330);
glVertex2i(5,330);
glEnd();
}
void window1() //window 2nd building
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2i(30,410);
glVertex2i(95,410);
glVertex2i(95,400);
glVertex2i(30,400);
glEnd();
}
void window2() //window 3rd building
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2i(75,370);
glVertex2i(125,370);
glVertex2i(125,360);
glVertex2i(75,360);
glEnd();
}
void window3() //window 4th building
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2i(115,310);
glVertex2i(165,310);
glVertex2i(165,300);
glVertex2i(115,300);
glEnd();
}
void window4() //window 5th building
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2i(145,270);
glVertex2i(185,270);
glVertex2i(185,260);
glVertex2i(145,260);
glEnd();
}
void backg1()
{
glColor3f(0.52,0.39,0.39);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(w_box[0][0], w_box[1][0]);
glTexCoord2f(0.0,1.0);
glVertex2f(w_box[0][1], w_box[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(w_box[0][2], w_box[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(w_box[0][3], w_box[1][3]);
glEnd();
}
void drawpixel(GLint ex, GLint ey)
{
glColor3f(0.0,0.0,0.0);
glBegin(GL_POINTS);
glVertex2i(ex,ey);
glEnd();
}
void plotpixel(GLint h, GLint k, GLint x, GLint y)
{
drawpixel(x+h,y+k);
drawpixel(-x+h,y+k);
drawpixel(x+h,-y+k);
drawpixel(-x+h,-y+k);
drawpixel(y+h,x+k);
drawpixel(-y+h,x+k);
drawpixel(y+h,-x+k);
drawpixel(-y+h,-x+k);
}
void circle_draw(GLint h, GLint k, GLint r)
{
GLint d=1-r, x=0, y=r;
while(y>x)
{
plotpixel(h,k,x,y);
if(d<0)
d+=(2*x+3);
else
{
d+=(2*(x-y)+5);
--y;
}
++x;
}
plotpixel(h,k,x,y);
}
void wall_e()
{
glPushMatrix();
glTranslatef(wallx,wally,0.0);
glColor3f(0.85,0.53,0.10);
glBegin(GL_POLYGON);
glTexCoord2f(0.0,0.0);
glVertex2f(sqr[0][0], sqr[1][0]);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][1], sqr[1][1]);
glTexCoord2f(1.0,1.0);
glVertex2f(sqr[0][2], sqr[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][3], sqr[1][3]);
glEnd();
glColor3f(0.85,0.53,0.10);
glBegin(GL_POLYGON);
glTexCoord2f(0.0,0.0);
glVertex2f(sqr[0][4], sqr[1][4]);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][5], sqr[1][5]);
glTexCoord2f(1.0,1.0);
glVertex2f(sqr[0][6], sqr[1][6]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][7], sqr[1][7]);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.81,0.71,0.23);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][8], sqr[1][8]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][9], sqr[1][9]);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][10], sqr[1][10]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][11], sqr[1][11]);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.81,0.71,0.23);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][12], sqr[1][12]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][13], sqr[1][13]);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][14], sqr[1][14]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][15], sqr[1][15]);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.25,0.0);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][16], sqr[1][16]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][17], sqr[1][17]);
glTexCoord2f(1.0,0.0);
glVertex2f(sqr[0][18], sqr[1][18]);
glTexCoord2f(0.0,1.0);
glVertex2f(sqr[0][19], sqr[1][19]);
glEnd(); //Square and triangle!!!
glColor3f(0.65,0.49,0.24);
glBegin(GL_POLYGON);
glTexCoord2f(0.0,0.0);
glVertex2f(rect[0][0], rect[1][0]);
glTexCoord2f(1.0,0.0);
glVertex2f(rect[0][1], rect[1][1]);
glTexCoord2f(1.0,1.0);
glVertex2f(rect[0][2], rect[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(rect[0][3], rect[1][3]);
glTexCoord2f(0.0,0.0);
glVertex2f(rect[0][4], rect[1][4]);
glEnd();
glColor3f(0.65,0.49,0.24);
glBegin(GL_POLYGON);
glTexCoord2f(0.0,0.0);
glVertex2f(rect[0][5], rect[1][5]);
glTexCoord2f(1.0,0.0);
glVertex2f(rect[0][6], rect[1][6]);
glTexCoord2f(1.0,1.0);
glVertex2f(rect[0][7], rect[1][7]);
glTexCoord2f(0.0,1.0);
glVertex2f(rect[0][8], rect[1][8]);
glTexCoord2f(0.0,0.0);
glVertex2f(rect[0][9], rect[1][9]);
glEnd(); //The Rectangles inside the square
glPushMatrix();
glTranslatef(100.0,260.0,0.0);
glRotatef(_anglel,0.0,0.0,1.0);
glTranslatef(-100.0,-260.0,0.0);
glColor3f(0.68,0.49,0.24);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(l_arm[0][0], l_arm[1][0]);
glTexCoord2f(0.0,1.0);
glVertex2f(l_arm[0][1], l_arm[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(l_arm[0][2], l_arm[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(l_arm[0][3], l_arm[1][3]);
glTexCoord2f(1.0,0.0);
glVertex2f(l_arm[0][4], l_arm[1][4]);
glTexCoord2f(0.0,1.0);
glVertex2f(l_arm[0][5], l_arm[1][5]);
glEnd(); //The left Big arm
glBegin(GL_POLYGON);
glColor3f(0.85,0.53,0.10);
glTexCoord2f(1.0,0.0);
glVertex2f(s_arm[0][0], s_arm[1][0]);
glTexCoord2f(0.0,1.0);
glVertex2f(s_arm[0][1], s_arm[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(s_arm[0][2], s_arm[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(s_arm[0][3], s_arm[1][3]);
glEnd(); //The Left Small Arm
glPointSize(8.0);
circle_draw(40,180,15);
glPopMatrix();
glPushMatrix();
glTranslatef(300.0,260.0,0.0);
glRotatef(_angler,0.0,0.0,1.0);
glTranslatef(-300.0,-260.0,0.0);
glColor3f(0.68,0.49,0.24);
glBegin(GL_POLYGON);
glTexCoord2f(1.0,0.0);
glVertex2f(r_arm[0][0], r_arm[1][0]);
glTexCoord2f(0.0,1.0);
glVertex2f(r_arm[0][1], r_arm[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(r_arm[0][2], r_arm[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(r_arm[0][3], r_arm[1][3]);
glTexCoord2f(1.0,0.0);
glVertex2f(r_arm[0][4], r_arm[1][4]);
glTexCoord2f(0.0,1.0);
glVertex2f(r_arm[0][5], r_arm[1][5]);
glEnd(); //The right Big arm
glBegin(GL_POLYGON);
glColor3f(0.85,0.53,0.10);
glTexCoord2f(1.0,0.0);
glVertex2f(s_arm[0][4], s_arm[1][4]);
glTexCoord2f(0.0,1.0);
glVertex2f(s_arm[0][5], s_arm[1][5]);
glTexCoord2f(0.0,1.0);
glVertex2f(s_arm[0][6], s_arm[1][6]);
glTexCoord2f(0.0,1.0);
glVertex2f(s_arm[0][7], s_arm[1][7]);
glEnd(); //The Right Small Arm
glPointSize(8.0);
circle_draw(360,180,15);
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,120.0,0.0);
glRotatef(anglel_l,0.0,0.0,1.0);
glTranslatef(-100.0,-120.0,0.0);
glBegin(GL_POLYGON);
glColor3f(0.68,0.49,0.24);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_l[0][0], limbs_l[1][0]);
glTexCoord2f(0.0,1.0);
glVertex2f(limbs_l[0][1], limbs_l[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_l[0][2], limbs_l[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(limbs_l[0][3], limbs_l[1][3]);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.68,0.49,0.24);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_l[0][4], limbs_l[1][4]);
glTexCoord2f(0.0,1.0);
glVertex2f(limbs_l[0][5], limbs_l[1][5]);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_l[0][6], limbs_l[1][6]);
glEnd();
glPopMatrix();
glPushMatrix();
glTranslatef(300.0,120.0,0.0);
glRotatef(anglel_r,0.0,0.0,1.0);
glTranslatef(-300.0,-120.0,0.0);
glBegin(GL_POLYGON);
glColor3f(0.68,0.49,0.24);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_r[0][0], limbs_r[1][0]);
glTexCoord2f(0.0,1.0);
glVertex2f(limbs_r[0][1], limbs_r[1][1]);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_r[0][2], limbs_r[1][2]);
glTexCoord2f(0.0,1.0);
glVertex2f(limbs_r[0][3], limbs_r[1][3]);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.68,0.49,0.24);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_r[0][4], limbs_r[1][4]);
glTexCoord2f(0.0,1.0);
glVertex2f(limbs_r[0][5], limbs_r[1][5]);
glTexCoord2f(1.0,0.0);
glVertex2f(limbs_r[0][6], limbs_r[1][6]);
glEnd(); //The Limbs
glPopMatrix();
circle_draw(80,240,30);
circle_draw(320,240,30);
glPushMatrix();
glTranslatef(0.0,xc,0.0);
glPointSize(5.0);
circle_draw(260,440,20);
circle_draw(140,440,20);
glPopMatrix();
glPointSize(8.0);
circle_draw(80,120,25);
circle_draw(320,120,25); //The other circles...
glPopMatrix();
}
void mouse(int btn, int state, int x, int y)
{
if(btn==GLUT_RIGHT_BUTTON&&state==GLUT_DOWN)
{
wallx+=5;
boxx+=5;
if(flag==0)
{
anglel_l-=10;
anglel_r+=10;
xc=5.0;
}
else if(flag==1)
{
anglel_l+=10;
anglel_r-=10;
xc=0.0;
}
if(anglel_l<=-30)
flag=1;
if(anglel_l>=0)
flag=0;
glutPostRedisplay();
} //Moves Wall-E right with the waste-box
if(btn==GLUT_LEFT_BUTTON&&state==GLUT_DOWN)
{
wallx-=5;
boxx-=5;
if(flag==0)
{
anglel_l-=10;
anglel_r+=10;
xc=5.0;
}
else if(flag==1)
{
anglel_l+=10;
anglel_r-=10;
xc=0.0;
}
if(anglel_l<=-30)
flag=1;
if(anglel_l>=0)
flag=0;
glutPostRedisplay(); //Moves Wall-E left with the waste-box
}
}
int i;
void keys(unsigned char key, int x, int y)
{
if(key=='x') //Moves Wall-e to right
{
wallx+=5;
if(flag==0)
{
anglel_l-=10;
anglel_r+=10;
xc=5.0;
}
else if(flag==1)
{
anglel_l+=10;
anglel_r-=10;
xc=0.0;
}
if(anglel_l<=-30)
flag=1;
if(anglel_l>=0)
flag=0;
}
if(key=='z') //Moves Wall-e to left
{
wallx-=5;
if(flag==0)
{
anglel_l-=10;
anglel_r+=10;
xc=5.0;
}
else if(flag==1)
{
anglel_l+=10;
anglel_r-=10;
xc=0.0;
}
if(anglel_l<=-30)
flag=1;
if(anglel_l>=0)
flag=0;
}
if(key=='y') //Moves Wall-e to up
{
wally+=5;
if(flag==0)
{
anglel_l-=10;
anglel_r+=10;
xc=5.0;
}
else if(flag==1)
{
anglel_l+=10;
anglel_r-=10;
xc=0.0;
}
if(anglel_l<=-30)
flag=1;
if(anglel_l>=0)
flag=0;
}
if(key=='h') //Moves Wall-E down
{
wally-=5;
if(flag==0)
{
anglel_l-=10;
anglel_r+=10;
xc=5.0;
}
else if(flag==1)
{
anglel_l+=10;
anglel_r-=10;
xc=0.0;
}
if(anglel_l<=-30)
flag=1;
if(anglel_l>=0)
flag=0;
}
if(key=='q') //Moves left hand to left
{
_anglel-=1;
}
if(key=='w') //Moves left hand to right
{
_anglel+=1;
}
if(key=='o') //Moves right hand to left
{
_angler-=1;
}
if(key=='p') //Moves right hand to right
{
_angler+=1;
}
if(key=='a')
{
wally+=5;
boxy+=5;
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glColor3f(0.85,0.85,0.10);
drawhouse4(); // 2nd building
glPushMatrix();
window1(); //window for 2nd building
for( i=0;i<=11;i++)
{
glTranslated(0.0,-20.0,0.0);
window1();
}
glPopMatrix();
drawhouse2(); // 1st building
glPushMatrix();
window(); //window for 1st building
for( i=0;i<=8;i++)
{
glTranslated(0.0,-20.0,0.0);
window();
}
glPopMatrix();
glPushMatrix();
glTranslatef(0.0,-translate1[0],0.0);
drawhouse();
glPushMatrix();
windtow();
for( i=0;i<=5;i++)
{
glTranslated(0.0,-20.0,0.0);
windtow();
}
glPopMatrix();
glPopMatrix();
drawhouse6(); // 4th building
glPushMatrix();
window3(); //window for 4th building
for( i=0;i<=7;i++)
{
glTranslated(0.0,-20.0,0.0);
window3();
}
glPopMatrix();
drawhouse3(); // 3rd building
glPushMatrix();
window2(); // window for 3rd building
for( i=0;i<=10;i++)
{
glTranslated(0.0,-20.0,0.0);
window2();
}
glPopMatrix();
road();
drawhouse5(); //5th building
glPushMatrix();
window4(); // window for 5th building
for( i=0;i<=5;i++)
{
glTranslated(0.0,-20.0,0.0);
window4();
}
glPopMatrix();
glPushMatrix();
glTranslatef(50.0,50.0,0.0);
glScalef(0.45,0.35,0.0);
wall_e();
box();
glPopMatrix();
output(100, 440, "Wall-E");
glutSwapBuffers();
glFlush();
}
void init()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,500.0,0.0,500.0);
glClearColor(0.59,0.41,0.31,1.0);
glColor3f(0.0,0.0,0.0);
}
int main(int argc, char **argv)
{
GLubyte image[64][64][3];
int i,j,c;
for(i=0;i<64;i++)
{
for(j=0;j<64;j++)
{
c=((((i&0x8)==0)^((j&0x8))==0))*255;
image[i][j][0]=(GLubyte) c;
image[i][j][1]=(GLubyte) c;
image[i][j][2]=(GLubyte) c;
}
}
glutInit(&argc, argv);
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-mono")) {
font = GLUT_BITMAP_9_BY_15;
}
}
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(1000, 1000);
glutCreateWindow("Wall-E");
glutDisplayFunc(display);
glutIdleFunc(tick);
glutKeyboardFunc(keys);
glutMouseFunc(mouse);
glEnable(GL_TEXTURE_2D);
glTexImage2D(GL_TEXTURE_2D,0,3,64,64,0,GL_RGB,GL_UNSIGNED_BYTE,image);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
init();
glutMainLoop();
return 0;
}
| fcef1794fdf793488f8832758fd2dd8b3355844b | [
"C"
] | 1 | C | sharadaryaz/Wall_E | a233b321849a5b26da44570b058ba4c2b2aee166 | 0e642100314fc4e79cb851345a69da25e1cce677 |
refs/heads/master | <repo_name>Kohara66/RecordStoreProject<file_sep>/src/main/java/Record.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by dilli on 4/17/2017.
*/
public class Record extends JFrame{
private JTextField ConsignorNameTextField;
private JTextField PriceTextField;
private JTextField TitleTextField;
private JTextField ArtistNameTextField;
private JTextField PhoneNoTextField;
private JComboBox AddToComboBox;
private JComboBox DisplayComboBox;
private JPanel rootPanel;
private JButton addRecordButton;
private JButton showRecordButton;
private JComboBox ReturnComboBox;
private JButton deleteRecordButton;
private JList<RecordObject> InventoryJList;
private JList<RecordObjectSold> SoldItemJList;
private JList<BargainListObject> BargainJList;
private JList<PayInfoObject> PayInfoJList;
private JLabel DisplayDaysJLabel;
private JButton displayNoOfDaysButton;
private JLabel NotifyConsignorLabel;
private DefaultListModel<RecordObject> InventoryListModel;
private DefaultListModel<RecordObjectSold> SoldItemListModel;
private DefaultListModel<PayInfoObject> PayInfoListModel;
private DefaultListModel<BargainListObject> BargainListModel;
private RecordDBcontroller recordDBcontroller;
Record(RecordDBcontroller recordDBcontroller){
setPreferredSize(new Dimension(800,400));
this.recordDBcontroller = recordDBcontroller;
InventoryListModel = new DefaultListModel<RecordObject>();
SoldItemListModel = new DefaultListModel<RecordObjectSold>();
PayInfoListModel = new DefaultListModel<PayInfoObject>();
BargainListModel = new DefaultListModel<BargainListObject>();
InventoryJList.setModel(InventoryListModel);
SoldItemJList.setModel(SoldItemListModel);
PayInfoJList.setModel(PayInfoListModel);
BargainJList.setModel(BargainListModel);
setContentPane(rootPanel);
addItemsToComboBox();
pack();
setVisible(true);
addListeners();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void addItemsToComboBox(){
AddToComboBox.addItem("Inventory");
AddToComboBox.addItem("Sold Item");
AddToComboBox.addItem("Bargain List");
AddToComboBox.addItem("Donate Item");
DisplayComboBox.addItem("All Inventory Records");
DisplayComboBox.addItem("Sold Items");
DisplayComboBox.addItem("Pay Information");
DisplayComboBox.addItem("Bargain List Item");
DisplayComboBox.addItem("No. of days in Inventory List");
ReturnComboBox.addItem("Yes");
ReturnComboBox.addItem("No");
}
private void addListeners(){
addRecordButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Read data, send message to database via controller
String cName = ConsignorNameTextField.getText();
String phone = PhoneNoTextField.getText();
String aName = ArtistNameTextField.getText();
String title = TitleTextField.getText();
java.util.Date recordDate = new java.util.Date();
java.sql.Date sqlrecordDate = new java.sql.Date(recordDate.getTime());
if(AddToComboBox.getSelectedItem().equals("Inventory")) {
if (cName.isEmpty()) {
JOptionPane.showMessageDialog(Record.this, "Enter Consignor's name");
return;
}else if(phone.isEmpty()){
JOptionPane.showMessageDialog(Record.this,"Enter the phone number");
return;
}else if(aName.isEmpty()){
JOptionPane.showMessageDialog(Record.this,"Enter name of the artist");
return;
}else if(title.isEmpty()){
JOptionPane.showMessageDialog(Record.this,"Enter the title");
return;
}
double price;
try {
price = Double.parseDouble(PriceTextField.getText());
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(Record.this, "Enter the number for price");
return;
}
RecordObject recordObjectRecord = new RecordObject(cName, phone, aName, title, price,sqlrecordDate);
recordDBcontroller.addRecordToDatabase(recordObjectRecord);
//Clear input JTextFields
ConsignorNameTextField.setText("");
PhoneNoTextField.setText("");
ArtistNameTextField.setText("");
TitleTextField.setText("");
PriceTextField.setText("");
JOptionPane.showMessageDialog(Record.this,"A record has been add to inventory list");
}
// else {
// JOptionPane.showMessageDialog(Record.this,"Please select Inventory from Add To combo box");
// return;
// }
if (AddToComboBox.getSelectedItem().equals("Sold Item") && InventoryJList.getSelectedValue()!=null){
String sPriceString = JOptionPane.showInputDialog(Record.this,"Please enter the selling price");
double sPrice = Double.parseDouble(sPriceString);
double consignorShare = sPrice*0.4;
RecordObject recordSold = InventoryJList.getSelectedValue();
String conName = recordSold.getConsignorName();
String sTitle = recordSold.getTitle();
Date soldDate = new Date();
java.sql.Date soldDateSQL = new java.sql.Date(soldDate.getTime());
RecordObjectSold recordObjectSold = new RecordObjectSold(conName,sTitle,sPrice,soldDateSQL);
recordDBcontroller.addRecordToSoldTable(recordObjectSold);
recordDBcontroller.delete(recordSold);//deletes selected object from Inventory list after it is added to sold item list.
JOptionPane.showMessageDialog(Record.this,"The selected item has been moved to sold item list");
String payNowString = JOptionPane.showInputDialog(Record.this,"Please enter the amount you want to pay now to the consignor");
double payNow = Double.parseDouble(payNowString);
double amountOwed = consignorShare - payNow;
PayInfoObject payInfoObject = new PayInfoObject(conName,consignorShare,payNow,amountOwed);
recordDBcontroller.addRecordToPayInfoTable(payInfoObject);
//RecordObject ro = InventoryJList.getSelectedValue();
//SoldItemListModel.addElement(recordObjectSold);
}
if(AddToComboBox.getSelectedItem().equals("Bargain List")){
java.sql.Date recordAddedDate = InventoryJList.getSelectedValue().getDate();
Date now = new Date();
long date = now.getTime() - recordAddedDate.getTime();
long msInDay = 1000*60*60*24;
long days = date/msInDay;
String StringDays = Long.toString(days);
int intDays = Integer.parseInt(StringDays);
int maxDaysInInventory = 30;
if(intDays<=maxDaysInInventory) {
JOptionPane.showMessageDialog(Record.this, "Oops! can't add this item to Bargain list before 30 days\n" +
"of it's stay in Inventory");
}else{
String conName = InventoryJList.getSelectedValue().getConsignorName();
String artistName = InventoryJList.getSelectedValue().getArtistName();
String rTitle = InventoryJList.getSelectedValue().getTitle();
double basePrice = 1;
BargainListObject bargainListObject = new BargainListObject(conName,rTitle, artistName,basePrice);
recordDBcontroller.addRecordToBargainTable(bargainListObject);
}
}
// else{
// JOptionPane.showMessageDialog(Record.this,"Oops! missing correct selection");
// }
}
});
showRecordButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(DisplayComboBox.getSelectedItem().equals("All Inventory Records")){
//request all data from database to update list
ArrayList<RecordObject> allData = recordDBcontroller.getAllData();
setListData(allData);
}
if(DisplayComboBox.getSelectedItem().equals("Sold Items")){
ArrayList<RecordObjectSold> allSoldData = recordDBcontroller.getAllSoldData();
setListOfSoldData(allSoldData);
}
if(DisplayComboBox.getSelectedItem().equals("Pay Information")){
ArrayList<PayInfoObject> allPayInfoData = recordDBcontroller.getAllPayInfoData();
setListOfPayInfoData(allPayInfoData);
}
if(DisplayComboBox.getSelectedItem().equals("No. of days in Inventory List")){
if(InventoryJList.getSelectedValue()!=null) {
displayNumberOfDays();
}else {
JOptionPane.showMessageDialog(Record.this,"Please select an item from the Inventory list to display number of days");
}
}
if(DisplayComboBox.getSelectedItem().equals("Bargain List Item")){
ArrayList<BargainListObject> allBargainListData = recordDBcontroller.getAllBargainListData();
setListOfBargainListData(allBargainListData);
}
}
});
deleteRecordButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RecordObject recordObject = InventoryJList.getSelectedValue();
if (recordObject == null) {
JOptionPane.showMessageDialog(Record.this, "Please select the record to delete");
} else if (!ReturnComboBox.getSelectedItem().equals("Yes")) {
JOptionPane.showMessageDialog(Record.this, "Please select 'Yes' from the 'Return to Consignor?' combox box");
}
if (recordObject!=null && ReturnComboBox.getSelectedItem().equals("Yes")){
int delete = JOptionPane.showConfirmDialog(Record.this, "Are you sure you want to delete this item?",
"Delete", JOptionPane.OK_CANCEL_OPTION);
if(delete == JOptionPane.OK_OPTION) {
recordDBcontroller.delete(recordObject);
ArrayList<RecordObject> recordObject1 = recordDBcontroller.getAllData();
setListData(recordObject1);
JOptionPane.showMessageDialog(Record.this, "The selected item has been deleted from the list");
}
}
}
});
displayNoOfDaysButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
displayNumberOfDays();
}
});
showRecordButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
}
private void displayNumberOfDays(){
java.sql.Date displayDays = InventoryJList.getSelectedValue().getDate();
Date now = new Date();
long date = now.getTime() - displayDays.getTime();
long msInDay = 1000*60*60*24;
long days = date/msInDay;
String StringDays = Long.toString(days);
int intDays = Integer.parseInt(StringDays);
DisplayDaysJLabel.setText(StringDays);
if(intDays>30){
NotifyConsignorLabel.setText("Notify consignor to pick item");
}else{
int daysDiff = 30-intDays;
String daysDiffString = Integer.toString(daysDiff);
NotifyConsignorLabel.setText(daysDiffString+" days to stay in this list");
}
}
void setListData(ArrayList<RecordObject> data) {
InventoryListModel.clear();
//add cubes object to display list model.
for (RecordObject rob : data) {
InventoryListModel.addElement(rob);
}
}
void setListOfSoldData(ArrayList<RecordObjectSold> soldData){
SoldItemListModel.clear();
for(RecordObjectSold robs : soldData){
SoldItemListModel.addElement(robs);
}
}
void setListOfPayInfoData(ArrayList<PayInfoObject> payInfoData){
PayInfoListModel.clear();
for(PayInfoObject pob : payInfoData){
PayInfoListModel.addElement(pob);
}
}
void setListOfBargainListData(ArrayList<BargainListObject> bargainListData){
BargainListModel.clear();
for(BargainListObject bob: bargainListData){
BargainListModel.addElement(bob);
}
}
}<file_sep>/src/main/java/RecordDBcontroller.java
import java.util.ArrayList;
/**
* Created by dilli on 4/17/2017.
*/
public class RecordDBcontroller {
static Record record;
static RecordDB recordDB;
public static void main(String[] args) {
RecordDBcontroller recordDBcontroller = new RecordDBcontroller();
recordDBcontroller.startApp();
}
private void startApp(){
recordDB = new RecordDB();
recordDB.createTable();
//ArrayList<RecordObject> allData = recordDB.fetchAllRecords();
record = new Record(this);
//record.setListData(allData);
}
void delete(RecordObject recordObject){
recordDB.delete(recordObject);
}
// void updateRecord(RecordObject recordObject){
// recordDB.updateRecord(recordObject);
// }
ArrayList<RecordObject> getAllData() {
return recordDB.fetchAllRecords();
}
ArrayList<RecordObjectSold> getAllSoldData(){
return recordDB.fetchAllSoldRecords();
}
ArrayList<PayInfoObject> getAllPayInfoData(){
return recordDB.fetchAllPayInfoRecords();
}
ArrayList<BargainListObject> getAllBargainListData(){
return recordDB.fetchAllBargainListRecords();
}
void addRecordToDatabase(RecordObject recordObject) {
recordDB.addRecord(recordObject);
}
void addRecordToSoldTable(RecordObjectSold recordObjectSold){
recordDB.addRecordToSoldItemTable(recordObjectSold);
}
void addRecordToPayInfoTable(PayInfoObject payInfoObject){
recordDB.addRecordToPayInfoItemTable(payInfoObject);
}
void addRecordToBargainTable(BargainListObject bargainListObject){
recordDB.addRecordToBargainListTable(bargainListObject);
}
}
| eb14a1ccfb89063d4b31da939141ffe13f468c6c | [
"Java"
] | 2 | Java | Kohara66/RecordStoreProject | 95c5696df0f36045e15cb8d114b7f4260c055a8a | 2a8b7b2f78dff2f0aa1e9bc62667c427936eab62 |
refs/heads/master | <repo_name>zitsen/unqlite-sys.rs<file_sep>/CHANGELOG.md
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [0.3.0] - 2015-12-23-11:48:38
### Added
- Features for all compile-time options support.
- Added this changelog file.
### Fixed
- Fixed constants in match pattern.
## [0.2.0] - 2015-12-21-17:25:35
### Changed
- Use submod for constants.
### Removed
- Remove constants: version, copyright, ident.
### Fixed
- Fix crate metadata documentation URL error.
## [0.1.0] - 2015-12-21-17:05:23
### Added
- First release for unqlite bindings.
[0.1.0]: https://github.com/zitsen/unqlite-sys.rs/releases/tag/0.1.0
[0.2.0]: https://github.com/zitsen/unqlite-sys.rs/releases/tag/0.2.0
[0.3.0]: https://github.com/zitsen/unqlite-sys.rs/releases/tag/0.3.0
<file_sep>/src/lib.rs
//! Rust bindings for [UnQlite][] library.
//!
//! [![travis-badge][]][travis] [![release-badge][]][cargo] [![downloads]][cargo]
//! [![docs-badge][]][docs] [![license-badge][]][cargo]
//!
//! As its official site says, **UnQlite** is
//! > An Embeddable NoSQL Database Engine.
//!
//! Please see [UnQLite C/C++ API Reference][] for full API documents.
//!
//! # Usage
//!
//! This crate provides several features for [UnQlite compile-time
//! options][apidoc-compile]:
//!
//! * **enable-threads**: equivalent to `UNQLITE_ENABLE_THREADS` enabled.
//! * **jx9-disable-builtin-func**: equivalent to `JX9_DISABLE_BUILTIN_FUNC` enabled.
//! * **jx9-enable-math-fuc**: equivalent to `JX9_ENABLE_MATH_FUNC` enabled.
//! * **jx9-disable-disk-io**: equivalent to `JX9_DISABLE_DISK_IO` enabled.
//! * **enable-jx9-hash-io**: equivalent to `UNQLITE_ENABLE_JX9_HASH_IO` enabled.
//!
//! To provide the same default behavior as original C does, non of the features
//! is enabled by default. When you want some features, such as **enable-threads**,
//! just config in `Cargo.toml`:
//!
//! ```toml
//! [dependencies.unqlite-sys]
//! version = "0.3"
//! features = [ "enable-threads" ]
//! ```
//!
//! For multiple features just add them in toml `features` array.
//!
//! # Threadsafe
//!
//! Note that even "enable-threads" is featured in your crate, it's not meant
//! that your code is threadsafe.
//!
//! > When UnQLite has been compiled with threading support then the threading mode can be altered
//! at run-time using the unqlite_lib_config() interface together with one of these verbs:
//!
//! >> UNQLITE_LIB_CONFIG_THREAD_LEVEL_SINGLE
//!
//! >> UNQLITE_LIB_CONFIG_THREAD_LEVEL_MULTI
//!
//! > Platforms others than Windows and UNIX systems must install their own mutex subsystem via
//! unqlite_lib_config() with a configuration verb set to UNQLITE_LIB_CONFIG_USER_MUTEX. Otherwise
//! the library is not threadsafe.
//! >
//! > Note that you must link UnQLite with the POSIX threads library under UNIX systems (i.e:
//! -lpthread).
//!
//! To use in multithread cases, that is **threadsafe**, you may use like this:
//!
//! ```no_run
//! extern crate unqlite_sys as ffi;
//! use ffi::constants as ffic;
//!
//! fn main() {
//! unsafe {
//! ffi::unqlite_lib_config(ffic::UNQLITE_LIB_CONFIG_THREAD_LEVEL_MULTI);
//! ffi::unqlite_lib_init();
//! assert_eq!(ffi::unqlite_lib_is_threadsafe(), 1);
//!
//! // do stuff ...
//!
//! }
//! }
//! ```
//!
//! [UnQlite]: http://unqlite.org
//! [UnQLite C/C++ API Reference]: http://unqlite.org/c_api.html
//! [travis-badge]: https://img.shields.io/travis/zitsen/unqlite-sys.rs.svg?style=flat-square
//! [travis]: https://travis-ci.org/zitsen/unqlite-sys.rs
//! [release-badge]: https://img.shields.io/crates/v/unqlite-sys.svg?style=flat-square
//! [downloads]: https://img.shields.io/crates/d/unqlite-sys.svg?style=flat-square
//! [cargo]: https://crates.io/crates/unqlite-sys
//! [docs-badge]: https://img.shields.io/badge/API-docs-blue.svg?style=flat-square
//! [docs]: https://zitsen.github.io/unqlite-sys.rs
//! [license-badge]: https://img.shields.io/crates/l/unqlite-sys.svg?style=flat-square
//! [apidoc-compile]: http://unqlite.org/c_api_const.html#compile_time
#[allow(dead_code)]
pub mod constants;
pub use self::bindgen::*;
#[allow(dead_code, non_snake_case, non_camel_case_types)]
#[cfg_attr(rustfmt, rustfmt_skip)]
mod bindgen;
#[cfg(test)]
mod tests {
use super::{unqlite_lib_config, unqlite_lib_init, unqlite_lib_is_threadsafe,
unqlite_lib_shutdown};
use super::constants as ffic;
#[cfg(feature = "enable-threads")]
#[test]
fn is_threadsafe() {
unsafe {
unqlite_lib_config(ffic::UNQLITE_LIB_CONFIG_THREAD_LEVEL_MULTI);
unqlite_lib_init();
assert_eq!(unqlite_lib_is_threadsafe(), 1);
unqlite_lib_shutdown();
unqlite_lib_config(ffic::UNQLITE_LIB_CONFIG_THREAD_LEVEL_SINGLE);
unqlite_lib_init();
assert_eq!(unqlite_lib_is_threadsafe(), 0);
unqlite_lib_shutdown();
}
}
#[cfg(not(feature = "enable-threads"))]
#[test]
fn not_threadsafe() {
unsafe {
unqlite_lib_config(ffic::UNQLITE_LIB_CONFIG_THREAD_LEVEL_MULTI);
unqlite_lib_init();
assert_eq!(unqlite_lib_is_threadsafe(), 0);
unqlite_lib_shutdown();
unqlite_lib_config(ffic::UNQLITE_LIB_CONFIG_THREAD_LEVEL_SINGLE);
unqlite_lib_init();
assert_eq!(unqlite_lib_is_threadsafe(), 0);
unqlite_lib_shutdown();
}
}
}
<file_sep>/build.rs
extern crate gcc;
fn main() {
gcc::Config::new().file("src/unqlite.c")
.if_enable_threads()
.if_jx9_diable_builtin_func()
.if_jx9_enable_math_func()
.if_jx9_disable_disk_io()
.if_enable_jx9_hash_io()
.compile("libunqlite.a");
}
trait ConfigExt {
fn if_enable_threads(&mut self) -> &mut Self {
self
}
fn if_jx9_diable_builtin_func(&mut self) -> &mut Self {
self
}
fn if_jx9_enable_math_func(&mut self) -> &mut Self {
self
}
fn if_jx9_disable_disk_io(&mut self) -> &mut Self {
self
}
fn if_enable_jx9_hash_io(&mut self) -> &mut Self {
self
}
}
impl ConfigExt for gcc::Config {
#[cfg(feature = "enable-threads")]
fn if_enable_threads(&mut self) -> &mut Self {
self.define("UNQLITE_ENABLE_THREADS", None).flag("-lpthread")
}
#[cfg(feature = "jx9-disable-builtin-func")]
fn if_jx9_diable_builtin_func(&mut self) -> &mut Self {
self.define("JX9_DISABLE_BUILTIN_FUNC", None)
}
#[cfg(feature = "jx9-enable-math-func")]
fn if_jx9_enable_math_func(&mut self) -> &mut Self {
self.define("JX9_ENABLE_MATH_FUNC", None)
}
#[cfg(feature = "jx9-disable-disk-io")]
fn if_jx9_disable_disk_io(&mut self) -> &mut Self {
self.define("JX9_DISABLE_DISK_IO", None)
}
#[cfg(feature = "enable-jx9-hash-io")]
fn if_enable_jx9_hash_io(&mut self) -> &mut Self {
self.define("UNQLITE_ENABLE_JX9_HASH_IO", None)
}
}
<file_sep>/Cargo.toml
[package]
name = "unqlite-sys"
version = "1.1.0"
authors = ["<NAME> <<EMAIL>>"]
build = "build.rs"
license = "MIT/Apache-2.0"
readme = "README.md"
homepage = "https://github.com/zitsen/unqlite-sys.rs"
repository = "https://github.com/zitsen/unqlite-sys.rs.git"
documentation = "http://zitsen.github.io/unqlite-sys.rs"
description = "Rust `unqlite` bindings."
keywords = ["unqlite", "kv", "nosql", "binding"]
[dependencies]
[build-dependencies]
gcc = "^0.3"
[features]
# no features by default
default = []
# UNQLITE_ENABLE_THREADS
enable-threads = []
# Options To Omit/Enable Features
jx9-disable-builtin-func = []
jx9-enable-math-func = []
jx9-disable-disk-io = []
enable-jx9-hash-io = []
<file_sep>/src/constants.rs
use std::os::raw::{c_int, c_uint};
// Standard return values from Symisc public interfaces
const SXRET_OK: c_int = 0; /* Not an error */
const SXERR_MEM: c_int = -1; /* Out of memory */
const SXERR_IO: c_int = -2; /* IO error */
const SXERR_EMPTY: c_int = -3; /* Empty field */
const SXERR_LOCKED: c_int = -4; /* Locked operation */
const SXERR_ORANGE: c_int = -5; /* Out of range value */
const SXERR_NOTFOUND: c_int = -6; /* Item not found */
const SXERR_LIMIT: c_int = -7; /* Limit reached */
const SXERR_MORE: c_int = -8; /* Need more input */
const SXERR_INVALID: c_int = -9; /* Invalid parameter */
const SXERR_ABORT: c_int = -10; /* User callback request an operation abort */
const SXERR_EXISTS: c_int = -11; /* Item exists */
const SXERR_SYNTAX: c_int = -12; /* Syntax error */
const SXERR_UNKNOWN: c_int = -13; /* Unknown error */
const SXERR_BUSY: c_int = -14; /* Busy operation */
const SXERR_OVERFLOW: c_int = -15; /* Stack or buffer overflow */
const SXERR_WILLBLOCK: c_int = -16; /* Operation will block */
const SXERR_NOTIMPLEMENTED: c_int = -17; /* Operation not implemented */
const SXERR_EOF: c_int = -18; /* End of input */
const SXERR_PERM: c_int = -19; /* Permission error */
const SXERR_NOOP: c_int = -20; /* No-op */
const SXERR_FORMAT: c_int = -21; /* Invalid format */
const SXERR_NEXT: c_int = -22; /* Not an error */
const SXERR_OS: c_int = -23; /* System call return an error */
const SXERR_CORRUPT: c_int = -24; /* Corrupted pointer */
const SXERR_CONTINUE: c_int = -25; /* Not an error: Operation in progress */
const SXERR_NOMATCH: c_int = -26; /* No match */
const SXERR_RESET: c_int = -27; /* Operation reset */
const SXERR_DONE: c_int = -28; /* Not an error */
const SXERR_SHORT: c_int = -29; /* Buffer too short */
const SXERR_PATH: c_int = -30; /* Path error */
const SXERR_TIMEOUT: c_int = -31; /* Timeout */
const SXERR_BIG: c_int = -32; /* Too big for processing */
const SXERR_RETRY: c_int = -33; /* Retry your call */
const SXERR_IGNORE: c_int = -63; /* Ignore */
// Standard UnQLite return values
/// Successful result
pub const UNQLITE_OK: c_int = SXRET_OK;
// Beginning of error codes
/// Out of memory
pub const UNQLITE_NOMEM: c_int = SXERR_MEM;
/// Another thread have released this instance
pub const UNQLITE_ABORT: c_int = SXERR_ABORT;
/// IO error
pub const UNQLITE_IOERR: c_int = SXERR_IO;
/// Corrupt pointer
pub const UNQLITE_CORRUPT: c_int = SXERR_CORRUPT;
/// Forbidden Operation
pub const UNQLITE_LOCKED: c_int = SXERR_LOCKED;
/// The database file is locked
pub const UNQLITE_BUSY: c_int = SXERR_BUSY;
/// Operation done
pub const UNQLITE_DONE: c_int = SXERR_DONE;
/// Permission error
pub const UNQLITE_PERM: c_int = SXERR_PERM;
/// Method not implemented by the underlying Key/Value storage engine
pub const UNQLITE_NOTIMPLEMENTED: c_int = SXERR_NOTIMPLEMENTED;
/// No such record
pub const UNQLITE_NOTFOUND: c_int = SXERR_NOTFOUND;
/// No such method
pub const UNQLITE_NOOP: c_int = SXERR_NOOP;
/// Invalid parameter
pub const UNQLITE_INVALID: c_int = SXERR_INVALID;
/// End Of Input
pub const UNQLITE_EOF: c_int = SXERR_EOF;
/// Unknown configuration option
pub const UNQLITE_UNKNOWN: c_int = SXERR_UNKNOWN;
/// Database limit reached
pub const UNQLITE_LIMIT: c_int = SXERR_LIMIT;
/// Record exists
pub const UNQLITE_EXISTS: c_int = SXERR_EXISTS;
/// Empty record
pub const UNQLITE_EMPTY: c_int = SXERR_EMPTY;
/// Compilation error
pub const UNQLITE_COMPILE_ERR: c_int = -70;
/// Virtual machine error
pub const UNQLITE_VM_ERR: c_int = -71;
/// Full database unlikely
pub const UNQLITE_FULL: c_int = -73;
/// Unable to open the database file
pub const UNQLITE_CANTOPEN: c_int = -74;
/// Read only Key/Value storage engine
pub const UNQLITE_READ_ONLY: c_int = -75;
/// Locking protocol error
pub const UNQLITE_LOCKERR: c_int = -76;
// end-of-error-codes
pub const UNQLITE_CONFIG_JX9_ERR_LOG: c_int = 1;
pub const UNQLITE_CONFIG_MAX_PAGE_CACHE: c_int = 2;
pub const UNQLITE_CONFIG_ERR_LOG: c_int = 3;
pub const UNQLITE_CONFIG_KV_ENGINE: c_int = 4;
pub const UNQLITE_CONFIG_DISABLE_AUTO_COMMIT: c_int = 5;
pub const UNQLITE_CONFIG_GET_KV_NAME: c_int = 6;
// UnQLite/Jx9 Virtual Machine Configuration Commands.
//
// The following set of constants are the available configuration verbs that can
// be used by the host-application to configure the Jx9 (Via UnQLite) Virtual machine.
// These constants must be passed as the second argument to the [unqlite_vm_config()]
// interface.
// Each options require a variable number of arguments.
// The [unqlite_vm_config()] interface will return UNQLITE_OK on success, any other return
// value indicates failure.
// There are many options but the most importants are: UNQLITE_VM_CONFIG_OUTPUT which install
// a VM output consumer callback, UNQLITE_VM_CONFIG_HTTP_REQUEST which parse and register
// a HTTP request and UNQLITE_VM_CONFIG_ARGV_ENTRY which populate the $argv array.
// For a full discussion on the configuration verbs and their expected parameters, please
// refer to this page:
// http://unqlite.org/c_api/unqlite_vm_config.html
//
/// TWO ARGUMENTS: int (*xConsumer)(const void *, unsigned int, void *), void *
pub const UNQLITE_VM_CONFIG_OUTPUT: c_int = 1;
/// ONE ARGUMENT: const char *zIncludePath
pub const UNQLITE_VM_CONFIG_IMPORT_PATH: c_int = 2;
/// NO ARGUMENTS: Report all run-time errors in the VM output
pub const UNQLITE_VM_CONFIG_ERR_REPORT: c_int = 3;
/// ONE ARGUMENT: int nMaxDepth
pub const UNQLITE_VM_CONFIG_RECURSION_DEPTH: c_int = 4;
/// ONE ARGUMENT: unsigned int *pLength
pub const UNQLITE_VM_OUTPUT_LENGTH: c_int = 5;
/// TWO ARGUMENTS: const char *zName, unqlite_value *pValue
pub const UNQLITE_VM_CONFIG_CREATE_VAR: c_int = 6;
/// TWO ARGUMENTS: const char *zRawRequest, int nRequestLength
pub const UNQLITE_VM_CONFIG_HTTP_REQUEST: c_int = 7;
/// THREE ARGUMENTS: const char *zKey, const char *zValue, int nLen
pub const UNQLITE_VM_CONFIG_SERVER_ATTR: c_int = 8;
/// THREE ARGUMENTS: const char *zKey, const char *zValue, int nLen
pub const UNQLITE_VM_CONFIG_ENV_ATTR: c_int = 9;
/// ONE ARGUMENT: unqlite_value **ppValue
pub const UNQLITE_VM_CONFIG_EXEC_VALUE: c_int = 10;
/// ONE ARGUMENT: const unqlite_io_stream *pStream
pub const UNQLITE_VM_CONFIG_IO_STREAM: c_int = 11;
/// ONE ARGUMENT: const char *zValue
pub const UNQLITE_VM_CONFIG_ARGV_ENTRY: c_int = 12;
/// TWO ARGUMENTS: const void **ppOut, unsigned int *pOutputLen
pub const UNQLITE_VM_CONFIG_EXTRACT_OUTPUT: c_int = 13;
// Storage engine configuration commands.
//
// The following set of constants are the available configuration verbs that can
// be used by the host-application to configure the underlying storage engine
// (i.e Hash, B+tree, R+tree).
//
// These constants must be passed as the first argument to [unqlite_kv_config()].
// Each options require a variable number of arguments.
// The [unqlite_kv_config()] interface will return UNQLITE_OK on success, any other return
// value indicates failure.
// For a full discussion on the configuration verbs and their expected parameters, please
// refer to this page:
// http://unqlite.org/c_api/unqlite_kv_config.html
//
/// ONE ARGUMENT: unsigned int (*xHash)(const void *,unsigned int)
pub const UNQLITE_KV_CONFIG_HASH_FUNC: c_int = 1;
/// ONE ARGUMENT: int (*xCmp)(const void *,const void *,unsigned int)
pub const UNQLITE_KV_CONFIG_CMP_FUNC: c_int = 2;
// Global Library Configuration Commands.
//
// The following set of constants are the available configuration verbs that can
// be used by the host-application to configure the whole library.
// These constants must be passed as the first argument to [unqlite_lib_config()].
//
// Each options require a variable number of arguments.
// The [unqlite_lib_config()] interface will return UNQLITE_OK on success, any other return
// value indicates failure.
// Notes:
// The default configuration is recommended for most applications and so the call to
// [unqlite_lib_config()] is usually not necessary. It is provided to support rare
// applications with unusual needs.
// The [unqlite_lib_config()] interface is not threadsafe. The application must insure that
// no other [unqlite_*()] interfaces are invoked by other threads while [unqlite_lib_config()]
// is running. Furthermore, [unqlite_lib_config()] may only be invoked prior to library
// initialization using [unqlite_lib_init()] or [unqlite_init()] or after shutdown
// by [unqlite_lib_shutdown()]. If [unqlite_lib_config()] is called after [unqlite_lib_init()]
// or [unqlite_init()] and before [unqlite_lib_shutdown()] then it will return UNQLITE_LOCKED.
// For a full discussion on the configuration verbs and their expected parameters, please
// refer to this page:
// http://unqlite.org/c_api/unqlite_lib.html
//
/// ONE ARGUMENT: const SyMemMethods *pMemMethods
pub const UNQLITE_LIB_CONFIG_USER_MALLOC: c_int = 1;
/// TWO ARGUMENTS: int (*xMemError)(void *), void *pUserData
pub const UNQLITE_LIB_CONFIG_MEM_ERR_CALLBACK: c_int = 2;
/// ONE ARGUMENT: const SyMutexMethods *pMutexMethods
pub const UNQLITE_LIB_CONFIG_USER_MUTEX: c_int = 3;
/// NO ARGUMENTS
pub const UNQLITE_LIB_CONFIG_THREAD_LEVEL_SINGLE: c_int = 4;
/// NO ARGUMENTS
pub const UNQLITE_LIB_CONFIG_THREAD_LEVEL_MULTI: c_int = 5;
/// ONE ARGUMENT: const unqlite_vfs *pVfs
pub const UNQLITE_LIB_CONFIG_VFS: c_int = 6;
/// ONE ARGUMENT: unqlite_kv_methods *pStorage
pub const UNQLITE_LIB_CONFIG_STORAGE_ENGINE: c_int = 7;
/// ONE ARGUMENT: int iPageSize
pub const UNQLITE_LIB_CONFIG_PAGE_SIZE: c_int = 8;
// These bit values are intended for use in the 3rd parameter to the [unqlite_open()] interface
// and in the 4th parameter to the xOpen method of the [unqlite_vfs] object.
//
/// Read only mode. Ok for [unqlite_open]
pub const UNQLITE_OPEN_READONLY: c_uint = 0x00000001;
/// Ok for [unqlite_open]
pub const UNQLITE_OPEN_READWRITE: c_uint = 0x00000002;
/// Ok for [unqlite_open]
pub const UNQLITE_OPEN_CREATE: c_uint = 0x00000004;
/// VFS only
pub const UNQLITE_OPEN_EXCLUSIVE: c_uint = 0x00000008;
/// VFS only
pub const UNQLITE_OPEN_TEMP_DB: c_uint = 0x00000010;
/// Ok for [unqlite_open]
pub const UNQLITE_OPEN_NOMUTEX: c_uint = 0x00000020;
/// Omit journaling for this database. Ok for [unqlite_open]
pub const UNQLITE_OPEN_OMIT_JOURNALING: c_uint = 0x00000040;
/// An in memory database. Ok for [unqlite_open]
pub const UNQLITE_OPEN_IN_MEMORY: c_uint = 0x00000080;
/// Obtain a memory view of the whole file. Ok for [unqlite_open]
pub const UNQLITE_OPEN_MMAP: c_uint = 0x00000100;
// Synchronization Type Flags
//
// When UnQLite invokes the xSync() method of an [unqlite_io_methods] object it uses
// a combination of these integer values as the second argument.
//
// When the UNQLITE_SYNC_DATAONLY flag is used, it means that the sync operation only
// needs to flush data to mass storage.: c_int = Inode information need not be flushed.
// If the lower four bits of the flag equal UNQLITE_SYNC_NORMAL, that means to use normal
// fsync() semantics. If the lower four bits equal UNQLITE_SYNC_FULL, that means to use
// Mac OS X style fullsync instead of fsync().
//
pub const UNQLITE_SYNC_NORMAL: c_int = 0x00002;
pub const UNQLITE_SYNC_FULL: c_int = 0x00003;
pub const UNQLITE_SYNC_DATAONLY: c_int = 0x00010;
// File Locking Levels
//
// UnQLite uses one of these integer values as the second
// argument to calls it makes to the xLock() and xUnlock() methods
// of an [unqlite_io_methods] object.
//
pub const UNQLITE_LOCK_NONE: c_int = 0;
pub const UNQLITE_LOCK_SHARED: c_int = 1;
pub const UNQLITE_LOCK_RESERVED: c_int = 2;
pub const UNQLITE_LOCK_PENDING: c_int = 3;
pub const UNQLITE_LOCK_EXCLUSIVE: c_int = 4;
// Flags for the xAccess VFS method
//
// These integer constants can be used as the third parameter to
// the xAccess method of an [unqlite_vfs] object. They determine
// what kind of permissions the xAccess method is looking for.
// With UNQLITE_ACCESS_EXISTS, the xAccess method
// simply checks whether the file exists.
// With UNQLITE_ACCESS_READWRITE, the xAccess method
// checks whether the named directory is both readable and writable
// (in other words, if files can be added, removed, and renamed within
// the directory).
// The UNQLITE_ACCESS_READWRITE constant is currently used only by the
// [temp_store_directory pragma], though this could change in a future
// release of UnQLite.
// With UNQLITE_ACCESS_READ, the xAccess method
// checks whether the file is readable. The UNQLITE_ACCESS_READ constant is
// currently unused, though it might be used in a future release of
// UnQLite.
//
pub const UNQLITE_ACCESS_EXISTS: c_int = 0;
pub const UNQLITE_ACCESS_READWRITE: c_int = 1;
pub const UNQLITE_ACCESS_READ: c_int = 2;
// Possible seek positions.
//
pub const UNQLITE_CURSOR_MATCH_EXACT: c_int = 1;
pub const UNQLITE_CURSOR_MATCH_LE: c_int = 2;
pub const UNQLITE_CURSOR_MATCH_GE: c_int = 3;
// UnQLite journal file suffix.
//
// #ifndef UNQLITE_JOURNAL_FILE_SUFFIX
pub const UNQLITE_JOURNAL_FILE_SUFFIX: &'static str = "_unqlite_journal";
// #endif
//
// Call Context - Error Message Serverity Level.
//
// The following constans are the allowed severity level that can
// passed as the second argument to the [unqlite_context_throw_error()] or
// [unqlite_context_throw_error_format()] interfaces.
// Refer to the official documentation for additional information.
//
/// Call context error such as unexpected number of arguments, invalid types and so on.
pub const UNQLITE_CTX_ERR: c_int = 1;
/// Call context Warning
pub const UNQLITE_CTX_WARNING: c_int = 2;
/// Call context Notice
pub const UNQLITE_CTX_NOTICE: c_int = 3;
<file_sep>/Changelog.md
<a name="v1.1.0"></a>
## v1.1.0 (2017-06-12)
#### Features
* **native:** update native unqlite source to 1.1.7 ([978df9cd](978df9cd))
<a name="v1.0.0"></a>
## v1.0.0 (2016-05-13)
#### Features
* **FFI:** `extern "C"` callbacks is converted to `unsafe` ([2e4a86ce](2e4a86ce))
* **remove-libc:**
* use std::os::raw:: type instead ([d628e906](d628e906))
* update bindgen FFI ([f82db71c](f82db71c))
#### Breaking Changes
* **remove-libc:** use std::os::raw:: type instead ([d628e906](d628e906))
<file_sep>/README.md
# unqlite-sys
Rust bindings for [UnQlite][] library.
[![travis-badge][]][travis] [![release-badge][]][cargo] [![downloads]][cargo]
[![docs-badge][]][docs] [![license-badge][]][cargo]
As its official site says, **UnQlite** is
> An Embeddable NoSQL Database Engine.
Please see [UnQLite C/C++ API Reference][] for full API documents.
## Usage
This crate provides several features for [UnQlite compile-time
options][apidoc-compile]:
* **enable-threads**: equivalent to `UNQLITE_ENABLE_THREADS` enabled.
* **jx9-disable-builtin-func**: equivalent to `JX9_DISABLE_BUILTIN_FUNC` enabled.
* **jx9-enable-math-fuc**: equivalent to `JX9_ENABLE_MATH_FUNC` enabled.
* **jx9-disable-disk-io**: equivalent to `JX9_DISABLE_DISK_IO` enabled.
* **enable-jx9-hash-io**: equivalent to `UNQLITE_ENABLE_JX9_HASH_IO` enabled.
To provide the same default behavior as original C does, non of the features
is enabled by default. When you want some features, such as **enable-threads**,
just config in `Cargo.toml`:
```toml
[dependencies.unqlite-sys]
version = "0.3.0"
features = [ "enable-threads" ]
```
For multiple features just add them in toml `features` array.
## Threadsafe
Note that even "enable-threads" is featured in your crate, it's not meant
that your code is threadsafe.
> When UnQLite has been compiled with threading support then the threading mode can be altered
at run-time using the unqlite_lib_config() interface together with one of these verbs:
>> UNQLITE_LIB_CONFIG_THREAD_LEVEL_SINGLE
>> UNQLITE_LIB_CONFIG_THREAD_LEVEL_MULTI
> Platforms others than Windows and UNIX systems must install their own mutex subsystem via
unqlite_lib_config() with a configuration verb set to UNQLITE_LIB_CONFIG_USER_MUTEX. Otherwise
the library is not threadsafe.
>
> Note that you must link UnQLite with the POSIX threads library under UNIX systems (i.e:
-lpthread).
To use in multithread cases, that is **threadsafe**, you may use like this:
```rust
extern crate unqlite_sys as ffi;
use ffi::constants as ffic;
fn main() {
unsafe {
ffi::unqlite_lib_config(ffic::UNQLITE_LIB_CONFIG_THREAD_LEVEL_MULTI);
ffi::unqlite_lib_init();
assert_eq!(ffi::unqlite_lib_is_threadsafe(), 1);
// do stuff ...
}
}
```
[UnQlite]: http://unqlite.org
[UnQLite C/C++ API Reference]: http://unqlite.org/c_api.html
[travis-badge]: https://img.shields.io/travis/zitsen/unqlite-sys.rs.svg?style=flat-square
[travis]: https://travis-ci.org/zitsen/unqlite-sys.rs
[release-badge]: https://img.shields.io/crates/v/unqlite-sys.svg?style=flat-square
[downloads]: https://img.shields.io/crates/d/unqlite-sys.svg?style=flat-square
[cargo]: https://crates.io/crates/unqlite-sys
[docs-badge]: https://img.shields.io/badge/API-docs-blue.svg?style=flat-square
[docs]: https://zitsen.github.io/unqlite-sys.rs
[license-badge]: https://img.shields.io/crates/l/unqlite-sys.svg?style=flat-square
[apidoc-compile]: http://unqlite.org/c_api_const.html#compile_time
| f4bc0c2b87fa9fb976f3ef3c66a591f56eb9ba7f | [
"Markdown",
"Rust",
"TOML"
] | 7 | Markdown | zitsen/unqlite-sys.rs | 3f8b954bc5a04706f37a5bdb9b44de020ca93534 | f981421cd79c0d9243dd25c9c59243a54c97ca72 |
refs/heads/master | <file_sep># Src
another readme file
<file_sep># Data
data from scripts
<file_sep>def my_cube(x):
"""
takes a cube from inserted number
uses ** operator
"""
return(x ** 3)
#def my_square2(x):
# """uses * to calculate square
# """
# return(x * x)
print(my_cube(3))
<file_sep># Output
readme file in output folder
<file_sep>#bin folder
added bin folder
<file_sep># Docs
readme file
Documentation
<file_sep>This repository contains my files
This is the changes to an existing file
Third change in file
Git is a version control system that prevents us from having the "final doc" problem.
| 212fde03ce4bb1f9c5b85f827f9ce28fb0493cc0 | [
"Markdown",
"Python"
] | 7 | Markdown | sibich/git_lesson | bc40c3a89e0dd0a1a3bd54ff7b07baf59c9e5b8b | 5bc3414772d4e19ec12968f9bb896daf125e4ae7 |
refs/heads/main | <file_sep>[package.metadata.wasm-pack.profile.release]
wasm-opt = false
[package]
edition = "2021"
name = "wasm-lib"
version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.78"
<file_sep>extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
#[no_mangle]
pub fn fib(n: i32) -> i32 {
match n {
0 => 0,
1 => 1,
_ => fib(n - 1) + fib(n - 2),
}
}
#[test]
fn add_test() {
assert_eq!(fib(30), 832040);
}
| 3e0f65e62cf4484f9314baef834fc0d4b0eea2a9 | [
"TOML",
"Rust"
] | 2 | TOML | since92x/my-react-app | b15c22e8ad64f6c0d3e5876a487985eef532025b | 4fab00dac3370bb5659526f2e9c7049e60690b5b |
refs/heads/master | <repo_name>liorze/rest-bench<file_sep>/README.md
# rest-bench
<file_sep>/routes/users.js
var express = require('express');
var router = express.Router();
var fs = require('fs');
console.log('READING FILE: ' + process.argv[2]);
var obj = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
var randomInt = require('random-int');
var mapping = new Map();
for (let i = 0; i < 10000; ++i) mapping.set(i, obj);
/* GET users listing. */
router.get('/', (req, res) => {
res.status(200);
res.json(mapping.get(randomInt(10000)));
});
module.exports = router;
| c35ef7b1f1b27c4a744d9d7b85ab2850018e11c0 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | liorze/rest-bench | 44f042b1eafa4a25edaafb136d3ce4360a2f8b18 | 5f21ad71dc3298ca76cc19a5e2736834817186c8 |
refs/heads/main | <repo_name>themebon/youtube-comments-api-flask<file_sep>/requirements.txt
certifi==2021.10.8
charset-normalizer==2.0.7
click==8.0.3
colorama==0.4.4
Flask==2.0.2
Flask-Cors==3.0.10
gunicorn==20.1.0
idna==3.3
itsdangerous==2.0.1
Jinja2==3.0.2
MarkupSafe==2.0.1
requests==2.26.0
six==1.16.0
urllib3==1.26.7
Werkzeug==2.0.2<file_sep>/main.py
from flask import Flask, jsonify
from ytb_comment_scraper import *
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/<string:videoId>")
def get_comments_json(videoId):
try:
youtube_url = f'https://www.youtube.com/watch?v={videoId}'
limit = COMMENT_LIMIT
count = 0
comments_array = []
for comment in download_comments(youtube_url):
# print(comment)
comments_array.append(comment)
count += 1
if limit and count >= limit:
break
if comments_array:
return jsonify(comments_array)
else:
return {'error': 'No video id found'}
except Exception as e:
print('Error:', str(e))
sys.exit(1)
| 5a7defee0406600dd18eaaddf807e920fe49ab60 | [
"Python",
"Text"
] | 2 | Text | themebon/youtube-comments-api-flask | 96216e7c5f35c3176f5aee3e1659569e810015a5 | f07f9fb424c98f85501c147793a47af57cacf31d |
refs/heads/master | <file_sep># Vue Project Example
一个简单的 Vue 前端项目脚手架例子
- 使用 Element UI 做 UI 组件
- 自动化引入 Icon svg 图标
- 模块化添加 Vuex 全局状态
- 根据路由动态切换页面 title
- 封装 Promise 来模拟请求 mock 数据
- 添加 normalize.css (使不同浏览器默认样式保持一致)
- 使用 [ESLint confige Vue](https://github.com/vuejs/eslint-config-vue) 格式化代码
- 在 vue.config.js 中添加 pages 分页配置
## 命令
初始化
```sh
yarn install
```
运行
```sh
yarn start
```
打包
```sh
yarn build
```
修复代码格式错误
```sh
yarn lint
```
## 添加 svg
假如我在 `src/icons/svg` 目录下添加了一个 `bag-check.svg` ,在项目中以以下方式引入即可
```vue
<icon-svg name="bag-check" />
```
`jsconfig.json` 配置参考:[https://vuejs.github.io/vetur/guide/setup.html#project-setup](https://vuejs.github.io/vetur/guide/setup.html#project-setup)
手动引入svg
```vue
<svg aria-hidden="true" :viewBox="iconAt.viewBox" class="icon-at">
<use :xlink:href="'#'+iconAt.id" />
</svg>
```
```js
import '@/icons/svg/at.svg' // 引入 icon
import iconAt from '@/icons/svg/at.svg'
export default {
name: 'App',
data() {
return {
iconAt
}
}
}
```
<file_sep>set -e
yarn build
cd dist
git init
git add -A
echo -e "\n# commit build"
git commit -m 'deploy'
echo -e "\n# push Github"
git push -f <EMAIL>:uphg/vue-project-example.git master:gh-pages
echo -e "\n# push Gitee"
git push -f <EMAIL>:uphg/vue-project-example.git master:gh-pages
echo -e "\n# Exit the build folder"
cd -
<file_sep>export function initDirective(Vue) {
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时执行
inserted(el) {
if (el.nodeName === 'INPUT') {
el.focus()
} else {
el.querySelector('input').focus()
}
}
})
}
<file_sep>// 请求添加延时,模拟网络延时
export function delay(fn) {
return new Promise(function(resolve, reject) {
setTimeout(() => {
fn(resolve, reject)
}, 500)
})
}
<file_sep>const path = require('path')
const resolve = (dir) => path.join(__dirname, dir)
const pages = require('./pages.config.js')
module.exports = {
publicPath: '/vue-project-example', // url 前缀
pages,
// lintOnSave: false,
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
resolve: {
alias: {
'@': resolve('src'),
'~mock': resolve('mock')
}
}
},
chainWebpack(config) {
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
}
<file_sep>const getters = {
name: state => state.user.name,
phone: state => state.user.phone
}
export default getters
<file_sep>import { delay } from './request.js'
/* 图片验证码 */
export function imgCaptcha() {
return delay((resolve) => {
resolve({
code: 200,
data: {
captcha: '<KEY>
captchaToken: '<PASSWORD>'
},
message: '请求成功'
})
})
}
<file_sep>const pages = {
index: {
entry: 'src/pages/index/main.js',
template: 'public/index.html',
filename: 'index.html',
title: '首页',
chunks: ['chunk-vendors', 'chunk-common', 'index']
},
foo: {
entry: 'src/pages/foo/main.js',
template: 'public/foo/index.html',
filename: 'foo/index.html',
title: 'Foo',
chunks: ['chunk-vendors', 'chunk-common', 'foo']
},
bar: {
entry: 'src/pages/bar/main.js',
template: 'public/bar/index.html',
filename: 'bar/index.html',
title: 'Bar',
chunks: ['chunk-vendors', 'chunk-common', 'bar']
},
'user': {
entry: 'src/pages/user/main.js',
template: 'public/user/index.html',
filename: 'user/index.html',
title: '个人中心',
chunks: ['chunk-vendors', 'chunk-common', 'user']
},
about: 'src/pages/about/main.js'
}
module.exports = pages
| 21657d2ae94cd78d5d93f6727f1c5fa4810a12b3 | [
"Markdown",
"JavaScript",
"Shell"
] | 8 | Markdown | uphg/vue-project-example | d3c81380727ef6c05592c7b9cfafb30ff5a6c841 | 037fdb6a05e57da6df4956896348c17180c3b3e6 |
refs/heads/main | <repo_name>wadewadewadewadewadewade/react-native-recipes<file_sep>/context/storage/StorageTypes.ts
export const storageTypes = ['UNKNOWN', 'GOOGLEDRIVE']
export enum StorageTypeIndexes {
UNKNOWN = 0,
GOOGLEDRIVE = 1
}
export type StorageTypes = typeof storageTypes[number]
export const isStorageType = (storageType: string) => storageTypes.includes(storageType)
export enum InitializingPhases {
NOT_INITIALIZED,
INITIALIZING,
INITIALIZIED
}
export interface StoreType {
type: StorageTypes
listFiles: (searchTerm?: string) => Promise<Array<any>>
getFile: (fileId: string) => Promise<any>
saveFile: (name: string, body: string) => Promise<any>
deleteFile: (fileId: string) => Promise<void>
}
export type ErrorType = string
export interface StorageContextType {
list?: (searchTerm?: string) => Promise<Array<any>>
get?: (fileId: string) => Promise<any>
put?: (name: string, body: string) => Promise<any>
delete?: (fileId: string) => Promise<void>
initialized: InitializingPhases
error?: ErrorType
}
<file_sep>/context/storage/GoogleDrive.ts
import GDrive from 'react-native-google-drive-api-wrapper';
/*const DISCOVERY_DOCS = [
"https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"
];
const SCOPES = "https://www.googleapis.com/auth/drive.metadata.readonly"
const API_KEY = process.env.REACT_APP_GAPI_API_KEY
const CLIENT_ID = process.env.REACT_APP_GAPI_CLIENT_ID*/
let initializied = GDrive.isInitialized();
const initialize = (accessToken: string) => {
GDrive.setAccessToken(accessToken);
GDrive.init();
initializied = GDrive.isInitialized();
};
/**
* List files.
*/
const listFiles = async (searchTerm?: string): Promise<Array<any>> => {
const response = await GDrive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name, mimeType, modifiedTime)',
q: searchTerm,
});
const res = JSON.parse(response.body);
return res.files;
};
/**
* Save file.
*/
const saveFile = async (name: string, body: string): Promise<any> => {
const response = await GDrive.files.createFileMultipart(
body,
'text/plain',
{
parents: ['root'],
name,
},
false,
);
const res = JSON.parse(response.body);
return res.file;
};
/**
* Get file.
*/
const getFile = async (fileId: string): Promise<any> => {
const response = await GDrive.files.get(fileId, {alt: 'media'});
const res = JSON.parse(response.body);
return res.file;
};
/**
* Delete file.
*/
const deleteFile = async (fileId: string): Promise<void> => {
await GDrive.files.delete(fileId);
return;
};
export {initializied, initialize, listFiles, saveFile, getFile, deleteFile};
<file_sep>/README.md
# react-nativ-recipes
A simple Recipes app I'm working on so that I can digitize my hand-written recipes as well as consildate those with ones I use online.
## Handwriting Recognition
For handwriting recognition, I tried react-native-tesseract-ocr, but it did not work well at all for handwriting (and was tough to get working for non-handwriting as well). So I went with a Firebase ML approach outlined here: https://www.section.io/engineering-education/react-native-firebase-text-recognition/
## Authenticaiton
I'm working on password-less authentication also Firebase Auth (https://rnfirebase.io/auth/usage), but having trouble setting Dynamic Links up. I need Dynamic Links because password-less authentication uses a link sent to an email, and the way to verify that link requires either a web page (which I don't want to pay for at this point), or linking back to the app directly (which requires Dynamic Linking)
### Authentication Notes
* https://dev.to/techtalks/deep-linking-in-react-native-app-with-react-navigation-v5-41id
* https://reactnavigation.org/docs/getting-started/
* https://firebase.google.com/docs/auth/web/email-link-auth
* https://firebase.google.com/docs/auth/android/email-link-auth
* https://firebase.google.com/docs/dynamic-links/custom-domains
* https://developer.android.com/training/app-links/deep-linking
* https://stackoverflow.com/questions/66847608/firebase-dynamic-links-cant-use-google-provided-hostname | 9e5cf61854fbc993dc55e181405b6aa2800abba5 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | wadewadewadewadewadewade/react-native-recipes | 52a1260f5dd20a5f86ea37437d2bf17bef4613e5 | b0ce9ccf2bd9d15708b6b9b47e7b208f22abf4a0 |
refs/heads/master | <repo_name>BValeo/serverchat<file_sep>/index.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
users = {};
//connections = [];
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
app.use(express.static(__dirname + '/public'));
io.on('connection', function (socket) {
socket.on('register user', function (username) {
console.log('register user');
if(users[username] === undefined)
users[username] = socket.id;
});
socket.on('print list users', function(){
console.log('====START LIST USERS====');
for(var key in users){
console.log('Ключ: ' + key + '== socket.id - ' + users[key]);
}
console.log('====END LIST USERS====');
});
socket.on('delete user', function(user){
console.log('deleting user is ===' + users[user]);
delete users[user];
});
socket.on('disconnect', function(){
for(var key in users){
if(users[key] == socket.id) {
delete users.key;
}
}
console.log('client disconnect');
});
socket.on('new message', function(to, from, data, time, isMine, type){
console.log('==========new MESSAGE===============');
io.to(users[to]).emit('new message', {
'username' : from,
'message' : data,
'time' : time,
'isMine' : isMine,
'type' : type,
});
console.log('============sended=============')
});
}); | bf0655f69ccc3a5b48497aee3053c1b727cb1b09 | [
"JavaScript"
] | 1 | JavaScript | BValeo/serverchat | 8ab3b928d9e61a6422f8775c9544b2738b0cb0b1 | fb74df7548c2eb4bdc259763b1abe3ba2836c069 |
refs/heads/master | <file_sep># Freeswitch setup
Since I don't run Windows servers, I won't be providing a windows-friendly setup here. Sorry.
### Ubuntu Setup:
##### Install the prerequisites.
``` bash
sudo apt update
sudo apt install build-essential autoconf cmake yasm \
python2 python2-dev libtool-bin git libjpeg-dev libsqlite3-dev \
libcurl4-openssl-dev libspeex-dev libspeexdsp-dev libedit-dev \
libtiff-dev libsndfile1-dev -y
```
##### Now grab and build freeswitch:
``` bash
git clone https://freeswitch.org/stash/scm/fs/freeswitch.git
cd freeswitch
./bootstrap.sh
```
##### Edit modules.conf
change:
- ```#languages/mod_python``` to ```languages/mod_python ```
Also change:
- ```mod_enum``` to ```#mod_enum```
- ```mod_opus``` to ```#mod_opus```
- ```languages/mod_lua``` to ```#languages/mod_lua```
##### Now run...
``` bash
./configure
```
and watch for additional required libraries you may need to install if the build script has changed since this was written.
Once that's done, run:
``` bash
make && sudo make install
```
This will build freeswitch, and then attempt to install if it succeeds.
Files will be installed in ```/usr/local/freeswitch``` by default.
### Configuration
Edit : /usr/local/freeswitch/conf/dialplan/public/00_inbound.xml
Replace the contents with this:
``` xml
<include>
<extension name="public_did">
<condition field="destination_number" expression="^(.*)$">
<action application="set“ data="domain_name=$${domain}"/>
<action application="python" data=“proxy"/>
</condition>
</extension>
</include>
```
Edit : /usr/local/freeswitch/conf/sip_profiles/internal/alcazarnetworks.xml
Add this content:
``` xml
<include>
<gateway name="alcazar_east2">
<param name="username" value=“YOUR_USER_NAME" />
<param name="liberal-dtmf" value="true"/>
<param name="password" value=“<PASSWORD>CAZAR_GATEWAY_PASSWORD" />
<param name="from-user" value="YOUR_USER_NAME" />
<param name="proxy" value="172.16.31.10" />
<param name="register-proxy" value="172.16.31.10:5060" />
<param name="realmx" value="alcazarnetworks.com" />
<param name="caller-id-in-from" value="true"/>
<param name="register" value="false" />
<param name="rtp-ip" value="${local_ip_v4}"/>
<param name="sip-ip" value="${local_ip_v4}"/>
<param name="ext-rtp-ip" value="auto-nat"/>
<param name="ext-sip-ip" value="auto-nat"/>
</gateway>
</include>
```
If you want to do outbound calling, you'll need to do this:
Edit : /usr/local/freeswitch/conf/sip_profiles/external/alcazarnetworks.xml
``` xml
<include>
<gateway name="alcazar_out">
<param name="username" value=“YOUR_ALCAZAR_USERNAME" />
<param name="password" value=“<PASSWORD>" />
<param name="proxy" value="192.168.127.12" />
<param name="realm" value="192.168.127.12" />
<param name="caller-id-in-from" value="true"/>
<param name="domain" value="$${domain}"/>
<param name="interval" value="10"/>
<param name="ping" value="25"/>
<param name="dtmf-mode" value="rfc2833" />
<param name="from-user" value=" YOUR_ALCAZAR_USERNAME " />
<param name="caller-id-name" value="$${outbound_caller_name}"/>
<param name="caller-id-number" value="$${outbound_caller_id}"/>
<param name="caller-controls" value="plain"/>
<param name="comfort-noise" value="true"/>
</gateway>
</include>
```
##### Now allow alcazar through the Freeswitch firewall.
Edit : /usr/local/freeswitch/conf/autoload_configs/acl.conf
Change ```<network-lists></network-lists>``` to look like this:
``` xml
<network-lists>
<list name="domains" default="deny">
<node type="allow" domain="$${domain}"/>
<node type="allow" cidr="192.168.3.11/32" />
<node type="allow" cidr="172.16.31.10/32" />
</list>
</network-lists>
```
##### Now add the proxy starter and restart freeswitch
```
cd /usr/local/freeswitch/scripts
git clone https://github.com/hipcast/freeswitch-python.git easy
find . -type d -exec chmod 775 {} \;
find . -type f -name "*py" -exec chmod 554 {} \;
systemctl restart freeswitch
```
##### Your freeswitch server is ready to accept calls.
##### To configure Alcazar, you'll need to:
- Open an account:
- go to [AlcazarNetworks.com](https://www.alcazarnetworks.com/signup1.php)
- Open your firewall/iptables to the Alcazar IP addresses you placed in /usr/local/freeswitch/conf/autoload_configs/acl.conf
- UDP 5060/5061 Inbound for SIP
- UDP 5080/5081 Outbound for SIP
- UDP/TCP 16384-32768 Inbound/Outbound for Media Channels
- Ensure requests are passing both directions
##### Once your account with Alcazar is active, you can use the promo code when ordering numbers:
- Use Promo Code : VSFREE5-31-19 to get
- Flat rate inbound toll-free @ $0.0109/min (1/2 price of Twilio)
- $0.25/mo per Toll-Free number
- Free Toll-Free # porting
- Free New Toll-Free number setup
- Free Local number porting and setup
- Inbound call termination at $0.001/min no min/max
- **Disclaimer** : *Nobody* receives any commissions, fees, or credits for using this code. The benefit is entirely for the customer.

<file_sep># freeswitch-python
An basic example of using Python to control Freeswitch.
This example utilizes a script running as a child of freeswitch. You may also use ESL to control Freeswitch from an external application. We chose to use this method because it appears, based on our tests, to be more stable than the ESL model. Your experience may vary.
See [docs/Setup.md](./docs/SETUP.md) for setup/installation instructions.
Other example:
[https://github.com/xrmx/freeswitch/blob/master/src/mod/languages/mod_python/python_example.py](https://github.com/xrmx/freeswitch/blob/master/src/mod/languages/mod_python/python_example.py)
Freeswitch Python Docs:
[https://freeswitch.org/confluence/display/FREESWITCH/mod_python#mod_python-HelloWorldviacall](https://freeswitch.org/confluence/display/FREESWITCH/mod_python#mod_python-HelloWorldviacall)
<file_sep>from freeswitch import *
def handler(session, args):
# pickup the line
session.answer()
# wait a second for media channels to sync
session.sleep(1000)
# play a beep
session.streamFile("/usr/local/freeswitch/scripts/easy/audio/beep.wav")
# get some digits: max 2sec btwn keys, # is optional terminator
digits = session.getDigits( 4, '#', 2000, 5000)
# did we get the secret code?
if digits == '1234':
# We're in! Do some cool stuff.
session.streamFile("/usr/local/freeswitch/scripts/easy/audio/beep.wav")
session.streamFile("/usr/local/freeswitch/scripts/easy/audio/beep.wav")
# play goodbye
session.streamFile("/usr/local/freeswitch/scripts/easy/audio/beep.wav")
# hangup the SIP session
session.hangup()
# end the session in freeswitch
session.destroy()
| b45e32b365c723f6892ba344b79324666c047bab | [
"Markdown",
"Python"
] | 3 | Markdown | hipcast/freeswitch-python | d870c6bacf3a339f60980d282f1eb0cb5dc8bb63 | bda19c4b5788afda3c65777e169ccfad11ebfda6 |
refs/heads/master | <repo_name>Yosra1993/timer<file_sep>/src/timer.js
import React from 'react';
import './timer.css';
class Time extends React.Component{
constructor(props)
{
super(props)
this.Convert = this.Convert.bind(this);
}
Convert()
{ let ms=this.props.ms
let hours = Math.floor(((ms/1000)/60)/60);
let minutes = Math.floor(((ms/1000)/60)%60);
let seconds = Math.floor((ms/1000)%60);
return (hours.toString().padStart(2, "0")+':'+ minutes.toString().padStart(2, "0") +':'+ seconds.toString().padStart(2, "0"))
}
render()
{ return ( <div className="time">
<p className='time1'>{this.Convert(this.props.ms)}</p>
<div className='container'>
<p className="hour">Hour</p>
<p className="seconde">Seconde</p>
<p className="minute"> Minute </p>
</div>
</div>
)
}
}
export default Time ;<file_sep>/src/App.js
import React, { Component } from 'react';
import Time from './timer'
import Btn from './btn'
import './App.css';
class App extends Component {
constructor(props)
{
super(props)
this.state={
ms:0,
isOn: false,
}
this.startTimer = this.startTimer.bind(this)
this.stopTimer = this.stopTimer.bind(this)
this.resetTimer = this.resetTimer.bind(this)
}
timer =setInterval(
() => {
if(this.state.isOn)
this.setState({
ms: this.state.ms+1000
})
},
1000
)
startTimer() {
console.log("start")
this.setState({
isOn: true,
})
}
stopTimer() {
console.log('sdqsd')
this.setState({isOn: false})
}
resetTimer () {
this.setState ({ms: 0, isOn: false})
}
render() {
return (
<div className='App'>
<Time ms={this.state.ms} />
<Btn start={this.startTimer} isOn={this.state.isOn} stop={this.stopTimer} reset={this.resetTimer} />
</div>
);
}
}
export default App;
<file_sep>/src/btn.js
import React, { Component } from 'react';
import './btn.css';
import { Button } from 'react-bootstrap';
class Btn extends Component {
constructor(props)
{
super(props)
this.Onclick = this.Onclick.bind(this);
this.reset = this.reset.bind(this);
}
Onclick()
{
if(this.props.isOn==false)
return this.props.start
return this.props.stop
}
reset()
{
return this.props.reset
}
render() {
return (
<div className='btn'>
<Button bsStyle="info" onClick={this.Onclick()}>Start</Button>
<input className='btn btn-info'type='button' value='Reset' onClick={this.reset()} style={{marginLeft:'20px'}}/>
</div>
);
}
}
export default Btn;
| fccee839dc82668177e694381bba93428c4f1ef4 | [
"JavaScript"
] | 3 | JavaScript | Yosra1993/timer | f09b87a63e000041684aa8e1d6b1df2c1063d3ee | 66df9b1c839d911ed8eb51bccb9404539f08db6d |
refs/heads/main | <repo_name>CaptionAdam/ComputerScience10<file_sep>/Python/HowOld.py
#Failed Code Attempt
#print("What Year Is it")
#year=input()
#print("So it is", year, "Already")
#print("Now you want to know when you will turn 100 \nFirst give me your name")
#name=input()
#print("Hello,",name, "\nNow what year were you born")
#birth=input()
#print(year - birth)
#Subtract = int(year) - int(birth)
#print(Subtract)
#Working Code
print("What Year Is it")
year=input()
print("Thank you, now I am able to tell you when you will turn 100 \nSo what is your name again")
name=input()
print(f"Why hello there {name} Nice to meet you \nhow old are you if you dont mind me asking")
age=input()
print(f"So you are {age}\nNow I will tell you when you will turn 100 \nOne minute please")
birth = int(year) - int(age)
old = int(birth) + 100
print(f"You will be 100 in the year {old}")<file_sep>/Python/NameThing.py
print("Hello There. What is your Name (First & Last)")
name=input()
a,b = name.split()
print(f"Nice to meet you {b}, {a}")<file_sep>/README.md
# ComputerScience10
## My code from computer science 10
All of my code so far for computer science 10
<file_sep>/TurtlePython/Turtle.py
from turtle import*
turtle = Turtle()
screen = Screen()
#turtle.left(120)
#turtle.forward(180)
#turtle.left(120)
#turtle.forward(180)
#turtle.left(120)
#turtle.forward(180)
#turtle.left(270)
#turtle.backward(360)
#turtle.forward(180)
#turtle.left(90)
#turtle.forward(180)
#turtle.backward(360)
#turtle.forward(180)
#turtle.left(90)
#turtle.backward(360)
for i in range(8):
turtle.write(i)
turtle.forward(20)
input("Press any key to exit ...")<file_sep>/TurtlePython/Circle.py
from turtle import*
turtle = Turtle()
screen = Screen()
turtle.speed(1000)
screen.colormode(255)
#Screen Color
R = 0
G = 0
B = 0
#Turtle Color
R1 = 255
G1 = 255
B1 = 255
screen.bgcolor((R, G, B))
turtle.color((R1, G1, B1))
turtle.fillcolor((R1, G1, B1))
turtle.pensize(5)
turtle.begin_fill()
for x in range(360):
turtle.left(1)
turtle.forward(1)
turtle.end_fill()
input("Press any key to exit ...")<file_sep>/TurtlePython/TurtleFinal.py
from turtle import*
import random
turtle = Turtle()
screen = Screen()
screen.colormode(255)
#Screen Color
R = 0
G = 0
B = 0
#Turtle Color
R1 = 255
G1 = 255
B1 = 255
screen.bgcolor((R, G, B))
turtle.color((R1, G1, B1))
turtle.pensize(5)
turtle.speed(10000)
for i in range(360):
turtle.color((R1, G1, B1))
R1 = random.randint(0,255)
G1 = random.randint(0,255)
B1 = random.randint(0,255)
turtle.circle(100)
turtle.forward(500)
turtle.left(90)
turtle.forward(20)
turtle.left(90)
turtle.forward(500)
turtle.left(90)
turtle.forward(20)
turtle.left(90)
turtle.left(1)
input("Press any key to exit ...")<file_sep>/TurtlePython/Face.py
from turtle import*
turtle = Turtle()
screen = Screen()
screen.colormode(255)
#Screen Color
R = 0
G = 0
B = 0
#Turtle Color
R1 = 255
G1 = 255
B1 = 255
screen.bgcolor((R, G, B))
turtle.color((R1, G1, B1))
turtle.pensize(5)
turtle.circle(100)
turtle.pu()
turtle.goto(65, 175)
turtle.pd()
turtle.left(45)
turtle.forward(80)
for x in range(90):
turtle.left(2)
turtle.forward(1)
turtle.forward(100)
turtle.pu()
turtle.goto(-65, 175)
turtle.pd()
turtle.left(-90)
turtle.forward(80)
for x in range(90):
turtle.right(2)
turtle.forward(1)
turtle.forward(100)
turtle.pu()
turtle.goto(0, 40)
turtle.left(45)
turtle.pd()
turtle.circle(20)
turtle.pu()
turtle.goto(30, 120)
turtle.pd()
turtle.circle(20)
turtle.circle(10)
turtle.pu()
turtle.goto(-30, 120)
turtle.pd()
turtle.circle(20)
turtle.circle(10)
turtle.pu()
turtle.goto(-500,-500)
input("Press any key to exit ...")<file_sep>/SonicPi/Test.rb
in_thread do
loop do
sample :loop_amen
sleep 1.753
end
end
in_thread do
16.times do
play 75
sleep 1.753
play 74
sleep 0.25
end
end<file_sep>/SonicPi/Original.rb
in_thread do
use_synth :mod_pulse
play 65
play 69
sleep 0.5
play 65
sleep 0.2
play 63
sleep 0.5
play 65
sleep 0.5
play 65
sleep 0.5
play 65
sleep 0.5
play 60
sleep 0.2
play 65
end
in_thread do
use_synth :saw
sleep 2
play 38
sleep 0.25
play 50
sleep 0.25
play 62
end
in_thread do
play 99
sleep 2
play 99
sleep 2
play 99
sleep 2
end
<file_sep>/TurtlePython/BigCross.py
from turtle import*
turtle = Turtle()
screen = Screen()
screen.colormode(255)
#Screen Color
R = 0
G = 0
B = 0
#Turtle Color
R1 = 255
G1 = 255
B1 = 255
screen.bgcolor((R, G, B))
turtle.color((R1, G1, B1))
turtle.left(0)
turtle.forward(180)
turtle.left(90)
turtle.forward(90)
turtle.left(90)
turtle.forward(180)
#Turtle Color2
R1 = 0
G1 = 255
B1 = 255
turtle.color((R1, G1, B1))
turtle.right(90)
turtle.forward(180)
turtle.left(90)
turtle.forward(90)
turtle.left(90)
turtle.forward(180)
#Turtle Color3
R1 = 255
G1 = 0
B1 = 255
turtle.color((R1, G1, B1))
turtle.right(90)
turtle.forward(180)
turtle.left(90)
turtle.forward(90)
turtle.left(90)
turtle.forward(180)
#Turtle Color4
R1 = 255
G1 = 255
B1 = 0
turtle.color((R1, G1, B1))
turtle.right(90)
turtle.forward(270)
turtle.left(90)
turtle.forward(90)
turtle.left(90)
turtle.forward(270)
input("Press any key to exit ...")<file_sep>/Python/RecSize.py
#Python rectangle size finder
print("Hello there how wide is your Rectange? \n(In mm)")
lenght=input()
print("Ok, How tall is the Rectangle? \n(In mm)")
hight=input()
print("One Moment Please \nPRESS ENTER")
input()
area = int(lenght) * int(hight)
perimeter = int(lenght) + int(hight) * 2
#int(parimiter) * 2
print("Your Rectangle")
print(f"Has a width of {lenght}(mm) wide")
print(f"Has a hight of {hight}(mm)tall")
print(f"Has an area = {area}(mm^2)")
print(f"has a perimeter = {perimeter}(mm)")<file_sep>/Python/test.py
print("Hi, I am Python. What's your name")
name=input()
print(f"Hello {name} nice to meet you") | 9596fb3efd08975b895a5681a3e56123f38ad89d | [
"Markdown",
"Python",
"Ruby"
] | 12 | Python | CaptionAdam/ComputerScience10 | 9e128a8e96fda70aa8139896c2ffd4c5fd2cd8df | ab5d790861d11b3f6cfe913c264e8f259d718c64 |
refs/heads/master | <repo_name>manishbisht2210/Trade-test<file_sep>/src/main/java/com/hackerrank/stocktrade/service/TradeService.java
package com.hackerrank.stocktrade.service;
import com.hackerrank.stocktrade.exceptions.AlreadyPresentException;
import com.hackerrank.stocktrade.exceptions.TradeNotFoundException;
import com.hackerrank.stocktrade.model.Trade;
import java.util.List;
public interface TradeService {
void saveTrade(Trade trade) throws AlreadyPresentException;
Trade getTradeById(Long id) throws TradeNotFoundException;
List<Trade> getAllTrade();
List<Trade> getTradeByUserId(Long id) throws TradeNotFoundException;
void deleteTrades();
List<Trade> getTradeBySymbol(String symbol) throws TradeNotFoundException;
List<Trade> getTradeBySymbolAndUser(String symbol, Long id) throws TradeNotFoundException;
}
<file_sep>/src/main/java/com/hackerrank/stocktrade/controller/TradesController.java
package com.hackerrank.stocktrade.controller;
import com.hackerrank.stocktrade.exceptions.AlreadyPresentException;
import com.hackerrank.stocktrade.exceptions.TradeNotFoundException;
import com.hackerrank.stocktrade.model.Trade;
import com.hackerrank.stocktrade.service.TradeService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/trades")
public class TradesController {
@Autowired
TradeService tradeService;
@PostMapping
@ResponseStatus(value = HttpStatus.CREATED)
public void createTrade(@RequestBody Trade trade) throws AlreadyPresentException {
tradeService.saveTrade(trade);
}
@GetMapping("/{id}")
@ResponseStatus(value = HttpStatus.OK)
public Trade getTrade(@PathVariable("id") Long id) throws TradeNotFoundException {
return tradeService.getTradeById(id);
}
@GetMapping
@ResponseStatus(value = HttpStatus.OK)
public List<Trade> getAllTrade() {
return tradeService.getAllTrade();
}
@GetMapping("/users/{userID}")
@ResponseStatus(value = HttpStatus.OK)
public List<Trade> getTradeByUser(@PathVariable("userID") Long id) throws TradeNotFoundException {
return tradeService.getTradeByUserId(id);
}
@GetMapping("/stocks/{symbol}")
@ResponseStatus(value = HttpStatus.OK)
public List<Trade> getTradeByUser(@PathVariable("symbol") String symbol)
throws TradeNotFoundException {
return tradeService.getTradeBySymbol(symbol);
}
@GetMapping("/users/{userID}/stocks/{symbol}")
@ResponseStatus(value = HttpStatus.OK)
public List<Trade> getTradeByUser(@PathVariable("userID") Long id,
@PathVariable("symbol") String symbol) throws TradeNotFoundException {
return tradeService.getTradeBySymbolAndUser(symbol, id);
}
}
<file_sep>/src/main/java/com/hackerrank/stocktrade/exceptions/AlreadyPresentException.java
package com.hackerrank.stocktrade.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class AlreadyPresentException extends Exception {
public AlreadyPresentException(){
super("Trade Already Present");
}
}
<file_sep>/src/main/java/com/hackerrank/stocktrade/controller/ResourcesController.java
package com.hackerrank.stocktrade.controller;
import com.hackerrank.stocktrade.service.TradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/erase")
public class ResourcesController {
@Autowired
TradeService tradeService;
@DeleteMapping
@ResponseStatus(value = HttpStatus.OK)
public void deleteTrade() {
tradeService.deleteTrades();
}
}
| fd00b2ae12daad41f53d473b035b53b9ae87ba85 | [
"Java"
] | 4 | Java | manishbisht2210/Trade-test | 592d896d3b6fcad625fe21385ea03d25f1c0aeb3 | 4907623710e7674475de48f79861937c36e211e1 |
refs/heads/master | <repo_name>Batldingar/DIC<file_sep>/Projekt_FIR_Filter/FIR_Filter/FIR_Main.c
#include <C8051F330.h>
sbit LED = P1^3; //for debugging on simulator
extern void init_device();
void main() {
PCA0MD &= 0xbf; //disable watchdog
init_device(); //initialize devices (config.c)
EA = 1; //enable all interrupts
TR0 = 1; //start timer 0
while (1) {} //basically nop while waiting for interrupts
}<file_sep>/Projekt_FIR_Filter/FIR_Filter/FIR_Sub.c
#include <C8051F330.h>
#include <stdio.h> //c standard input/output library
#define ORDER 19
const float code lpCoef_cdata[ORDER+1] = {
-0.0031996,-0.0047849,-0.0042133,0.0025155,0.018631,
0.045285,0.080213,0.11756,0.14923,0.16745,
0.16745,0.14923,0.11756,0.080213,0.045285,
0.018631,0.0025155,-0.0042133,-0.0047849,-0.0031996
};
const float code hpCoef_cdata[ORDER+1] = {
0.0086171,-0.030235,0.019977,0.029451,-0.013986,
-0.057481,-0.0054963,0.11526,0.094903,-0.49306,
0.49306,-0.094903,-0.11526,0.0054963,0.057481,
0.013986,-0.029451,-0.019977,0.030235,-0.0086171
};
const float code apCoef_cdata[ORDER+1] = {
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
int ringbuffer[ORDER+1]; // contains adc values
float xdata lpCoef[ORDER+1]; // for the calculation of the
float xdata hpCoef[ORDER+1]; // filtercoefficients the last
float xdata apCoef[ORDER+1]; // ORDER+1 values are needed
// index-variables
unsigned int coefIndex0 = 0;
unsigned int coefIndex1 = 0;
unsigned int counterIndex = 0;
// pointer-variables
int pointer0 = 0; // points to the current adc-value in the ringbuffer
int pointer1 = 0; // points to the previous adc-value in the ringbuffer
int filterPointer = 0;
// filter-variables
float filterValue = 0.0f;
int trigger = 0; // when the triggercondition is fullfilled the trigger is set
int triggerType = 1; // selected trigger-type (falling or rising edge)
int filterType = 1; // selected filter-type (lowpass, highpass or allpass)
bit startup = 1; // used to load the coefficients into xdata at startup
sbit LED_bit = P1^3; // LED control
// function prototypes
void loadCoef (void);
void calcValues (void);
void adc_interrupt() interrupt 10 { // ADC-Interrup (activated by setting AD0BUSY in the timer-interrupt)
AD0BUSY = 0; // resets the adc-interrupt
AD0INT = 0;
ringbuffer[pointer0] = ADC0L + (ADC0H << 8) - 512; // reading the adc-values and storing them in a ringringbuffer
// -512 to achieve a 10 bit range (1024 values) from -512 to +512
// shifting is necesarry because of how ADC0L and ADC0H are made up
return;
}
void serial_interrupt() interrupt 4 { // UART
if (RI0 == 1) { // check for receive interrupt
// check for UART input
if(SBUF0 == 'L' || SBUF0 == 'l') {
filterType = 1;
TI0 = 1;
puts("\nLowpass\n");
TI0 = 0;
}
if(SBUF0 == 'H' || SBUF0 == 'h') {
filterType = 2;
TI0 = 1;
puts("\nHighpass\n");
TI0 = 0;
}
if(SBUF0 == 'A' || SBUF0 == 'a') {
filterType = 3;
TI0 = 1;
puts("\nAllpass\n");
TI0 = 0;
}
if(SBUF0 == 'F') {
triggerType = 1;
TI0 = 1;
puts("\nRising edge\n");
TI0 = 0;
}
if(SBUF0 == 'f') {
triggerType = 2;
TI0 = 1;
puts("\nFalling edge\n");
TI0 = 0;
}
RI0 = 0; // clear the receive interrupt in order to receive new input
}
else {
TI0 = 0; // clear the transmit interrupt
return;
}
}
void timer_interrupt() interrupt 1 {
TF0 = 0;
TL0 = 0x4F;
TH0 = 0x9C;
if(startup) {
loadCoef(); // move the coefficients from code to xdata at startup because of a compiler-error
}
AD0BUSY = 1; // activates the adc-interrupt (reads the adc-values)
if(((ringbuffer[pointer0] >= 0) && (ringbuffer[pointer1] <= 0) && (trigger == 0)) && (triggerType == 1)) // rising edge
{
trigger = 1; // sets the trigger
LED_bit = 0; // the led controls are inverted so 0 means that the led emits light
}
if(((ringbuffer[pointer0] <= 0) && (ringbuffer[pointer1] >= 0) && (trigger == 0)) && (triggerType == 2)) // falling edge
{
trigger = 1; // sets the trigger
LED_bit = 0; // the led controls are inverted so 0 means that the led emits light
}
pointer1 = pointer0; // the previous adc value becomes the now current adc value in the ringbuffer
if(counterIndex<100 && trigger == 1) { // reads until 100 values are read when triggered
filterValue = 0;
filterPointer = pointer0;
coefIndex0 = 0;
while(coefIndex0 <= ORDER) { // as long as the coefficient-index stays below or equal to 19
if(filterPointer<0) { // when filterpointer is below 0
filterPointer = ORDER; // reset filterPointer to 19
}
calcValues(); // calculate the filter-values (adc-value * filter-coefficient)
filterPointer--;
coefIndex0++;
}
//write the results:
TI0 = 1;
printf("%d,%f\n", ringbuffer[pointer0], filterValue); // writes the "raw" values and the filtered vales to the uart in a csv-format
// in order to use them for further processing/analyzing in matlab
while(!TI0); // wait for the transmit-interrupt-flag
TI0 = 0; // reset it
counterIndex++;
} else {
LED_bit = 1; // deactivate the led
trigger = 0;
counterIndex = 0;
}
pointer0++;
if(pointer0 > ORDER) { //if the current adc-value exceeds the order (19)
pointer0 = 0; // reset it
}
return;
}
void loadCoef(void) { // move the coefficients from code to xdata at startup because of a compiler-error
for(coefIndex1 = 0; coefIndex1<=ORDER; coefIndex1++) {
lpCoef[coefIndex1] = lpCoef_cdata[coefIndex1];
hpCoef[coefIndex1] = hpCoef_cdata[coefIndex1];
apCoef[coefIndex1] = apCoef_cdata[coefIndex1];
ringbuffer[coefIndex1] = 0; // clear the ringbuffer
}
startup = 0; // startup is done
return;
}
void calcValues(void) { // calculate the filter-values (adc-value * filter-coefficient)
if(filterType == 1) { // lowpass
filterValue += (float)ringbuffer[filterPointer] * lpCoef[coefIndex0];
}
else if(filterType == 2) { // highpass
filterValue += (float)ringbuffer[filterPointer] * hpCoef[coefIndex0];
}
else if (filterType == 3) { // allpass
filterValue += (float)ringbuffer[filterPointer] * apCoef[coefIndex0];
}
} | 901c78ed71e23ed7c0ed581cc84b4a72a6e9ee46 | [
"C"
] | 2 | C | Batldingar/DIC | 6404d8304d64236116d842d32c56dd40ead39c91 | 1c2f7e686f3b85dffde2fd6fcaf9fd32aa99c065 |
refs/heads/master | <repo_name>davidaguirremolins/flask-session-demo<file_sep>/README.md
# flask-session-demo
Sample code using flask-session
<file_sep>/application.py
import os
from flask import Flask, render_template, request, redirect, session
from flask_session import Session
app = Flask(__name__)
app.config['SESSION_PERMANENT'] = True
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)
counter = 1000
@app.route("/")
def index():
user = session.get('user', None)
return f"<html><body>User is {user}</body></html>"
@app.route("/create")
def create_session():
if 'user' in session:
return redirect('/')
global counter
counter += 1
user = {'username': "joe", 'email': '<EMAIL>', 'user_id': counter}
session['user'] = user
return redirect('/')
@app.route("/clear")
def clear_session():
user = session.pop('user', None)
value_now = session.get('user', None)
return f"Removed session for user {user} value is now {value_now}"
@app.route("/clearall")
def clear_all():
session.clear()
return redirect("/")
def main():
app.run(debug=True)
if __name__ == "__main__":
main()
<file_sep>/.flaskenv
FLASK_APP=application.py
#FLASK_ENV=production
FLASK_ENV=development
# see .env for DATABASE_URL and GOODREADS_API_KEY
| b0cada4121158211b2ecb22fda682e32bbf0ddd4 | [
"Markdown",
"Python",
"Shell"
] | 3 | Markdown | davidaguirremolins/flask-session-demo | 5395f91ccd0e3d2f44d84b8dcad53620cacb8da2 | c37d3ec8885f87df55238ebdc911e60ed990f2f2 |
refs/heads/master | <file_sep>from PySide import QtCore, QtGui
import sys
import time
import imguruploader
import selectionselector
import settings
class CakeShot(QtGui.QSystemTrayIcon):
uploaders = [imguruploader.ImgurUploader]
def __init__(self):
QtGui.QSystemTrayIcon.__init__(self)
self.setIcon(QtGui.QIcon("icon/cakeshot.png"))
self.menu = QtGui.QMenu()
self.take_screenshot_item = self.menu.addAction("Take Screenshot\tPlaceholder")
self.take_screenshot_item.triggered.connect(self.take_screenshot)
self.open_settings_item = self.menu.addAction("Settings")
self.open_settings_item.triggered.connect(self.open_settings)
self.setContextMenu(self.menu)
self.show()
def pre_take_screenshot(self):
timer = QtCore.QTimer(self)
timer.setSingleShot(True)
timer.timeout.connect(self.take_screenshot)
timer.start(1000)
def take_screenshot(self):
desktop = QtGui.QApplication.desktop()
print desktop.childAt(QtCore.QPoint(100, 100))
self.selector = selectionselector.SelectionSelector()
self.selector.selection_made.connect(self.selection_made)
self.selector.select()
def selection_made(self, rect):
sound = QtGui.QSound("snd/shutter.wav")
sound.play()
screenshot = QtGui.QPixmap.grabWindow(QtGui.QApplication.desktop().winId(), rect.x(), rect.y(), rect.width(),
rect.height())
buffer = QtCore.QBuffer()
buffer.open(QtCore.QBuffer.ReadWrite)
screenshot.save(buffer, "PNG")
buffer.seek(0)
data = buffer.data()
uploader = CakeShot.uploaders[QtCore.QSettings().value("options/uploaders/uploader", 0)]()
try:
link = uploader.upload(data.data())
self.showMessage("Upload Complete!", link)
QtGui.QApplication.clipboard().setText(link)
except BaseException as e:
self.showMessage("An error occured :(", e.message, QtGui.QSystemTrayIcon.Critical)
def open_settings(self):
self.settings_window = settings.SettingsWindow()
def main():
app = QtGui.QApplication(sys.argv)
app.setApplicationName("CakeShot")
app.setApplicationVersion("1.0")
app.setOrganizationName("CrateMuncher")
app.setOrganizationDomain("cratemuncher.net")
app.setWindowIcon(QtGui.QIcon("icon/cakeshot.png"))
app.setQuitOnLastWindowClosed(False)
cs = CakeShot()
sys.exit(app.exec_())
if __name__ == "__main__":
main()<file_sep>from PySide import QtGui
import json
import requests
class ImgurUploader(object):
name = "Imgur"
def upload(self, image_str):
data = json.load(open("api.json", "r"))
imgur_keys = data["imgur"]
id = imgur_keys["client-id"]
secret = imgur_keys["client-secret"]
files = {"image": ('image.png', image_str)}
headers = {"authorization": "Client-ID " + id}
response = requests.post("https://api.imgur.com/3/image", files=files, headers=headers)
return response.json()["data"]["link"]
def show_settings(self):
dialog = QtGui.QDialog()
dialog.exec_()<file_sep>CakeShot - a screenshot tool
First image uploaded! http://i.imgur.com/iGdVfw6.png
# Credits
Shutter sound - http://www.freesound.org/people/benjohansen/sounds/87149/<file_sep>from PySide import QtCore, QtGui
class SelectionSelector(QtGui.QGraphicsView):
selection_made = QtCore.Signal(QtCore.QRect)
def __init__(self):
QtGui.QGraphicsView.__init__(self)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setStyleSheet("background:transparent;")
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.scene = QtGui.QGraphicsScene(self)
self.scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
self.setScene(self.scene)
self.setWindowTitle("CakeShot")
self.pixmap = QtGui.QPixmap(QtGui.QApplication.desktop().width(), QtGui.QApplication.desktop().height())
self.origin = None
self.mouse_down_last = False
QtGui.QApplication.instance().installEventFilter(self)
def select(self):
self.showFullScreen()
self.pixmap_item = self.scene.addPixmap(self.pixmap)
self.draw_overlay()
self.grabKeyboard()
self.grabMouse()
def draw_overlay(self):
self.pixmap.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(self.pixmap)
painter.fillRect(0, 0, QtGui.QApplication.desktop().width(), QtGui.QApplication.desktop().height(),
QtGui.QColor(0, 0, 0, 127))
if self.origin is not None:
painter.setCompositionMode(QtGui.QPainter.CompositionMode_Source)
from_pos = self.origin
to_pos = QtGui.QCursor.pos()
painter.fillRect(QtCore.QRect(from_pos, to_pos), QtGui.QColor(0, 0, 0, 0))
txt = str(abs(from_pos.x() - to_pos.x())) + "x" + str(abs(from_pos.y() - to_pos.y()))
font = QtGui.QFont()
font.setStyleHint(QtGui.QFont.SansSerif)
font.setPointSize(32)
font.setBold(True)
painter.setFont(font)
painter.setPen(QtGui.QColor(127, 127, 127, 127))
painter.drawText(QtCore.QRect(from_pos, to_pos), QtCore.Qt.AlignVCenter | QtCore.Qt.AlignCenter, txt)
self.pixmap_item.setPixmap(self.pixmap)
def eventFilter(self, obj, evt): # I couldn't get normal events to work, so here's a workaround
if type(evt) is QtGui.QMouseEvent:
if QtGui.QApplication.mouseButtons() == QtCore.Qt.LeftButton:
if not self.mouse_down_last:
# Mouse down
self.mouse_down_last = True
self.origin = QtGui.QCursor.pos()
else:
if self.mouse_down_last:
# Mouse up
self.mouse_down_last = False
self.hide()
settings = QtCore.QSettings()
QtCore.QTimer.singleShot(int(settings.value("options/delay", 250)), self.send_final)
self.draw_overlay()
return False
def send_final(self): # Worst name ever
self.selection_made.emit(QtCore.QRect(self.origin, QtGui.QCursor.pos()))
self.destroy()<file_sep>from PySide import QtCore, QtGui
import cakeshot
import utils
class SettingsWindow(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(SettingsWindow, self).__init__(*args, **kwargs)
self.options_tab = OptionsTab(self)
self.uploaders_tab = UploadersTab(self)
tabs = QtGui.QTabWidget()
tabs.addTab(self.options_tab, "Options")
tabs.addTab(self.uploaders_tab, "Uploaders")
hbox = QtGui.QHBoxLayout()
hbox.addWidget(tabs)
self.setLayout(hbox)
self.setWindowTitle("CakeShot")
self.show()
class OptionsTab(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(OptionsTab, self).__init__(*args, **kwargs)
self.settings = QtCore.QSettings()
self.delay_spinner = QtGui.QSpinBox(self)
self.delay_spinner.setMinimum(0)
self.delay_spinner.setMaximum(5000)
self.delay_spinner.setValue(self.settings.value("options/delay", 250))
self.prefix_edit = QtGui.QLineEdit()
self.prefix_edit.setText(self.settings.value("options/naming/prefix", ""))
self.prefix_edit.textChanged.connect(self.update_naming)
self.suffix_edit = QtGui.QLineEdit()
self.suffix_edit.setText(self.settings.value("options/naming/suffix", ""))
self.suffix_edit.textChanged.connect(self.update_naming)
self.naming = QtGui.QComboBox()
self.naming.addItem("Random numbers")
self.naming.addItem("Random letters")
self.naming.addItem("Time")
self.naming.addItem("Unix timestamp")
self.naming.setCurrentIndex(self.settings.value("options/naming/naming", 3))
self.naming.currentIndexChanged.connect(self.update_naming)
self.format = QtGui.QLineEdit()
self.format.setText(self.settings.value("options/naming/format", "%Y-%m-%d %H:%M:%S"))
self.format.textChanged.connect(self.update_naming)
self.amount = QtGui.QSpinBox()
self.amount.setValue(self.settings.value("options/naming/amount", 5))
self.amount.valueChanged.connect(self.update_naming)
self.naming_example = QtGui.QLabel()
self.save_button = QtGui.QPushButton("Save")
self.save_button.clicked.connect(self.save)
form = QtGui.QFormLayout()
form.addRow("Screenshot delay (ms)", self.delay_spinner)
form.addRow("Naming prefix", self.prefix_edit)
form.addRow("Naming", self.naming)
form.addRow("Date format", self.format)
form.addRow("Digit/character amount", self.amount)
form.addRow("Naming suffix", self.suffix_edit)
form.addRow("Naming example", self.naming_example)
vbox = QtGui.QVBoxLayout()
vbox.addLayout(form)
vbox.addWidget(self.save_button)
self.setLayout(vbox)
self.update_naming()
def update_naming(self):
self.save()
naming = utils.get_filename()
self.naming_example.setText(naming)
if self.naming.currentIndex() == 0:
self.amount.setEnabled(True)
self.format.setEnabled(False)
elif self.naming.currentIndex() == 1:
self.amount.setEnabled(True)
self.format.setEnabled(False)
elif self.naming.currentIndex() == 2:
self.amount.setEnabled(False)
self.format.setEnabled(True)
elif self.naming.currentIndex() == 3:
self.amount.setEnabled(False)
self.format.setEnabled(False)
def save(self):
self.settings.setValue("options/naming/amount", self.amount.value())
self.settings.setValue("options/delay", self.delay_spinner.value())
self.settings.setValue("options/naming/prefix", self.prefix_edit.text())
self.settings.setValue("options/naming/naming", self.naming.currentIndex())
self.settings.setValue("options/naming/suffix", self.suffix_edit.text())
self.settings.setValue("options/naming/format", self.format.text())
class UploadersTab(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(UploadersTab, self).__init__(*args, **kwargs)
settings = QtCore.QSettings()
self.uploaders_list = QtGui.QListWidget()
for uploader in cakeshot.CakeShot.uploaders:
self.uploaders_list.addItem(QtGui.QListWidgetItem(uploader.name))
self.uploaders_list.item(settings.value("options/uploaders/uploader", 0)).setSelected(True)
self.uploaders_list.currentItemChanged.connect(self.save)
self.settings_btn = QtGui.QPushButton("Settings")
self.settings_btn.clicked.connect(self.open_settings)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.uploaders_list)
vbox.addWidget(self.settings_btn)
self.setLayout(vbox)
def open_settings(self):
uploader = cakeshot.CakeShot.uploaders[self.uploaders_list.currentIndex().row()]
uploader().show_settings()
def save(self):
settings = QtCore.QSettings()
settings.setValue("options/uploaders/uploader", self.uploaders_list.currentIndex().row())<file_sep>import random
import string
from PySide import QtCore
import datetime
import time
old_time = ""
def get_filename():
settings = QtCore.QSettings()
prefix = settings.value("options/naming/prefix", "")
naming_num = settings.value("options/naming/naming", 3)
suffix = settings.value("options/naming/suffix", "")
format_ = settings.value("options/naming/format", "%Y-%m-%d %H:%M:%S")
amount = settings.value("options/naming/amount", 5)
naming = ""
if naming_num == 0:
naming = ''.join(random.choice(string.digits) for x in range(amount))
elif naming_num == 1:
naming = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(amount))
elif naming_num == 2:
try:
naming = datetime.datetime.now().strftime(format_)
old_time = naming
except ValueError:
naming = ""
elif naming_num == 3:
naming = str(int(time.time()))
return prefix + naming + suffix + ".png" | 734f217f4c8660b984ebcd1a6e8d7ab843c044b4 | [
"Markdown",
"Python"
] | 6 | Python | CrateMuncher/CakeShot | 259f9f3e5a0381d255c6da895d3ad8fa02fec398 | adc0058a45cf727c79501f5f280a3e4264deec3b |
refs/heads/master | <file_sep>from abc import ABC, abstractmethod
from pyspark.sql import DataFrame
from ..context import Context
class ExecutionContainer(ABC):
def __init__(self, context: Context):
self.context = context
self.__logger = self.context.logger.getLogger(__name__)
self._dataframe = None
@abstractmethod
def execute(self):
"""Run the execution to produce the dataframe"""
@property
def dataframe(self):
"""Return the output dataframe from this pipeline"""
if not self._dataframe:
self.execute()
return self._dataframe
@dataframe.setter
def dataframe(self, df: DataFrame):
if not isinstance(df, DataFrame):
self.__logger.error("cannot set unknown type as dataframe")
raise ValueError("Not a valid dataframe instance")
self._dataframe = df
def exec(self):
"""Force the execution of the dataframe pipeline"""
self.dataframe = self.execute()
return self
<file_sep>FROM ubuntu:latest
# Install OpenJDK 8
RUN \
apt-get update && \
apt-get install -y openjdk-8-jdk && \
rm -rf /var/lib/apt/lists/*
# Install Python
RUN \
apt-get update && \
apt-get install -y python3 python3-dev python3-pip python3-virtualenv zip && \
rm -rf /var/lib/apt/lists/*
RUN mkdir -p /opt/src
COPY requirements.txt Makefile /opt/
RUN pip3 install --upgrade pip
RUN pip3 install -r /opt/requirements.txt && pip freeze
COPY src /opt/src
# Define working directory
WORKDIR /opt
ENTRYPOINT ["make","run/spark"]
<file_sep>from pyspark.sql import DataFrame
import pyspark.sql.functions as f
from ..context import Context
from ..transform.transform import Transform
class Display:
"""
Display Class
- Displays two dataframes to console
- Monthly Average
- 45 day Moving Average
"""
def __init__(self, context: Context, transform: Transform):
self.context = context
self.transform = transform
self.__logger = self.context.logger.getLogger(__name__)
def exec(self):
"""
Displaying two dataframes:
- Monthly Average
- 45 day Moving Average
"""
self.display_monthly_average(self.transform.dataframe).show(truncate=False)
self.display_45day_moving_average(self.transform.dataframe).orderBy(f.col("tpep_dropoff_date").desc()).show(truncate=False)
def display_monthly_average(self, dataframe: DataFrame) -> DataFrame:
"""
Aggregating data to get the monthly average.
:param dataframe:
"""
self.__logger.info("Monthly Average Trips")
return dataframe.groupBy("tpep_dropoff_month_year").agg(
f.round(f.avg("daily_avg_trip_distance"), 2).alias("monthly_avg_trip_distance")
).sort(f.col("tpep_dropoff_month_year").desc())
def display_45day_moving_average(self, dataframe: DataFrame) -> DataFrame:
"""
Calculating the 45 day average
:param dataframe:
"""
self.__logger.info("45 day moving average")
dataframe.createOrReplaceTempView("daily_avg_trips")
return self.context.spark.sql(
"select tpep_dropoff_date, "
"avg(daily_avg_trip_distance) OVER(ORDER BY tpep_dropoff_date asc "
"ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) as "
"45_day_moving_average from daily_avg_trips order by tpep_dropoff_date desc"
)
<file_sep>tap "homebrew/bundle"
tap "homebrew/cask"
tap "homebrew/cask-versions"
tap "homebrew/core"
cask "java8"
brew "apache-spark"
brew "git"
brew "python"
brew "scala"
brew "docker"
<file_sep>import os
from pyspark.sql import DataFrame
from ..utils.containers import ExecutionContainer
class Ingest(ExecutionContainer):
"""
Ingestion Class
- Ingest the CSV(s) into memory
"""
def __init__(self, context):
super().__init__(context)
self.context = context
self.spark = self.context.spark
self.__logger = self.context.logger.getLogger(__name__)
self.source_path = os.path.join(
os.getcwd(), self.context.get("SOURCE_PATH"), "*.csv"
)
def execute(self) -> DataFrame:
"""
Ingesting all dataframes under the specified directory into memory.
:return:
"""
self.__logger.info(f"Reading file from {self.source_path}")
self.dataframe = self.spark.read.option("inferSchema", "true").csv(
self.source_path, header=True, schema=None
)
self.__logger.info(f"Successfully read file from {self.source_path}")
return self.dataframe
<file_sep>import datetime
import pandas as pd
from pandas.testing import assert_frame_equal
from tests.base import PySparkTest
class TestTransform(PySparkTest):
def test_should_select_required_columns(self):
pandas_df = pd.DataFrame(
{
"tpep_dropoff_datetime": ["2021-03-23"],
"trip_distance": [2],
"remove": ["test"],
}
)
expected_df = pd.DataFrame(
{"tpep_dropoff_datetime": ["2021-03-23"], "trip_distance": [2]}
)
self.assert_dataframe(
self.transform.select_required_colums, expected_df, pandas_df
)
def test_should_extract_date_from_drop_off_datetime_col(self):
pandas_df = pd.DataFrame(
{
"tpep_dropoff_datetime": ["2021-03-23"],
"trip_distance": [2],
}
)
expected_df = pd.DataFrame(
{
"tpep_dropoff_datetime": ["2021-03-23"],
"trip_distance": [2],
"tpep_dropoff_date": [datetime.datetime(2021, 3, 23)],
}
)
self.assert_dataframe(
self.transform.extract_date_from_drop_off_datetime_col,
expected_df,
pandas_df,
)
def test_should_get_daily_average_of_trips(self):
pandas_df = pd.DataFrame(
{
"tpep_dropoff_datetime": ["2021-03-23"],
"trip_distance": [2],
"tpep_dropoff_date": [datetime.datetime(2021, 3, 23)],
}
)
expected_df = pd.DataFrame(
{
"tpep_dropoff_date": [datetime.datetime(2021, 3, 23)],
"daily_avg_trip_distance": [2.0],
}
)
self.assert_dataframe(
self.transform.daily_average_of_trips, expected_df, pandas_df
)
def test_should_extract_month_from_drop_off_datetime_col(self):
pandas_df = pd.DataFrame(
{
"tpep_dropoff_date": [datetime.datetime(2021, 3, 23)],
"daily_avg_trip_distance": [2.0],
}
)
expected_df = pd.DataFrame(
{
"tpep_dropoff_date": [datetime.datetime(2021, 3, 23)],
"daily_avg_trip_distance": [2.0],
"tpep_dropoff_month_year": ["2021-03"],
}
)
self.assert_dataframe(
self.transform.extract_month_from_drop_off_datetime_col,
expected_df,
pandas_df,
)
def test_should_execute_transformations(self):
expected_df = pd.DataFrame(
{
"tpep_dropoff_date": [
datetime.datetime(2021, 3, 24),
datetime.datetime(2021, 3, 23)
],
"daily_avg_trip_distance": [2.0, 2.0],
"tpep_dropoff_month_year": ["2021-03", "2021-03"],
}
)
actual_spark_df = self.transform.execute()
actual_df = actual_spark_df.toPandas()
assert_frame_equal(left=actual_df, right=expected_df, check_dtype=False)
<file_sep>class TestContext:
def test_should_get_variable_from_env(self, monkeypatch, fake_context):
expected = "test"
monkeypatch.setenv("SOURCE_PATH", expected)
actual = fake_context.get("SOURCE_PATH")
assert actual == expected
def test_should_get_variable_from_local_state(self, fake_context):
expected = "test"
fake_context.set({"SOURCE_PATH": expected})
actual = fake_context.get("SOURCE_PATH")
assert actual == expected
def test_should_set_variable_to_local_state(self, fake_context):
expected = "test"
fake_context.set({"test": expected})
actual = fake_context.get("test")
assert actual == expected
<file_sep>import os
class Context:
"""
- The Context is passed around to all tasks of the application
- Shared functions and variables can be accessed from the Context
"""
def __init__(self, app_name=None, spark=None, logger=None):
self.logger = logger
self.app_name = app_name
self.spark = spark
self.state = {}
def get(self, key):
"""
To get variables in the local state or the environment
:param key: name of the variable
:return:
"""
if key in self.state:
return self.state[key]
return os.environ.get(key)
def set(self, *args, **kwargs):
"""
Set variables to local state
:param args:
:param kwargs:
:return:
"""
if len(args) == 0 and len(kwargs) == 0:
raise ValueError(
"Setting variables onto the state requires named arguments or a dictionary"
)
for arg in args:
if not isinstance(arg, dict):
raise ValueError(
"Setting variables onto the state does not support non dictionary or non-named arguments"
)
self.state.update(arg)
if len(kwargs) > 0:
self.state.update(kwargs)
<file_sep>-include .env
export
help:
@echo "clean - remove all build, test, coverage and Python artifacts"
@echo "clean-pyc - remove Python file artifacts"
@echo "clean-test - remove test and coverage artifacts"
@echo "lint - check style"
@echo "test - run tests quickly with the default Python"
@echo "coverage - check code coverage quickly with the default Python"
@echo "build - package"
all: default
default: clean deps-dev deps tests fmt run
.venv:
if [ ! -e ".venv/bin/activate_this.py" ] ; then virtualenv --clear .venv ; fi
.venv/local:
python3 -m venv .venv
clean: clean-build clean-pyc clean-test
clean-build:
rm -fr src/libs.zip
rm -fr src/jobs.zip
clean-pyc:
find . -name '*.pyc' -exec rm -f {} +
find . -name '*.pyo' -exec rm -f {} +
find . -name '*~' -exec rm -f {} +
find . -name '__pycache__' -exec rm -fr {} +
find . -name '.pytest_cache' -exec rm -fr {} +
clean-test:
rm -fr .tox/
rm -f .coverage
rm -fr htmlcov/
rm -fr .pytest_cache
deps: .venv
. .venv/bin/activate && pip install -U -r requirements.txt -t ./src/libs
deps/local: .venv
. .venv/bin/activate && pip install -U -r requirements.txt
deps-dev: .venv
. .venv/bin/activate && pip install -U -r requirements-dev.txt
download: clean
cd src/data && curl https://nyc-tlc.s3.amazonaws.com/trip+data/yellow_tripdata_2020-07.csv -o 2020-07.csv \
&& curl https://nyc-tlc.s3.amazonaws.com/trip+data/yellow_tripdata_2020-08.csv -o 2020-08.csv \
&& curl https://nyc-tlc.s3.amazonaws.com/trip+data/yellow_tripdata_2020-09.csv -o 2020-09.csv
fmt:
. .venv/bin/activate && pylint -r n src/main.py src/jobs
test:
. .venv/bin/activate && pytest ./tests/* -s -vv && python3 -m pytest --cov-report term-missing --cov=src/jobs/code_challenge/ tests/
build: clean deps
cd ./src && zip -x main.py -x \*libs\* -r ./jobs.zip .
cd ./src/libs && zip -r ../libs.zip .
run/spark: build
cd src && spark-submit --py-files jobs.zip,libs.zip main.py --job code_challenge
run: clean .venv
. .venv/bin/activate && cd src && python3 main.py --job code_challenge
docker/run: clean
docker-compose up --build
<file_sep>import pandas as pd
from pandas.testing import assert_frame_equal
from src.jobs.code_challenge.app.ingest.ingest import Ingest
class TestIngest:
def test_should_get_csv_file(self, fake_context, monkeypatch, tmpdir):
expected_df = pd.DataFrame({"Lovely": [1, 2], "Wonderful": [1, 2]})
f = tmpdir.mkdir("data").join("hello.csv")
expected_df.to_csv(f.strpath, index=False)
monkeypatch.setenv("SOURCE_PATH", str(f.dirpath()))
ingest = Ingest(fake_context).exec()
actual_df = ingest.dataframe.toPandas()
assert_frame_equal(left=actual_df, right=expected_df, check_dtype=False)
<file_sep>import logging
import pytest
from pyspark.sql import SparkSession
from src.jobs.code_challenge.app.context import Context
@pytest.fixture
def fake_logging():
return logging
@pytest.fixture
def fake_spark():
return (
SparkSession.builder.master("local[2]")
.appName("my-local-testing-pyspark-context")
.enableHiveSupport()
.getOrCreate()
)
@pytest.fixture
def fake_context(fake_spark, fake_logging):
return Context(app_name="Fake", spark=fake_spark, logger=fake_logging)
<file_sep>import datetime
import pandas as pd
from tests.base import PySparkTest
class TestDisplay(PySparkTest):
def test_should_get_monthly_average(self):
pandas_df = pd.DataFrame(
{
"tpep_dropoff_date": [
datetime.datetime(2021, 3, 24),
datetime.datetime(2021, 3, 23)
],
"daily_avg_trip_distance": [2.0, 2.0],
"tpep_dropoff_month_year": ["2021-03", "2021-03"],
}
)
expected_df = pd.DataFrame(
{
"tpep_dropoff_month_year": ["2021-03"],
"monthly_avg_trip_distance": [2.0]
}
)
self.assert_dataframe(
self.display.display_monthly_average,
expected_df,
pandas_df
)
def test_should_display_45day_moving_average(self):
pandas_df = pd.DataFrame(
{
"tpep_dropoff_date": [
datetime.datetime(2021, 3, 24),
datetime.datetime(2021, 3, 23)
],
"daily_avg_trip_distance": [4.0, 2.0],
"tpep_dropoff_month_year": ["2021-03", "2021-03"],
}
)
expected_df = pd.DataFrame(
{
"tpep_dropoff_date": [
datetime.datetime(2021, 3, 24),
datetime.datetime(2021, 3, 23)
],
"45_day_moving_average": [3.0, 2.0]
}
)
self.assert_dataframe(
self.display.display_45day_moving_average,
expected_df,
pandas_df
)
<file_sep>import argparse
import importlib
import os
import sys
from pyspark.sql import SparkSession
def main(args):
"""
Main entry point to run the selected spark job. In here we create a spark session
that is passed to the spark job
:param args: command line arguments
"""
try:
spark = SparkSession.builder.getOrCreate()
spark.sparkContext.setLogLevel("WARN")
job_module = importlib.import_module("jobs.%s" % args.job)
job_module.run(spark)
except Exception:
sys.exit(1)
if __name__ == "__main__":
if os.path.exists("jobs.zip"):
sys.path.insert(0, "jobs.zip")
else:
sys.path.insert(0, "./jobs")
parser = argparse.ArgumentParser()
parser.add_argument("--job", type=str, required=True)
parsed_args = parser.parse_args()
main(parsed_args)
<file_sep>import datetime
import logging
from unittest import TestCase
import pandas as pd
from pandas.testing import assert_frame_equal
from pyspark.sql import SparkSession
from src.jobs.code_challenge.app.context import Context
from src.jobs.code_challenge.app.display.display import Display
from src.jobs.code_challenge.app.ingest.ingest import Ingest
from src.jobs.code_challenge.app.transform.transform import Transform
class PySparkTest(TestCase):
spark = None
@classmethod
def suppress_py4j_logging(cls):
logger = logging.getLogger("py4j")
logger.setLevel(logging.WARN)
@classmethod
def create_testing_pyspark_session(cls):
return (
SparkSession.builder.master("local[2]")
.appName("my-local-testing-pyspark-context")
.enableHiveSupport()
.getOrCreate()
)
@classmethod
def setUpClass(cls):
cls.suppress_py4j_logging()
cls.spark = cls.create_testing_pyspark_session()
cls.log = logging
cls.context = Context("test_app", cls.spark, cls.log)
cls.context.set({"SOURCE_PATH": "data/"})
cls.ingest = Ingest(cls.context)
cls.pandas_df = pd.DataFrame(
{
"tpep_dropoff_datetime": ["2021-03-23", "2021-03-24"],
"trip_distance": [2, 2],
"remove": ["test", "test"],
}
)
cls.ingest.dataframe = cls.spark.createDataFrame(cls.pandas_df)
cls.transform = Transform(cls.context, cls.ingest)
cls.display = Display(cls.context, cls.transform.dataframe)
@classmethod
def tearDownClass(cls):
cls.spark.stop()
@classmethod
def assert_dataframe(cls, func, expected_df, pandas_df):
df = cls.spark.createDataFrame(pandas_df)
actual_spark_df = func(df)
actual_df = actual_spark_df.toPandas()
assert_frame_equal(left=actual_df, right=expected_df, check_dtype=False)
<file_sep># Code Challenge Blue Yonder
### Tech
This project is based on a code challenge given by Blue Yonder.
This project is dependent on:
- PySpark - Apache Spark is an open-source cluster-computing framework, built around speed, ease of use, and streaming analytics whereas Python is a general-purpose, high-level programming language that can interact with Spark framework through pyspark.
- Docker - Docker is a tool designed to make it easier to create, deploy, and run applications by using containers.
## Getting Started Running The Project
If you have docker and python already installed in an environment, just clone the project and run the following command:
```bash
make docker/run
```
## Testing
To run all the test execute the following commands:
```bash
make .venv/local
make deps/local
make deps-dev
make test
```
## How do you scale?
This project already answers the question of scale. Im currently using Apache Spark to ingest
data, perform some transformation and display the data on to the console.
Ideally, we would have a pipeline that is orchestrated by airflow.
Files will land in an Amazon s3 bucket, which will be picked up by this process. The results will be sent back to S3 or
a relational database for presentation. If files are sent to S3 we can use Athena to
query the contents.
Spark jobs run on a cluster of nodes, which give it the ability to scale the processing of data.<file_sep>import logging
import time
from pyspark.sql import SparkSession
from .app.context import Context
from .app.display.display import Display
from .app.ingest.ingest import Ingest
from .app.transform.transform import Transform
def run(spark: SparkSession):
"""
Entry point for this job
:param spark: Spark session passed from the Main Jobs Interface
:return:
"""
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
try:
start = time.time()
context = Context("BY_Engineering_Code_Challenge", spark, logging)
logger.info("Application Started")
# Ingest CSV from source path supplied in the ENV
logger.info("Ingesting data")
ingest = Ingest(context).exec()
logger.info("Transforming ingested data")
transform = Transform(context, ingest).exec()
logger.info("Displaying the data")
Display(context, transform).exec()
logger.info("Application Successfully Completed")
end = time.time()
logger.info("Process Finished take {0:.2f} secs".format((end - start)))
except Exception as e:
logger.error("Job failed: %s", e)
raise Exception("Failure Occured whiles running the code challenge job") from e
<file_sep>from pipetools import pipe
from pyspark.sql import DataFrame
from pyspark.sql.functions import to_date, date_format, avg, col
from ..context import Context
from ..ingest.ingest import Ingest
from ..utils.containers import ExecutionContainer
class Transform(ExecutionContainer):
"""
Transformation class
- All transformation to the ingested dataset are completed here.
"""
def __init__(self, context: Context, ingest: Ingest):
super().__init__(context)
self.context = context
self.ingest = ingest
self.required_columns = ["tpep_dropoff_datetime", "trip_distance"]
self.__logger = self.context.logger.getLogger(__name__)
def execute(self) -> DataFrame:
"""
Piping one transformation into another to achieve the desired dataframe.
:return: Transformed dataframe
"""
transform = (
pipe
| self.select_required_colums
| self.extract_date_from_drop_off_datetime_col
| self.daily_average_of_trips
| self.extract_month_from_drop_off_datetime_col
)
self.dataframe = transform(self.ingest.dataframe)
return self.dataframe
def select_required_colums(self, dataframe: DataFrame) -> DataFrame:
"""
Selecting columns that are required, to achieve the desired dataframe.
:param dataframe:
:return: Dataframe with the necessary columns
"""
self.__logger.info(f"Selecting required Columns: {self.required_columns}")
return dataframe.select(*self.required_columns)
def extract_date_from_drop_off_datetime_col(
self, dataframe: DataFrame
) -> DataFrame:
"""
Extracting the date from the datetime column
:param dataframe:
:return: Dataframe with a new date column
"""
self.__logger.info("Extracting date from `tpep_dropoff_date` Column")
return dataframe.withColumn(
"tpep_dropoff_date", to_date("tpep_dropoff_datetime")
)
def daily_average_of_trips(self, dateframe: DataFrame) -> DataFrame:
"""
Transforming the dataframe into daily average trips
:param dateframe:
:return: Dataframe that has the day and the daily average.
"""
self.__logger.info("Transforming dataframe to get daily average of trips")
return dateframe.groupBy("tpep_dropoff_date").agg(
avg("trip_distance").alias("daily_avg_trip_distance")
)
def extract_month_from_drop_off_datetime_col(
self, dataframe: DataFrame
) -> DataFrame:
"""
Extracting the month and year from the datetime column
:param dataframe:
:return: Dataframe with an additional column that has the year and month
"""
self.__logger.info("Extracting month and year from `tpep_dropoff_date` Column")
return dataframe.withColumn(
"tpep_dropoff_month_year", date_format(col("tpep_dropoff_date"), "yyyy-MM")
)
| 5dfa215e6d8557d906f9379bbffe9ac7b28b98ad | [
"Ruby",
"Markdown",
"Makefile",
"Python",
"Dockerfile"
] | 17 | Python | georgeclarke23/code_challenge_BY | 9f723c654dbaa60d2535b9803174293e61df5920 | 36155ee45b0fd384ae2a1194eb110a439cc730dd |
refs/heads/master | <file_sep>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdlib.h>
int min_val, max_val, avg_val;
int* data;
int count;
void* get_min(void* param);
void* get_max(void* param);
void* get_avg(void* param);
int main(int argc, char* argv[]){
count = argc-1;
if(count == 0){
printf("You must enter some numbers\n\n");
return 1;
}
data = (int *) malloc(count * sizeof(int));
for(int i=0 ; i<count ; i++){
data[i] = atoi(argv[i+1]);
}
pthread_t tid_min, tid_max, tid_avg;
pthread_create(&tid_min, NULL, get_min, NULL);
pthread_join(tid_min, NULL);
pthread_create(&tid_max, NULL, get_max, NULL);
pthread_join(tid_max, NULL);
pthread_create(&tid_avg, NULL, get_avg, NULL);
pthread_join(tid_avg, NULL);
printf("The average value is %d\n", avg_val);
printf("The minimum value is %d\n", min_val);
printf("The maximum value is %d\n", max_val);
free(data);
return 0;
}
void* get_min(void* param){
min_val = data[0];
for (int i=0 ; i<count ; i++){
min_val = min_val > data[i] ? data[i] : min_val;
}
pthread_exit(NULL);
}
void* get_max(void* param){
max_val = data[0];
for (int i=0 ; i<count ; i++){
max_val = max_val < data[i] ? data[i] : max_val;
}
pthread_exit(NULL);
}
void* get_avg(void* param){
for (int i=0 ; i<count ; i++){
avg_val += data[i];
}
avg_val /= count;
pthread_exit(NULL);
}
<file_sep>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
void* runner(void* param);
int value = 0;
int main(){
pid_t pid;
pthread_t tid;
pthread_attr_t attr;
pid = fork();
if(pid ==0){
fork();
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, NULL);
pthread_join(tid, NULL);
printf("Child: value=%d\n", value);
}else if(pid >0){
wait(NULL);
printf("Parent: value=%d\n", value);
}
return 0;
}
void* runner(void* param){
value = 5;
pthread_exit(0);
}
<file_sep>#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdatomic.h>
#define SIZE 20
int top;
int stack[SIZE];
volatile int lock = 0;
volatile int available_lock = 0;
void push(int x);
int pop();
int is_empty();
void* produce(void*);
void* consume(void*);
void acquire(char c);
void release(char c);
int main(){
stack[0] = 5;
stack[1] = 6;
top = 2;
pthread_t tid_producer;
pthread_t tid_consumer;
pthread_create(&tid_producer, NULL, produce, NULL);
pthread_create(&tid_consumer, NULL, consume, NULL);
pthread_join(tid_producer, NULL);
pthread_join(tid_consumer, NULL);
for(int i=0 ; i<top ; i++){
printf("%d - ", stack[i]);
}
printf("\n");
return 0;
}
void acquire(char c){
while(atomic_compare_exchange_strong(&lock, &available_lock, 1)){
printf("waiting in %c\n", c);
}
printf("acquired for %c \n", c);
}
void release(char c){
printf("released from %c \n", c);
lock = 0;
}
void push(int x){
//sleep(0.1);
acquire('s');
if(top < SIZE){
stack[top] = x;
sleep(0.01);
top ++;
}else{
printf("Stack is Full\n");
}
release('s');
}
int pop(){
sleep(0.1);
int val = -1;
acquire('p');
if(! is_empty() ){
top--;
sleep(0.01);
val = stack[top];
}else{
printf("Stack is empty\n");
}
release('p');
return val;
}
int is_empty(){
return top==0;
}
void* produce(void* param){
push(8);
pthread_exit(NULL);
}
void* consume(void* param){
printf("value poped = %d\n", pop());
pthread_exit(NULL);
}
<file_sep># Operating-Systems
This repository contains the source codes for operating systems discussion sheets.
Course Link:
https://sites.google.com/view/ahmedamershahin/courses/spring-2020/cse-325-operating-systems
<file_sep>#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#define SIZE 5
int num[SIZE] = {0, 1, 2, 3, 4};
int main(){
int i;
pid_t pid;
pid = fork();
if(pid == 0){
for(i=0 ; i<SIZE ; i++){
num[i] *= -i;
printf("CHILD: %d\n", num[i]);
}
}else if(pid > 0){
wait(NULL);
for(i=0 ; i<SIZE ; i++){
printf("PARENT: %d\n", num[i]);
}
}
return 0;
}
<file_sep>#include <stdio.h>
#include <unistd.h>
int value = 5;
int main(){
fork();
if(fork() && fork()){
fork();
}
printf("%d\n", getpid());
return 0;
}
/*
Other examples:
fork();
if(fork()){
fork();
}
fork();
if(fork() && fork()){
fork();
}
*/
| e67f25e5f81789a73c3ea9da83428706d2d6d46d | [
"Markdown",
"C"
] | 6 | C | AhmedAbdelbasit/Operating-Systems | b4f23f428f2ab5935f532b78636dcfe8ec6c7c52 | d1cc3e18f773a6bd67368b541474dd0174e64b69 |
refs/heads/master | <repo_name>huanglong-zz/wechat-oceanify<file_sep>/app/lib/cloudinary.js
'use strict'
const cloudinary = require('cloudinary')
const Promise = require('bluebird')
exports.uploadAsync = function(image, folder) {
return new Promise(function(resolve, reject) {
cloudinary.uploader.upload(image, function(result) {
resolve(result.public_id)
}, {
folder: folder
})
})
}
<file_sep>/config/env/all.js
'use strict'
// https://jslinterrors.com/option-jshint-camelcase
var path = require('path')
var rootPath = path.join(__dirname, '/../..')
module.exports = {
root: rootPath,
//port: process.env.PORT || 8000,
port: 8000,
name: 'CR',
hostname: 'www.campusroom.com'
}
<file_sep>/Readme.md
# Wechat Example For Oceanify
## Spin up server
```bash
$ npm i
$ npm start
```
<file_sep>/components/main.js
'use strict'
/*
* Test cases
*/
var homeInit = require('pages/homepage/main')
var Chart = require('chart.js')
homeInit()
console.log(Chart)
var $ = window.Zepto
console.log($('.category'))
// require.async('yen', function(yen) {
// // amd style
// console.log(yen.replaceClass)
// })
// test map
var t = require('templates/1')
console.log(t)
<file_sep>/app/controllers/app.js
'use strict'
const render = require('../lib/render')
exports.homePage = function *(next) {
this.body = yield render('index', {
page: 'index'
})
}
<file_sep>/components/pages/homepage/main.js
'use strict'
var flatpickr = require('flatpickr')
var Cleave = require('cleave.js')
// flatpickr works fine, while addon modules failed
require('cleave.js/src/addons/phone-type-formatter.cn')
function init() {
flatpickr('#flatpickr-tryme')
new Cleave('.input-phone', {
phone: true,
phoneRegionCode: 'CN'
})
}
module.exports = init
<file_sep>/app/lib/render.js
'use strict'
const views = require('co-views')
const path = require('path')
const moment = require('moment')
const _package = require('../../package.json')
const config = require('../../config/config')
const dir = path.join(__dirname, '../', 'views')
// http://paularmstrong.github.io/node-templates/benchmarks.html
// swig is faster overall
// const filters = {
// formatVersion: function(version) {
// return '@v' + version
// }
// }
// app.context.render = render({
// root: path.join(__dirname, '../', 'views'),
// ext: 'html',
// locals: locals,
// filters: filters
// })
module.exports = views(dir, {
cache: true,
map: {
html: 'swig',
md: 'hogan'
},
locals: {
moment: moment,
version: _package.version,
online: config.online
}
})
| 26f1f83afb30afffe11f6b29c8039474f971a106 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | huanglong-zz/wechat-oceanify | db08c7c256b895092ecdd2f4526ddbe6a67a04a1 | 119cd9845c0e423aeac6c71e1d909829dc698c7a |
refs/heads/master | <file_sep>package com.openbravo.pos.pda.struts.actions;
import com.openbravo.pos.pda.bo.RestaurantManager;
import com.openbravo.pos.pda.struts.forms.FloorForm;
import com.openbravo.pos.ticket.ProductInfo;
import com.openbravo.pos.ticket.ProductInfoExt;
import com.openbravo.pos.ticket.TicketInfo;
import com.openbravo.pos.ticket.TicketLineInfo;
import com.openbravo.pos.ticket.UserInfo;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
/**
*
* @author jaroslawwozniak
*/
public class PlaceAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
private final static String EDITING = "editing";
private final static String UPDATE = "update";
/**
* This is the action called from the Struts framework.
*
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// buscando a conexão do request
Connection connection = (Connection) request
.getAttribute("connection");
FloorForm floorForm = (FloorForm) form;
RestaurantManager manager = new RestaurantManager(connection);
String floorId = (String) floorForm.getFloorId();
String place = (String) floorForm.getId();
String str = (String) floorForm.getMode();
String[] array = null;
int mode = 0;
if (!str.equals("")) {
mode = Integer.valueOf(str);
}
List<TicketLineInfo> linesList = new ArrayList<TicketLineInfo>();
List products = new ArrayList<ProductInfoExt>();
TicketInfo ticket;
ProductInfo productInfo;
switch (mode) {
//removes products
case 1:
ticket = manager.findTicket(place);
linesList = ticket.getM_aLines();
array = floorForm.getParameters();
if (array != null) {
for (int i = 0; i < array.length; i++) {
int temp = Integer.valueOf(array[i]);
if (linesList.get(temp).getMultiply() > 1) {
linesList.get(temp).setMultiply(linesList.get(temp).getMultiply() - 1);
productInfo = manager.findProductById(ticket.getLines().get(temp).getProductid());
if (!productInfo.isCom() && productInfo.isSpecial()) {
for (int j = temp + 1; j < linesList.size(); j++) {
if (manager.findProductById(linesList.get(j).getProductid()).isCom()) {
if(linesList.get(j).getMultiply() <= 1){
linesList.remove(j);
j--;
} else {
linesList.get(j).setMultiply(linesList.get(j).getMultiply() - 1); //strange
}
}
}
}
}
}
}
manager.updateLineFromTicket(place, ticket);
for (Object line : linesList) {
TicketLineInfo li = (TicketLineInfo) line;
products.add(manager.findProductById(li.getProductid()));
}
request.setAttribute("floorName", manager.findFloorById(manager.findPlaceById(place).getFloor()).getName());
request.setAttribute("place", place);
request.setAttribute("placeName", manager.findPlaceNameById(place));
request.setAttribute("floorId", floorId);
request.setAttribute("lines", linesList);
request.setAttribute("products", products);
request.setAttribute("total", manager.getTotalOfaTicket(place));
return mapping.findForward(SUCCESS);
case 4:
ticket = manager.findTicket(place);
linesList = ticket.getM_aLines();
array = floorForm.getParameters();
int var = Integer.parseInt(array[0]);
productInfo = manager.findProductById(linesList.get(var).getProductid());
linesList.remove(var);
if (!productInfo.isCom()) {
if (linesList.size() > var && manager.findProductById(linesList.get(var).getProductid()).isCom()) {
linesList.remove(var);
while (linesList.size() > var && manager.findProductById(linesList.get(var).getProductid()).isCom()) {
linesList.remove(var);
if (linesList.size() == var) {
break;
}
}
}
}
manager.updateLineFromTicket(place, ticket);
for (Object line : linesList) {
TicketLineInfo li = (TicketLineInfo) line;
products.add(manager.findProductById(li.getProductid()));
}
request.setAttribute("floorName", manager.findFloorById(manager.findPlaceById(place).getFloor()).getName());
request.setAttribute("place", place);
request.setAttribute("placeName", manager.findPlaceNameById(place));
request.setAttribute("floorId", floorId);
request.setAttribute("lines", linesList);
request.setAttribute("products", products);
request.setAttribute("total", manager.getTotalOfaTicket(place));
return mapping.findForward(SUCCESS);
//edits lines
case 2:
ticket = manager.findTicket(place);
linesList = ticket.getM_aLines();
String[] index = floorForm.getParameters();
//if null go to default and refresh products. that's why no break
int temp = Integer.valueOf(index[0]);
Double multiply = Double.valueOf(index[1]);
linesList.get(temp).setMultiply(multiply);
productInfo = manager.findProductById(ticket.getLines().get(temp).getProductid());
if (!productInfo.isCom() && productInfo.isSpecial()) {
for (int j = temp + 1; j < linesList.size(); j++) {
if (manager.findProductById(linesList.get(j).getProductid()).isCom()) {
linesList.get(j).setMultiply(multiply); //strange
}
}
}
manager.updateLineFromTicket(floorForm.getId(), ticket);
for (Object line : linesList) {
TicketLineInfo li = (TicketLineInfo) line;
products.add(manager.findProductById(li.getProductid()));
}
break;
//increment product
case 3:
ticket = manager.findTicket(place);
linesList = ticket.getM_aLines();
array = floorForm.getParameters();
if (array != null) {
for (int i = 0; i < array.length; i++) {
temp = Integer.valueOf(array[i]);
linesList.get(temp).setMultiply(linesList.get(temp).getMultiply() + 1); //strange
productInfo = manager.findProductById(ticket.getLines().get(Integer.valueOf(array[i])).getProductid());
if (!productInfo.isCom() && productInfo.isSpecial()) {
for (int j = temp + 1; j < linesList.size(); j++) {
if (manager.findProductById(linesList.get(j).getProductid()).isCom()) {
linesList.get(j).setMultiply(linesList.get(j).getMultiply() + 1); //strange
}
}
}
}
}
manager.updateLineFromTicket(place, ticket);
for (Object line : linesList) {
TicketLineInfo li = (TicketLineInfo) line;
products.add(manager.findProductById(li.getProductid()));
}
request.setAttribute("floorName", manager.findFloorById(manager.findPlaceById(place).getFloor()).getName());
request.setAttribute("place", place);
request.setAttribute("placeName", manager.findPlaceNameById(place));
request.setAttribute("floorId", floorId);
request.setAttribute("lines", linesList);
request.setAttribute("products", products);
request.setAttribute("total", manager.getTotalOfaTicket(place));
return mapping.findForward(SUCCESS);
case 5:
ticket = manager.findTicket(place);
ticket.setM_User((UserInfo) request.getSession().getAttribute("user"));
manager.updateLineFromTicket(place, ticket);
Runtime.getRuntime().exec("java -cp c:\\java\\dist\\Openbravo-POS.jar com.openbravo.teste.ImprimiCupons " + place + " " + floorForm.getPrint());
Thread.sleep(5000);
ticket = manager.findTicket(place);
linesList = ticket.getM_aLines();
for (Object line : linesList) {
TicketLineInfo li = (TicketLineInfo) line;
products.add(manager.findProductById(li.getProductid()));
}
request.setAttribute("floorName", manager.findFloorById(manager.findPlaceById(place).getFloor()).getName());
request.setAttribute("place", place);
request.setAttribute("placeName", manager.findPlaceNameById(place));
request.setAttribute("floorId", floorId);
request.setAttribute("lines", linesList);
request.setAttribute("products", products);
request.setAttribute("total", manager.getTotalOfaTicket(place));
return mapping.findForward(SUCCESS);
case 6:
ticket = manager.findTicket(place);
linesList = ticket.getM_aLines();
array = floorForm.getParameters();
temp = Integer.valueOf(array[0]);
linesList.get(temp).setProductAttSetInstDesc(floorForm.getObs());
manager.updateLineFromTicket(place, ticket);
for (Object line : linesList) {
TicketLineInfo li = (TicketLineInfo) line;
products.add(manager.findProductById(li.getProductid()));
}
request.setAttribute("floorName", manager.findFloorById(manager.findPlaceById(place).getFloor()).getName());
request.setAttribute("place", place);
request.setAttribute("placeName", manager.findPlaceNameById(place));
request.setAttribute("floorId", floorId);
request.setAttribute("lines", linesList);
request.setAttribute("products", products);
request.setAttribute("total", manager.getTotalOfaTicket(place));
return mapping.findForward(SUCCESS);
//adds new products or just refresh
default:
if (manager.findTicket(place) == null) {
manager.initTicket(place);
} else {
linesList = manager.findTicketLines(place);
}
for (Object line : linesList) {
TicketLineInfo li = (TicketLineInfo) line;
if(floorForm.getParameters() != null){
if("consulta".endsWith(floorForm.getParameters()[0]))
li.setPrint(false);
}
products.add(manager.findProductById(li.getProductid()));
}
break;
}
request.setAttribute("floorName", manager.findFloorById(manager.findPlaceById(place).getFloor()).getName());
request.setAttribute("place", place);
request.setAttribute("placeName", manager.findPlaceNameById(place));
request.setAttribute("floorId", floorId);
request.setAttribute("lines", linesList);
request.setAttribute("products", products);
request.setAttribute("total", manager.getTotalOfaTicket(place));
return mapping.findForward(SUCCESS);
}
}
<file_sep>package com.openbravo.pos.pda.struts.actions;
import com.openbravo.pos.pda.bo.RestaurantManager;
import com.openbravo.pos.pda.struts.forms.AddedProductForm;
import com.openbravo.pos.ticket.ProductInfo;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
public class addProductAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// buscando a conexão do request
Connection connection = (Connection) request
.getAttribute("connection");
AddedProductForm aForm = (AddedProductForm) form;
RestaurantManager bo = new RestaurantManager(connection);
String place = aForm.getPlace();
String productId = aForm.getProductId();
bo.addLineToTicket(place, productId);
List<ProductInfo> auxiliars = new ArrayList<ProductInfo>();
auxiliars = bo.findAuxiliars(productId);
if(bo.findProductById(productId).isSpecial()){
while(!auxiliars.isEmpty()){
bo.addLineToTicket(place, auxiliars.get(0).getId());
auxiliars.remove(0);
}
}
request.setAttribute("place", place);
request.setAttribute("auxiliars", auxiliars);
request.setAttribute("rates", bo.findAllTaxRatesByCategory(auxiliars));
return mapping.findForward(SUCCESS);
}
}
<file_sep>errors.loginfailed=Login/Senha incorreto.
errors.nologon=Voc\u00ea deve fazer login antes.
welcome.title=Shinjiru POS PDA
message.login=Login
message.password=Senha
button.login=Login
editproduct=Editar Produtos
item=Item
price=Pre\u00e7o
units=Unidades
value=Valor
receipt=Recibo
modify=Modificar
floors=Sal\u00e3o
tables=Mesas
edit=Produtos
add=Add
delete=Delete
addProducts=Adicionando Produtos
message.welcome=Efetue o login | 19f79646f2840aa987c1a6df9f6dfb9cfaa8c609 | [
"Java",
"INI"
] | 3 | Java | osmarhes/openbravo | af47f8edf05e9e785297f69eaaecc39550978459 | 030c08a6c7a10d7db06a217cc486a4d9f090638f |
refs/heads/main | <repo_name>Beowulf1220/Biblioteca_Oracle_JS<file_sep>/README.md
# Biblioteca_Oracle_JS
Proyecto final de Fundamentos de bases de datos
<file_sep>/Biblioteca.sql
--------------------------------------------------------
-- DDL for Table BIBLIOTECA
--------------------------------------------------------
CREATE TABLE "HR"."BIBLIOTECA"
( "BIBLIOTECA_ID" NUMBER(*,0),
"BIBLIOTECA_NOMBRE" VARCHAR2(30 BYTE),
"DIRECCION_ID" NUMBER(*,0)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "SYSAUX" ;
<file_sep>/app.js
/*
// This is for Oracle data base:
npm install oracledb
// This commands allow us make a http very easy:
npm i express
// This is for templates:
npm i ejs
// This is for read POST:
npm install body-parser
// These commands update the app.js after every modify:
npm install -g nodemon
nodemon app.js
*/
const express = require('express'); // import module
const bodyParser = require('body-parser');
const oracledb = require('oracledb');
const app = express();
app.use(express.static(__dirname + "/public")); // path
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json())
const port = 3000;
// templates engine
app.set("view engine", "ejs");
app.set("views", __dirname + "/views");
app.get('/', (req, res) => {
res.send('Mi respuesta');
});
app.listen(port, () => {
console.log("Servidor a su servicio", port);
});
const dbConfig = {
user: "hr",
password: "hr",
connectString: "localhost/xepdb1",
};
// data base conection
/*var oracledb = require('oracledb');
oracledb.getConnection(dbConfig,
function (err, connection) {
if (err) {
console.error(err.message);
return;
}
console.log('Connection was successful!');
connection.close(
function (err) {
if (err) {
console.error(err.message);
return;
}
}
);
}
);*/
oracledb.autoCommit = true;
// Query function
async function query(req, res) {
try {
connection = await oracledb.getConnection({
user: "hr",
password: "hr",
connectString: "localhost:1521/xepdb1"
});
console.log('connected to database');
result = await connection.execute(req);
//console.log(result);
} catch (err) {
//show error message
console.log(err.message);
} finally {
if (connection) {
try {
// Always close connections
await connection.close();
console.log('close connection success');
} catch (err) {
console.error(err.message);
}
}
return result;//res.send(result.rows);
}
}
// Get /employee?id=<id employee>
app.get('/employee', function (req, res) {
//get query param ?id
let id = req.query.id;
// id param if it is number
if (isNaN(id)) {
res.send('Query param id is not number');
return;
}
query(req, res, id);
}
);
// Get /employess
app.get('/employees', function (req, res) {
query("SELECT * FROM employees", res);
}
);
// Get general query
app.get('/query', function (req, res) {
query(req, res);
});
// This is for login
app.post("/index", urlencodedParser, async (req, res) => {
const profile = await query(`SELECT * FROM usuario WHERE matricula = ${req.body.user} AND contrasena = ${req.body.contrasena}`, res); // Query
//console.log(x.rows.length == 1);
if (profile.rows.length == 1) { // verify user
const no_students = await query(`SELECT * FROM alumno`, res);
const no_books = await query(`SELECT * FROM libros`, res);
const no_prestamos = await query(`SELECT * FROM prestamo`, res);
const no_categorias = await query(`SELECT * FROM categoria`, res);
const no_docentes = await query(`SELECT * FROM docente`, res);
const no_admin = await query(`SELECT * FROM administrador`, res);
res.render("home", {
profile: profile.rows,
title: "Inicio",
no_students: no_students.rows,
no_books: no_books.rows,
no_prestamos: no_prestamos.rows,
no_categorias: no_categorias.rows,
no_docentes: no_docentes.rows,
no_admin: no_admin.rows,
});
} else {
// ...
}
});
///////////////////////////////////////////////////////////////////////////
// Page advancesettings
app.use('/admin', (req, res) => {
res.render("admin", { title: "Administradores" });
});
// Page advancesettings
app.use('/adminAdd', async (req, res) => {
await oracledb.getConnection(dbConfig).then(async (conn) => {
await conn.execute("INSERT INTO administrador VALUES (:0, :1)",
[req.body.matricula, req.body.rol], { autoCommit: true });
});
res.render("listadmin", { title: "Administradores" });
});
// Page advancesettings
app.use('/advancesettings', (req, res) => {
res.render("advancesettings", { title: "Configuraciones avanzadas" });
});
// Page book
app.use('/book', async (req, res) => {
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM categoria');
});
res.render("book", { title: "Registrar Libro", tabla : result.rows });
});
// Page book save
app.use('/saveBook', async (req, res) => {
console.log(req.body);
await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO libros VALUES (:0, :1)",
[req.body.isbn, req.body.titulo], { autoCommit: true });
});
await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO libros_por_categoria VALUES (:0, :1)",
[req.body.isbn, req.body.categoria], { autoCommit: true });
});
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM libros');
});
res.render("catalog", { title: "Libros", tabla: result.rows });
});
// Page catalog
app.use('/catalog', async (req, res) => {
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM libros');
});
res.render("catalog", { title: "Catálogo", tabla: result.rows });
});
// Page category
app.use('/category', (req, res) => {
res.render("category", { title: "Categorías" });
});
// Register category
app.post('/saveCategory', urlencodedParser, async (req, res) => {
// category
await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO categoria VALUES (:0, :1)",
[req.body.code, req.body.name], { autoCommit: true });
});
let result;
let queryy = await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM categoria');
});
res.render("listcategory", { title: "Categorías", tabla: result });
});
// Page home
app.use('/home', async (req, res) => {
const no_students = await query(`SELECT * FROM alumno`, res);
const no_books = await query(`SELECT * FROM libros`, res);
const no_prestamos = await query(`SELECT * FROM prestamo`, res);
const no_categorias = await query(`SELECT * FROM categoria`, res);
const no_docentes = await query(`SELECT * FROM docente`, res);
const no_admin = await query(`SELECT * FROM administrador`, res);
res.render("home", {
title: "Inicio",
no_students: no_students.rows,
no_books: no_books.rows,
no_prestamos: no_prestamos.rows,
no_categorias: no_categorias.rows,
no_docentes: no_docentes.rows,
no_admin: no_admin.rows,
});
});
// Page index
app.use('/index', (req, res) => {
res.render("index", { title: "Inicio de sesión" });
});
// Page listpersonal
app.use('/institution', (req, res) => {
res.render("institution", { title: "Institución" });
});
// Page listadmin
app.use('/listadmin', async (req, res) => {
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM Administrador join usuario on usuario.matricula = administrador.matricula');
});
res.render("listadmin", { title: "Administradores", tabla: result.rows });
});
// Page listcategory
app.use('/listcategory', async (req, res) => {
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM categoria');
});
res.render("listcategory", { title: "Categorías", tabla: result.rows });
});
// Page listpersonal
app.use('/listpersonal', (req, res) => {
res.render("listpersonal", { title: "Personal administrativo" });
});
// Page listprovider
app.use('/listprovider', (req, res) => {
res.render("listprovider", { title: "Proveedores" });
});
// Page listsection
app.use('/listsection', (req, res) => {
res.render("listsection", { title: "Secciones" });
});
// Page liststudent
app.use('/liststudent', async (req, res) => {
let result;
let query = await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM usuario join alumno on usuario.matricula = alumno.matricula join direcciones on direcciones.direccion_id = usuario.direccion_id');
});
//console.log(result);
res.render("liststudent", { title: "Estudiantes", tabla: result.rows });
});
app.post('/astudent', urlencodedParser, async (req, res) => {
const x = await query(`SELECT * FROM usuario join alumno on usuario.matricula = alumno.matricula join direcciones on direcciones.direccion_id = usuario.direccion_id WHERE alumno.matricula = ${req.body.user}`, res); // Query
console.log(x.rows);
if (x.rows.length == 1) { // verify user
res.render("astudent", { title: "student", tabla: x.rows });
}
});
// Page liststteacher
app.use('/listteacher', async (req, res) => {
let result;
let query = await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM usuario join docente on usuario.matricula = docente.matricula join direcciones on direcciones.direccion_id = usuario.direccion_id');
});
//console.log(result);
res.render("listteacher", { title: "Docentes", tabla: result.rows });
});
// Register teacher
app.post('/listteacher', urlencodedParser, async (req, res) => {
console.log(req.body);
let dir_id = Math.floor(Math.random() * 100000);
let fecha = new Date(req.body.fecha);
let fech = fecha.getDate() + "-" + fecha.getMonth() + "-" + fecha.getFullYear();
// direction
await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO direcciones VALUES (:0, :1, :2, :3)",
[dir_id, req.body.calle, req.body.numero, req.body.cp], { autoCommit: true });
});
// user
await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO usuario VALUES (:0, :1, :2, :3, :4, :5, :6)",
[req.body.matricula, req.body.contrasena, dir_id, req.body.nombre, req.body.apellido,
fech, req.body.telefono], { autoCommit: true });
});
// teacher
await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO docente VALUES (:0, :1)",
[req.body.matricula, req.body.materia], { autoCommit: true });
});
let result;
let queryy = await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM usuario join docente on usuario.matricula = docente.matricula join direcciones on direcciones.direccion_id = usuario.direccion_id');
});
res.render("listteacher", { title: "Docentes", tabla: result });
});
// Page loan
app.use('/loan', async (req, res) => {
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM prestamo join usuario on usuario.matricula = prestamo.matricula join libros on libros.isbn = prestamo.isbn');
});
console.log(result);
res.render("loan", { title: "Prestamos", tabla: result.rows });
});
app.use('/loanDelete', async (req, res) => {
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM prestamo join usuario on usuario.matricula = prestamo.matricula join libros on libros.isbn = prestamo.isbn');
});
console.log(result);
res.render("loan", { title: "Prestamos", tabla: result.rows });
});
// Page loannew
app.use('/loannewAdd', async (req, res) => {
await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO prestamo VALUES (:0, :1, :2)",
[Math.floor(Math.random() * 100000), req.body.matricula, req.body.isbn], { autoCommit: true });
});
let result;
await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM prestamo join usuario on usuario.matricula = prestamo.matricula join libros on libros.isbn = prestamo.isbn');
});
res.render("loan", { title: "Prestamos", tabla: result.rows });
});
// Page loanreservation
app.use('/loannew', (req, res) => {
res.render("loannew", { title: "Prestamo" });
});
// Page personal
app.use('/personal', (req, res) => {
res.render("personal", { title: "Personal administrativo" });
});
// Page provider
app.use('/provider', (req, res) => {
res.render("provider", { title: "Provedorees" });
});
// Page report
app.use('/report', (req, res) => {
res.render("report", { title: "Reportes" });
});
// Page searchBook
app.use('/searchBook', (req, res) => {
res.render("searchBook", { title: "Buscar libro" });
});
// Page students
app.use('/student', (req, res) => {
res.render("student", { title: "Estudiantes" });
});
// Register student
app.post('/liststudent', urlencodedParser, async (req, res) => {
let dir_id = Math.floor(Math.random() * 100000);
let fecha = new Date(req.body.fecha);
let fech = fecha.getDate() + "-" + fecha.getMonth() + "-" + fecha.getFullYear();
// direction
let query = await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO direcciones VALUES (:0, :1, :2, :3)",
[dir_id, req.body.calle, req.body.numero, req.body.cp], { autoCommit: true });
});
// user
let mer = await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO usuario VALUES (:0, :1, :2, :3, :4, :5, :6)",
[req.body.matricula, req.body.contrasena, dir_id, req.body.nombre, req.body.apellido,
fech, req.body.telefono], { autoCommit: true });
});
// Alumno
let merd = await oracledb.getConnection(dbConfig).then(async (conn) => {
const r = await conn.execute("INSERT INTO alumno VALUES (:0, :1)",
[req.body.matricula, req.body.carrera], { autoCommit: true });
});
//const c = await query(`INSERT INTO Alumno VALUES( ${req.body.matricula}, ${req.body.carrera} );`, res); // Register student
let result;
let queryy = await oracledb.getConnection(dbConfig).then(async (conn) => {
result = await conn.execute('SELECT * FROM usuario join alumno on usuario.matricula = alumno.matricula join direcciones on direcciones.direccion_id = usuario.direccion_id');
});
res.render("liststudent", { title: "Estudiantes", tabla: result });
});
// Page teachers
app.use('/teacher', (req, res) => {
res.render("teacher", { title: "Profesores" });
});
// Page 404 (Error: page not found)
app.use((req, res, next) => {
res.status(404).render("404", { title: "Error" });
}); | 9f84ce957a1d25ec96013ee7f8a13df177bb817f | [
"Markdown",
"SQL",
"JavaScript"
] | 3 | Markdown | Beowulf1220/Biblioteca_Oracle_JS | 313eca369e386911cf6842ce5b46215c674b2467 | 288d4068b351ee4cb1b90f6a3de899214d6b7c9d |
refs/heads/master | <repo_name>shaon3343/myAllPhpWorks<file_sep>/phpProgs/get_cities.php
<?php
switch($_REQUEST['country']){
case 'ie': // { ireland
$cities=array(
'Cork', 'Dublin', 'Galway', 'Limerick',
'Waterford'
);
break;
// }
case 'uk': // { United Kingdom
$cities=array(
'Bath', 'Birmingham', 'Bradford',
'Brighton & Hove', 'Bristol',
'Cambridge', 'Canterbury', 'Carlisle',
'Chester', 'Chichester', 'Coventry',
'Derby', 'Durham', 'Ely', 'Exeter',
'Gloucester', 'Hereford', 'Kingston upon Hull',
/* and on and on! */
'Newport', 'St David\'s', 'Swansea'
);
break;
// }
default: // { else
$cities=false;
// }
}
if(!$cities)echo 'please choose a country first';
else echo '<select name="city"><option>',
join('</option><option>',$cities),
'</select>';
?>
<file_sep>/database_prog/database_insert.php
<html>
<head><title>inserting data to database</title></head>
<body>
<?php
$name=trim($_POST['name']);
$marks=trim($_POST['marks']);
$id=trim($_POST['id']);
if(!$name || !$marks || !$id)
{
echo "please enter all required field";
exit;
}
@ $connect = new mysqli('localhost','ashfak.shaon','shaonna','mysql');
if(mysqli_connect_errno())
{
echo "connecting to the database failed please try again";
exit;
}
$query="insert into info_student values('".$name."','".$id."','".$marks."')";
$result=$connect->query($query);
if($result)
{
echo " <br> $connected->affected_rows names inserted into database </br>";
}
else
echo "<br> An error has occured the entries was not added </br>";
$connect->close();
?>
</body>
</html>
<file_sep>/testingtushar/nbproject/private/private.properties
index.file=index.php
url=http://localhost/testingtushar/
<file_sep>/phpProgs/loadGoods.php
<html>
<head>
<title>load Goods</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.21" />
</head>
<body>
<?php
$connect=new mysqli('localhost','root','rootroot','shaonTest');
$connect->query("set character_set_results='utf8'");
if(mysqli_connect_errno())
{
echo "cannot connect to the database";
exit;
}
$query = "select * from Warehouse";
$result=$connect->query($query);
$no_rows= $result->num_rows;
echo"<form method=\"post\" action=\"ComputeExpense.php\" target=\"_parent\"> \n";
echo "<h2> পন্য নির্বাচন করুনঃ </h2>\n
<select name=\"GoodsName\" onchange=\" echo \"printTable()\";\" xml:lang=\"en\" > \n
<option value=\" \"> \"------পন্য নির্বাচন করুন ----\" </option>";
//this.form.submit();
for ($i=0; $i <$no_rows ; $i++)
{
$row = $result->fetch_assoc();
echo "<option value="; echo $row[GoodsName]; echo ">"; echo $row[GoodsName]; echo "</option>";
echo "<br>";
// echo $row['GoodsName'];
}
echo "</select> \n
</form>";
function printTable(){
echo "shaon";
}
$result->free();
$connect->close();
?>
</body>
</html>
<file_sep>/issue/nbproject/private/private.properties
index.file=index.php
url=http://localhost/issue/
<file_sep>/phpProgs/FooterPrint.php
<?php
class FooterPrint{
public function printFooter(){
echo "</body> \n
</html>\n";
}
}
?>
<file_sep>/PHP/myfirst1.php
<html>
<head>
<title> my_first_php</title>
</head>
<body>
this is my first PHP program , and today is :
<?php
$todaysdate=date("d",time())."-".date("m",time())."-".date("Y",time());
echo $todaysdate;
$todaysdate=" the time is :";
echo $todaysdate;
$todaysdate=date("h:i:s");
echo $todaysdate;
?>
</body>
</html>
<file_sep>/phpProgs/Listbox.html
<html>
<head>
<title>untitled</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.21" />
</head>
<body>
<form method="POST" action="listbox.php">
<h2> What price of things are your choice:</h2>
<br>
<br>
<select name="price">
<option> Under 10000$ </option>
<option> Under 20000$ </option>
<option> Under 5000$ </option>
</select>
<br>
<br>
<h2> What size of other things you consider:</h2>
<select name="Engine[]" multiple>
<option>1.0L</option>
<option>2.0L</option>
<option>3.0L</option>
</select>
<br>
<br>
<input type ="submit" value="submit">
</form>
</body>
</html>
<file_sep>/phpProgs/test.php
<?php
$dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
. ' target="_blank" class="browse_foreign" '
.'>' . __('Browse foreign values') . '</a>';
echo $dropdown;
?>
<file_sep>/phpProgs/Demo.php
<?php
/*
* OOP1.php
*
* Copyright 2012 shaon <<EMAIL>>
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program 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.
*
*
*
*/
class Demo{
private $_name;
public function sayHello(){
print "Hello "; print $this->getName();print "!!";
}
public function getName(){
return $this->_name;
}
public function setName($name)
{
$this->_name=$name;
}
}
?>
<html>
<head>
<title>OOP1</title>
</head>
<body>
</body>
</html>
<file_sep>/Product_entry/index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$pid=trim($_POST['pid']);
$type=trim($_POST['type']);
$desc=trim($_POST['description']);
if(!$pid || !$type || !$desc)
{
echo "please enter all required field";
exit;
}
@ $connect = new mysqli('localhost','ashfak.shaon','shaonna','product_list');
if(mysqli_connect_errno())
{
echo "connecting to the database failed please try again";
exit;
}
$query="insert into prodct values('".$pid."','".$type."','".$d."')";
$result=$connect->query($query);
if($result)
{
echo " <br> $connected->affected_rows names inserted into database </br>";
}
else
echo "<br> An error has occured the entries was not added </br>";
$connect->close();
?>
</body>
</html>
<file_sep>/phpProgs/DBtest.php
<?php
require_once('HeaderPrint.php');
require_once('FooterPrint.php');
$hp = new HeaderPrint();
$hp->print_header();
header('Content-type: text/html; charset=UTF-8');
$connect = new mysqli('localhost','root','rootroot','shaonTest');
if(mysqli_connect_errno())
{
echo "Cannot connect to Database";
exit;
}
$connect->query("set character_set_results='utf8'");
// mysql_query ("set character_set_results='utf8'");
$query="select * from BengaliTel";
$noRows=0;
$result=$connect->query($query);
/* mysql_query ("set character_set_results='utf8'");
$sql=mysql_query("select * from BengaliTel");
$noRow=mysql_fetch_array($sql);
*/
$noRows = $result->num_rows;
echo "Total number of phone number:";
echo $noRows;
echo "<br>";
for ($i=0; $i <$noRows ; $i++)
{
$j=$i+1;
$row = $result->fetch_assoc();
// echo "<br> ($i+1) Name: </br>";
echo "<br>$j</br>";
// echo htmlspecialchars(stripslashes($row['name']));
echo $row['name'];
echo " <br>";
echo $row['telephone'];
echo " <br>";
echo $row['Address'];
// echo "<strong><br> id: </br> </strong>";
// echo stripslashes($row['id']);
echo " <br>......</br>";
}
$result->free();
$connect->close();
$fp = new FooterPrint();
$fp->printFooter();
?>
<file_sep>/new/text.php
<html>
<head><title>my_second</title></head>
<body>
Great Scott!!! You are
<?php
echo $_GET['author'];
echo " and now the time is: " ;
$current_time=date(" h:i:s ");
echo $current_time;
echo " today is: ";
$todaysdate=date("d",time())."-".date("m",time())."-".date("Y",time());
echo $todaysdate;
echo "......php.....";
print_r (phpinfo());
?>
</body>
</html>
<file_sep>/phpProgs/OOPtest.php
<?php
require_once('Demo.php');
echo"<br>";
$objDemo = new Demo();
$objDemo->setName('Shaon');
$objDemo->sayHello();
// echo $objDemo->getName();
?>
<file_sep>/PHP/connecting_db.php
<head><title>connect to database</title>
<body>
<?php
$i=10;
$m="shaon";
@ $connect=new mysqli("localhost","ashfak.shaon","shaonna","mysql");
if(!mysqli_connect_errno())
{
echo "congrats !!! connected to localhost as ashfak.shaon";
echo "<br>ha ha ha ha...........</br>";
echo "<br>.......... ha ha ha ha</br>";
echo "<br> $i </br>";
echo $m;
}
else echo "connection failed";
?>
</body>
</head>
<file_sep>/phpProgs/showExpense.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/xml"; charset="utf-8" />
<link rel = "stylesheet" type = "text/css" href = "/phpProgs/jquery-ui-1.8.13.custom.css" />
<script type = "text/javascript" src = "/phpProgs/jquery.min.js"></script>
<script type = "text/javascript" src = "/phpProgs/jquery-ui-1.8.13.custom.min.js"></script>
<script type = "text/javascript">
//<![CDATA[
$(init);
function init(){
$("h1").addClass("ui-widget-header");
$("#datePicker").datepicker();
$("#datePicker1").datepicker();
}
//]]>
</script>
<title> বাজারের হিসাব নিকাশ </title>
</head>
<body>
<h1> মোট খরচের হিসাবঃ </h1>
<h2> কোন তারিখ থেকে কত তারিখ পর্যন্ত হিসাব দেখতে চানঃ </h2>
<?php
/* require_once('FooterPrint.php');
$hp = new HeaderPrint();
$hp->print_header(); */
header('Content-type: text/html; charset=utf8');
// $name=trim($_POST['GoodsName']);
// echo $name;
echo "<form action=\"show.php\" method=\"POST\"> \n
<table name =\"expenseTbl\" border=\”0\”> \n
<tr> \n
<td align=\”center\”><input type=\”text\” id = \"datePicker\" name=\"date1\" size=\"5\" value = \"তারিখ\"/></td>
<td align=\”center\”><input type=\”text\” id = \"datePicker1\" name=\"date2\" size=\"5\" value = \"তারিখ\"/></td>
</tr> \n
</table> \n
<input type = \"submit\" value = \"submit\" >
</form> \n";
?>
</body>
</html>
<file_sep>/phpProgs/PrintList.php
<?php
class PrintList{
public function printList(){
/* echo "<html>
<head>
<meta http-equiv=\"content-type\" content=\"text/xml\"; charset=\"utf-8\" />
<link rel = \"stylesheet\" type = \"text/css\" href = \"/phpProgs/jquery-ui-1.8.13.custom.css\" />
<script type = \"text/javascript\" src = \"/phpProgs/jquery.min.js\"></script>
<script type = \"text/javascript\" src = \"/phpProgs/jquery-ui-1.8.13.custom.min.js\"></script>
<script type = \"text/javascript\">
//<![CDATA[
\$(init);
function init(){
\$(\"h1\").addClass(\"ui-widget-header\");
\$(\"#tabs\").tabs();
\$(\"#datePicker\").datepicker();
\$(\"#slider\").slider()
.bind(\"slide\", reportSlider);
\$(\"#selectable\").selectable();
\$(\"#sortable\").sortable();
\$(\"#dialog\").dialog();
//initially close dialog
\$(\"#dialog\").dialog(\"close\");
}
//]]>
</script>
<title> বাজারের হিসাব নিকাশ </title>
</head>
<body>";
*/
header('Content-type: text/html; charset=utf8');
// $name=trim($_POST['GoodsName']);
// echo $name;
echo "
<table name =\"expenseTbl\" border=\”0\”> \n
<tr> \n
<td align=\”center\”><input type=\”text\” id = \"datePicker\" name=date size=\"5\"/></td>
<td align=\"center\"> <select name=\"GoodsName\" > <option value=\" \"> \"------পন্য নির্বাচন করুন ----\" </option>";
$connect=new mysqli('localhost','root','rootroot','shaonTest');
$connect->query("set character_set_results='utf8'");
if(mysqli_connect_errno())
{
echo "cannot connect to the database";
exit;
}
$query = "select * from Warehouse";
$result=$connect->query($query);
$no_rows= $result->num_rows;
for ($i=0; $i <$no_rows ; $i++)
{
$row = $result->fetch_assoc();
echo "<option value="; echo "\"".$row['GoodsName']."\""; echo ">"; echo "\"".$row['GoodsName']."\""; echo "</option>";
echo "<br>";
// echo $row['GoodsName'];
}
echo "</select> </td>
<td align=\”center\”><input type=\”text\” value=\"মূল্য\" name=price size=\"5\" /></td>
<td align=\”center\”><input type=\”text\” value=\"পরিমাণ\" name=qty size=\"5\" /></td>
</tr> \n
</table> \n
<input type = \"submit\" value = \"submit\" >";
$result->free();
$connect->close();
}
}
?>
<file_sep>/phpProgs/vara.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/xml"; charset="utf-8" />
<link rel = "stylesheet" type = "text/css" href = "/phpProgs/jquery-ui-1.8.13.custom.css" />
<script type = "text/javascript" src = "/phpProgs/jquery.min.js"></script>
<script type = "text/javascript" src = "/phpProgs/jquery-ui-1.8.13.custom.min.js"></script>
<script type = "text/javascript">
//<![CDATA[
$(init);
function init(){
$("h1").addClass("ui-widget-header");
$("#datePicker").datepicker();
}
//]]>
</script>
<title> গাড়ি ভাড়া হিসাবঃ </title>
</head>
<body>
<h1> গাড়ি ভাড়া হিসাবঃ </h1>
<?php
header('Content-type: text/html; charset=utf8');
echo "<form action=\"garivara.php\" method=\"POST\"> \n
<table name =\"expenseTbl\" border=\”0\”> \n
<tr> \n
<td align=\”center\”><input type=\”text\” id = \"datePicker\" name=date size=\"5\" value = \"তারিখ\"/></td>
<td align=\”center\”><input type=\”text\” value=\"গাড়ি ভাড়া \" name=price size=\"8\" /></td>
</tr> \n
</table> \n
<input type = \"submit\" value = \"submit\" >
</form> \n";
?>
</body>
</html>
<file_sep>/testingtushar/index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
if($_POST[bill_no])
{
echo "test before add to db <br>";
echo "fine!!! <br>";
$ret=add_db();
if(!$ret)
{
print "ERROR DB";
}
else
{
print "Thanks";
}
}
else
{
echo "fine!!! <br>";
echo "test before form creation<br>";
Bill_info();
}
function Bill_info()
{
$self=$_SERVER['PHP_SELF'];
echo <<<EOT
<form action="$self" method="POST">
Enter BILLNO here:<br />
<textarea name="bill_no" rows="1" cols="10" wrap>
</textarea><br />
Enter DATE here:<br />
<textarea name="bill_date" rows="1" cols="15" wrap>
</textarea><br />
Enter DESCRIPTION here:<br />
<textarea name="description" rows="1" cols="40" wrap>
</textarea><br />
Enter the RECEIPTDATE here:<br />
<textarea name="receipt_date" rows="1" cols="50" wrap>
</textarea><br />
<input type="submit" name="submit" value="SUBMIT">
</form>
EOT;
}
function add_db()
{
$bill_no=trim($_POST['bill_no']);
$bill_date=trim($_POST['bill_date']);
$description=trim($_POST['description']);
$receipt_date=trim($_POST['receipt_date']);
mysql_connect("localhost","root","shaonna") OR die("couldnt connect");
echo $bill_no;
echo"<br>";
echo "BOsssss I just started working $bill_no";
mysql_select_db("shaon");
$sql="INSERT INTO bills VALUES('$bill_no', '$bill_date', '$description', '$receipt_date')"; /*checked */
echo "BOsssss I just started working $bill_no";
echo"<br>";
mysql_query($sql);
$bill_no=$bill_no+1;
echo "BOsssss I just finished working $bill_no";
mysql_close();
return true;
}
?>
</body>
</html>
<file_sep>/phpProgs/ComputeExpense.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/xml"; charset="utf-8" />
<link rel = "stylesheet" type = "text/css" href = "/phpProgs/jquery-ui-1.8.13.custom.css" />
<script type = "text/javascript" src = "/phpProgs/jquery.min.js"></script>
<script type = "text/javascript" src = "/phpProgs/jquery-ui-1.8.13.custom.min.js"></script>
<script type = "text/javascript">
//<![CDATA[
$(init);
function init(){
$("h1").addClass("ui-widget-header");
$("#datePicker").datepicker();
}
//]]>
</script>
<title> বাজারের হিসাব নিকাশ </title>
</head>
<body>
<h1> বাজারের লিষ্টঃ </h1>
<?php
/* require_once('FooterPrint.php');
$hp = new HeaderPrint();
$hp->print_header(); */
header('Content-type: text/html; charset=utf8');
// $name=trim($_POST['GoodsName']);
// echo $name;
echo "<form action=\"InsertExpense.php\" method=\"POST\"> \n
<table name =\"expenseTbl\" border=\”0\”> \n
<tr> \n
<td align=\”center\”><input type=\”text\” id = \"datePicker\" name=date size=\"5\" value = \"তারিখ\"/></td>
<td align=\"center\"> <select name=\"GoodsName\"> <option value=\" \"> \"------পন্য নির্বাচন করুন ----\" </option>";
$connect=new mysqli('localhost','root','rootroot','shaonTest');
$connect->query("set character_set_results='utf8'");
if(mysqli_connect_errno())
{
echo "cannot connect to the database";
exit;
}
$query = "select * from Warehouse";
$result=$connect->query($query);
$no_rows= $result->num_rows;
for ($i=0; $i <$no_rows ; $i++)
{
$row = $result->fetch_assoc();
echo "<option value="; echo "\"".$row['GoodsName']."\""; echo ">"; echo "\"".$row['GoodsName']."\""; echo "</option>";
echo "<br>";
// echo $row['GoodsName'];
}
echo "</select> </td>
<td align=\”center\”><input type=\”text\” value=\"প্রতি ইউনিটের মূল্য\" name=price size=\"8\" /></td>
<td align=\”center\”><input type=\”text\” value=\"ক্রয়ের পরিমাণ\" name=qty size=\"8\" /></td>
</tr> \n
</table> \n
<input type = \"submit\" value = \"submit\" >
</form> \n";
$result->free();
$connect->close();
?>
</body>
</html>
<file_sep>/database_prog/connect_database_fetch.php
<html><head><title> connect and fetch</title>
</head>
<body>
<?php
$search_it= trim($_POST['marks']);
if(!$search_it)
{
echo " please enter a valid number to search";
exit;
}
$connect=new mysqli('localhost','ashfak.shaon','shaonna','mysql');
if(mysqli_connect_errno())
{
echo "cannot connect to the database";
exit;
}
$query = "select * from info_student where id like $search_it";
$result=$connect->query($query);
$no_rows= $result->num_rows;
echo "......Total student found. :-->";
echo $no_rows;
for ($i=0; $i <$no_rows ; $i++)
{
$j=$i+1;
$row = $result->fetch_assoc();
// echo "<br> ($i+1) Name: </br>";
echo "<br>$j</br>";
// echo htmlspecialchars(stripslashes($row['name']));
echo $row['name'];
// echo "<strong><br> id: </br> </strong>";
// echo stripslashes($row['id']);
echo " <br>......</br>";
}
$result->free();
$connect->close();
?>
</body>
</html>
<file_sep>/PHP/fnc_chr.php
<?php
$ascii_chr_ret_ln=chr(111);
$ascii_chr_ret_cr=chr(13);
echo "the character corresponding to enter is "." ".$ascii_chr_ret_ln."<br>";
?>
<file_sep>/phpProgs/InsertInWarehouse.php
<?php
require_once('HeaderPrint.php');
require_once('FooterPrint.php');
$hp = new HeaderPrint();
$hp->print_header();
header('Content-type: text/html; charset=utf8');
$connect = new mysqli('localhost','root','rootroot','shaonTest');
if(mysqli_connect_errno())
{
echo "Cannot connect to Database";
exit;
}
$connect->query("set character_set_results= utf8");
$connect->query("SET NAMES utf8");
// mysql_query ("set character_set_results='utf8'");
$name=trim($_POST['GoodsName']);
// echo "Name retrieved ===> $name";
echo "<br>";
//$n="NULL";
$qquery="INSERT INTO Warehouse VALUES(\"NULL\",'".$name."')";
$result=$connect->query($qquery);
if($result)
{
echo " <br> $connect->affected_rows টি পন্য ডাটাবেজে রাখা হয়েছে । </br>";
}
else
echo "<br> কস্কি মবিন !!! কিছু একটা গোলমাল হইসে !! </br>";
// echo $result;
echo "<br> আরো কিছু কি ডাটাবেজে রাখবেন ? </br>";
echo "<form method=\"POST\" action=\"insertGoods.php\"> \n
<input type = \"submit\" value = \"ইয়েস !\">\n
<input type = \"text\" name = \"duplicate\" value = '".$name."'> \n
</form>";
$connect->close();
$fp = new FooterPrint();
$fp->printFooter();
?>
<file_sep>/phpProgs/HeaderPrint.php
<?php
class HeaderPrint{
public function print_header()
{
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"> \n
<head> \n
<title>বাজারের হিসাব-নিকাশ </title> \n
<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" /> \n
<meta name=\"generator\" content=\"শাওন + Geany 0.21\" /> \n
</head> \n
<body> \n";
}
}
?>
<file_sep>/phpProgs/insertGoods.php
<?php
require_once('HeaderPrint.php');
require_once('FooterPrint.php');
$hp = new HeaderPrint();
$hp->print_header();
echo "<form method=\"POST\" action=\"InsertInWarehouse.php\"> \n
<h2> ডাটাবেজ এ বিভিন্ন পন্য এর নাম রাখুন : </h2>\n
<input type = \"text\" name = \"GoodsName\" > \n
<input type = \"submit\" value = \"submit\">\n
</form>";
echo "<h2> বর্তমানে ডাটাবেজ এ আছেঃ </h2> \n";
$connect=new mysqli('localhost','root','rootroot','shaonTest');
$connect->query("set character_set_results='utf8'");
if(mysqli_connect_errno())
{
echo "cannot connect to the database";
exit;
}
$query = "select * from Warehouse";
$result=$connect->query($query);
$no_rows= $result->num_rows;
echo "......মোট পন্য পাওয়া গেছেঃ .... :-->";
echo $no_rows;
echo "টি ";
echo "<br>";
$n=0;
for ($i=0; $i <$no_rows ; $i++)
{
$j=$i+1;
$row = $result->fetch_assoc();
// echo "<br> ($i+1) Name: </br>";
// echo "<br>$j</br>";
// echo htmlspecialchars(stripslashes($row['name']));
if($row['GoodsName']==$_POST['duplicate'] && $n==0)
{
$n=1;
echo "<font color=\"#ff4500\" size =12 >";
//echo $row['GoodsName'];
echo $_POST['duplicate'];
// echo " ";
echo "</font>";
}
else
echo $row['GoodsName'];
echo "      ";
// echo "<strong><br> id: </br> </strong>";
// echo stripslashes($row['id']);
// echo " <br>......</br>";
}
$result->free();
$connect->close();
$fp = new FooterPrint();
$fp->printFooter();
?>
<file_sep>/PHP/ren.php
<?php
if (isset($_POST['bill_no']) )
{
$ret = add_to_database();
if (!$ret)
{
print "Error: Database error";
}
else
{
print "Thank you for submission";
}
}
else
{
echo "ok";
write_form();
}
//functions
function write_form() {
$self =$_SERVER['PHP_SELF'];
echo <<<EOT
<form action="$self" method="POST">
<table>
<tr>
<td>Bill No:</td>
<td><input type="text" name="bill_no"/></td>
</tr>
<tr>
<td>Bill Date:</td>
<td><input type="date" name="bill_date" /></td>
</tr>
<tr>
<td>Description:</td>
<td><input type="text" name="description" /></td>
</tr>
<tr>
<td>Receipt Date:</td>
<td><input type="date" name="receipt_date" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" /></td>
</tr>
</table>
</form>
EOT;
}
function add_to_database() {
$bill_no = trim($_POST['bill_no']);
$bill_date = trim($_POST['bill_date']);
$description = trim($_POST['description']);
$receipt_date = trim($_POST['receipt_date']);
echo($bill_no);
mysql_connect("localhost","root","") or die("Coulsdn't connect to server");
mysql_select_db("durjay");
//check_user($username);
//check_email($email);
$sql = "INSERT INTO `bill_info` VALUES ('$bill_no', '$bill_date', '$description', '$receipt_date')";
mysql_query($sql);
mysql_close();
return true;
}
//this will check whether there is user with same user name
/*function check_user($usr) {
$sql = "SELECT * FROM `site_users` WHERE username='$usr'";
$result = mysql_query($sql);
$rows =mysql_num_rows($result);
if ($rows>0) {
print "The user $usr already exists. Please select another username.";
exit;
}
}
//checks that email is unique
function check_email($em) {
$sql = "SELECT * FROM `site_users` WHERE user_email='$em'";
$result = mysql_query($sql);
$rows =mysql_num_rows($result);
if ($rows>0) {
print "The e-mail address $em already exists. Please type another e-mail address.";
exit;
}
}*/
?>
<file_sep>/PHP/bill.php
<?php
$t=1;
echo "My name is $t";
if($t==1)
{
echo "test <br>";
echo "fine!!! <br>";
$ret=add_db();
if(!$ret)
{
print "ERROR DB";
}
else
{
print "Thanks";
}
}
else
{
echo "fine!!! <br>";
echo "test <br>";
Bill_info();
}
function Bill_info()
{
$self=$_SERVER['PHP_SELF'];
echo <<<EOT
<form action="$self" method="POST">
Enter BILLNO here:<br />
<textarea name="bill_no" rows="1" cols="10" wrap>
</textarea><br />
Enter DATE here:<br />
<textarea name="bill_date" rows="1" cols="15" wrap>
</textarea><br />
Enter DESCRIPTION here:<br />
<textarea name="description" rows="1" cols="40" wrap>
</textarea><br />
Enter the RECEIPTDATE here:<br />
<textarea name="recept_date" rows="1" cols="50" wrap>
</textarea><br />
<input type="submit" name="submit" value="SUBMIT">
</form>
EOT;
}
function add_db()
{
$bill_no=trim($_post['bill_no']);
$bill_date=trim($_post['bill_date']);
$description=trim($_post['description']);
$receipt_date=trim($_post['receipt_date']);
/*$bill_no=1;
$bill_date="2001-01-23";
$description="shaonshaon";
$receipt_date="2004-03-12";*/
mysql_connect("localhost","root","shaonna")OR die("couldnt connect");
echo $bill_no;
echo"<br>"
mysql_select_db("shaon");
$sql="INSERT INTO `shaon`.`bills` (`bill_no` ,`bill_date` ,`description` ,`receipt_date`)
VALUES('5', '2015-5-21', 'shaonshuktimuktajewel', '2011-05-16')";
echo $bill_no;
echo"<br>"
//$sql="INSERT INTO bills VALUES("$bill_no","$bill_date","$description","$receipt_date")";
//$retn=mysql_query($sql);
mysql_close();
return true;
}
?>
<file_sep>/phpProgs/calender.php
<?php
$today = getdate();
//print_r($today);
echo $today['year']; echo "/"; echo $today['mon']; echo "/";echo $today['mday'];
?>
<file_sep>/PHP/tushar.php
<?php
if(isset($_POST['bill_info']))
{
$ret=add_db();
if(!$ret)
{
print "ERROR DB";
}
else
{
print "Thanks";
}
}
else
{
Bill_info();
}
function Bill_info()
{
$self=$_SERVER['PHP_SELF'];
echo <<< EOT
<form action="$self" method="POST">
Enter BILLNO here:<br>
<input type=text name="bill_no" >
<br>
Enter DATE here:<br>
<input type=text name="bill_date" >
<br>
Enter DESCRIPTION here:<br>
<input type=text name="description" >
<br>
Enter the RECEIPTDATE here:<br>
<input type=text name="recept_date">
<br>
<input type="submit" name="submit" value="SUBMIT">
</form>
EOT;
}
function add_db()
{
$bill_no=trim($_post['bill_no']);
$bill_date=trim($_post['bill_date']);
$description=trim($_post['description']);
$receipt_date=trim($_post['receipt_date']);
mysql_connect('localhost','root')OR die("couldnt connect");
echo $bill_no;
mysql_select_db('ahsan',$db);
$sql="INSERT INTO `billinfo`(`bill_no`,`bill_date`,`description`,`receipt_date`) VALUES('$bill_no','$bill_date','$description','$receipt_date')";
mysql_query($sql);
mysql_close();
return true;
}
?>
<file_sep>/issue/index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<form name="issue_form" action="$_SERVER['PHP_SELF']" method="POST">
<?php
echo "<select name=\"$pid\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
mysql_connect("localhost","root","shaonna") or die("coudnt connect");
mysql_select_db("dept_project");
$sql="SELECT pid FROM issue";
$ret=mysql_query($sql);
//echo "<option value=\"$strA\">$strB</option>\n";
for($i=0; $i<mysql_num_rows($ret);$i++)
{
$t=mysql_result($ret, $i);
echo "<option > $t</option>\n";
}
// echo "<br>".mysql_result($ret, $i);
/*foreach ($res as $ind =>$content)
echo "<br> $ind-----$content";*/
?>
</form>
</body>
</html>
<file_sep>/phpProgs/show.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/xml"; charset="utf-8" />
<link rel = "stylesheet" type = "text/css" href = "/phpProgs/jquery-ui-1.8.13.custom.css" />
<script type = "text/javascript" src = "/phpProgs/jquery.min.js"></script>
<script type = "text/javascript" src = "/phpProgs/jquery-ui-1.8.13.custom.min.js"></script>
<script type = "text/javascript">
//<![CDATA[
$(init);
function init(){
$("h1").addClass("ui-widget-header");
$("#datePicker").datepicker();
}
//]]>
</script>
<title> বাজারের হিসাব নিকাশ </title>
</head>
<body>
<h1> খরচের খেরো-খাতাঃ </h1>
<?php
header('Content-type: text/html; charset=utf8');
$connect=new mysqli('localhost','root','rootroot','shaonTest');
$connect->query("set character_set_results='utf8'");
if(mysqli_connect_errno())
{
echo "cannot connect to the database";
exit;
}
$date1=$_POST['date1'];
$date2=$_POST['date2'];
$query = "select * from Expense WHERE Date between '".$date1."' and '".$date2."' ORDER BY Date DESC";
$qvara = "select * from RoadVehicle WHERE Date between '".$date1."' and '".$date2."' ORDER BY Date DESC";
$result=$connect->query($query);
$no_rows= $result->num_rows;
$total=0;
$Qt=0;
$pr=0;
echo "<table border=\"1\">\n";
echo "<tr><th bgcolor=\"#CCCCFF\"> তারিখঃ </th>
<th bgcolor=\"#CCCCFF\">পন্যের নামঃ </th>
<th bgcolor=\"#CCCCFF\"> প্রতি ইউনিটের দামঃ </th>
<th bgcolor=\"#CCCCFF\">ক্রয়ের পরিমানঃ</th>
<th bgcolor=\"#CCCCFF\">মোট মুল্যঃ</th>
</tr>";
for ($i=0; $i <$no_rows ; $i++)
{
$row = $result->fetch_assoc();
$Qt=$row['Qty'];
$pr = $row['pricePerUnit'];
$tot=$pr * $Qt;
$total = $total +$tot;
echo "<tr>
<td align=\"right\">".$row['Date']."</td>
<td align=\"right\">".$row['GoodsName']."</td>
<td align=\"right\">".$row['pricePerUnit']."</td>
<td align=\"right\">".$row['Qty']."</td>
<td align=\"right\">".$tot."</td>
</tr>";
}
echo "</table>";
echo "<h4>গাড়ি ভাড়াঃ </h4>";
echo "<table border=\"1\">\n";
echo "<tr><th bgcolor=\"#CCCCFF\"> তারিখঃ </th>
<th bgcolor=\"#CCCCFF\">গাড়ি ভাড়াঃ </th>
</tr>";
$result=$connect->query($qvara);
$no_rows= $result->num_rows;
$vara=0;
for ($i=0; $i <$no_rows ; $i++)
{
$row = $result->fetch_assoc();
$vara=$row['Vehicle'];
$total = $total +$vara;
echo "<tr>
<td align=\"right\">".$row['Date']."</td>
<td align=\"right\">".$row['Vehicle']."</td>
</tr>";
}
echo "</table>";
echo "<h3>";
echo "$date1 থেকে $date2 পর্যন্ত মোট খরচঃ : "; echo $total;echo " ৳ " ;
echo "</h3>";
$result->free();
$connect->close();
?>
</body>
</html>
<file_sep>/phpProgs/2-dynamic_select_boxes/chap1.html
<h2>1 - Gathering Your Tools</h2>
<ul>
<li>Picking your computer</li>
<li>Choosing an editor</li>
<li>Working with Internet Explorer</li>
<li>Using Firefox</li>
<li>Adding extensions to Firefox</li>
<li>Using other Browsers</li>
</ul>
<file_sep>/phpProgs/InsertExpense.php
<?php
require_once('HeaderPrint.php');
require_once('FooterPrint.php');
$hp = new HeaderPrint();
$hp->print_header();
header('Content-type: text/html; charset=utf8');
$goods=trim($_POST['GoodsName']);
$dt=$_POST['date'];
$qt=$_POST['qty'];
$pr=$_POST['price'];
echo $_POST['date']." তারিখ ";
echo "আপনি ".$goods." কিনেছেন, ";
echo "প্রতি ইউনিট ".$pr." টাকা দরে ".$qt." ইউনিট <br>";
$cost = $pr * $qt;
echo "আপনার খরচ হয়েছেঃ == ".$cost." টাকা <br>";
$connect = new mysqli('localhost','root','rootroot','shaonTest');
if(mysqli_connect_errno())
{
echo "Cannot Connect To the Database";
}
$connect->query("set character_set_results=utf8");
$connect ->query("SET NAMES utf8");
$qry=" INSERT INTO Expense VALUES('".$dt."','".$goods."','".$pr."','".$qt."')";
$result=$connect->query($qry);
if($result)
{
echo " <br> $connect->affected_rows টি পন্য ডাটাবেজে রাখা হয়েছে । </br>";
}
else
echo "<br> কস্কি মবিন !!! কিছু একটা গোলমাল হইসে !! </br>";
echo "<form action=\"ComputeExpense.php\"> \n
<input type = \"submit\" value = \"আগের পেজে যান !\" action = \"ComputeExpense.php\"> \n
</form>";
$fp = new FooterPrint();
$fp->printFooter();
?>
| ba2c3b55566a828a34df5d56f02ea091bb1ae2c9 | [
"HTML",
"PHP",
"INI"
] | 33 | PHP | shaon3343/myAllPhpWorks | 72d8f5e2bc20c0f12bcc5a20747773025b6a6c03 | 7cfe18e02a559180ba65557746edc96c47e72e13 |
refs/heads/master | <file_sep><?php
include_once 'classes/EnqueteTexto.class.php';
$caminho = 'C:/xampp/htdocs/enquetetexto/enquetes/';
define("CAMINHO_ENQUETE", $caminho);
$enquete = new EnqueteTexto();
//echo $enquete->CriaEnquete("Oque você acha do PHP?");
//$enquete->CriaResposta("teste", 1974);
echo $enquete->ExcluiResposta(1974, 3);
//print_r($enquete->SelecionaEnquete(1974));
//echo $enquete->ExcluiEnquete(1974);
//echo $enquete->RegistrarVoto(1974, 4, 1, "alterou para ruim");
include_once 'modulo.php';
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
Resultado(1974);
?>
</body>
</html>
<file_sep><?php
function Resultado($enquete) {
?>
<table border="1">
<?php
$e = new EnqueteTexto();
$enq = $e->SelecionaEnquete($enquete);
if (is_array($enq)) {
/* print_r($enq);
exit(); */
foreach ($enq as $key => $value) {
$resposta = $enq[$key]["resposta"];
$porcentagem = $enq[$key]["porcentagem"];
$votos = $enq[$key]["votos"];
?>
<tr>
<td><?php echo $resposta; ?></td>
<td><div style="width: <?php echo $porcentagem; ?>px; height:20px; background:blue;"></div></td>
<td><?php echo $votos; ?></td>
</tr>
<?php
}
}
?>
<tr>
<td colspan="3">Total de Votos: <?php echo $e->RetornaTotalDeVotos($enquete); ?></td>
</tr>
</table>
<?php
}
?>
<file_sep><?php
class EnqueteTexto {
private $pergunta;
private $resposta;
private $codigo;
private $id;
private $pasta;
private $arquivoResposta;
private $votos;
private $ids;
private $perguntas;
private $totalVotos;
private $registros;
private $porcentagens;
public function RegistrarVoto($enquete, $id, $voto, $resposta) {
$this->resposta = $resposta;
$this->votos = $voto;
$this->codigo = $enquete;
$this->id = $id;
$this->pasta = CAMINHO_ENQUETE . $this->codigo;
$this->arquivoResposta = $this->pasta . "/resposta_" . $this->id . ".txt";
if (is_dir($this->pasta)) {
$this->votos += 1;
$dados = $this->resposta . "\n" . $this->votos;
session_start();
if (!isset($_COOKIE["enquetetxt"])) {
setcookie("enquetetxt", "true", time() + 24 * 60 * 60);
$handle = fopen($this->arquivoResposta, "w");
fwrite($handle, $this->resposta . "\n");
fwrite($handle, $this->votos);
fclose($handle);
return "Seu voto foi cadastrados com sucesso!";
} else {
return "Seu voto já foi registrado!";
}
}
}
public function SelecionaEnquete($enquete) {
$this->pasta = CAMINHO_ENQUETE . $enquete;
if (is_dir($this->pasta)) {
$this->RetornaRegistros();
$this->RetornaPercentual();
$p = $this->porcentagens;
$r = $this->registros;
$total = count($p);
for ($i = 0; $i < $total; $i++) {
$registros[] = array("enquete" => $enquete, "id" => $r[$i]["id"], "resposta" => $r[$i]["resposta"], "votos" => $r[$i]["votos"], "porcentagem" => $p[$i]["porcentagem"]);
}
$this->registros = $registros;
return $this->registros;
} else {
return "Enquete não encontrada!";
}
}
private function RetornaPercentual() {
$registros = $this->RetornaRegistros();
$totalPerguntas = count($this->registros);
$totalVotos = $this->RetornaTotalDeVotos($this->codigo);
for ($i = 0; $i < $totalPerguntas; $i++) {
if ($registros[$i]["votos"] > 0) {
$valor = (($registros[$i]["votos"] * 100) / $totalVotos);
} else {
$valor = 0;
}
$porcentagens[] = array("porcentagem" => $valor);
}
$this->porcentagens = $porcentagens;
return $this->porcentagens;
}
public function RetornaTotalDeVotos($enquete) {
$this->RetornaRegistros($enquete);
$total = 0;
foreach ($this->registros as $key => $value) {
$total += intval($this->registros[$key]["votos"]);
}
$this->totalVotos = $total;
return $this->totalVotos;
}
private function RetornaRegistros() {
if (is_dir($this->pasta)) {
$resposta = scandir($this->pasta);
$totalResposta = count($resposta);
for ($i = 3; $i < $totalResposta; $i++) {
$id = substr($resposta[$i], 9, 1);
$arquivos[] = $this->pasta . "/" . $resposta[$i];
$ids[] = $id;
}
foreach ($arquivos as $key => $value) {
$handle = fopen($arquivos[$key], "r");
$perguntas[] = trim(fgets($handle));
$votos[] = fgets($handle, 2);
fclose($handle);
}
$this->ids = $ids;
$this->votos = $votos;
$this->perguntas = $perguntas;
$indice = 0;
foreach ($arquivos as $key => $value) {
$registros[] = array(
"id" => $this->ids[$indice],
"resposta" => $this->perguntas[$indice],
"votos" => $this->votos[$indice]
);
$indice++;
}
if (count($registros) > 0) {
$this->registros = $registros;
return $this->registros;
}
} else {
return "A enquete não foi encontrada!";
}
}
public function CriaEnquete($pergunta) {
$this->pergunta = $pergunta;
$this->GeraCodigo();
return $this->CriaPasta();
}
public function ExcluiEnquete($codigo) {
$this->codigo = $codigo;
$this->pasta = CAMINHO_ENQUETE . $this->codigo;
if (is_dir($this->pasta)) {
$arquivos = scandir($this->pasta);
$t = count($arquivos);
for ($i = 2; $i < $t; $i++) {
if (file_exists($this->pasta . "/" . $arquivos[$i])) {
unlink($this->pasta . "/" . $arquivos[$i]);
}
}
if (rmdir($this->pasta)) {
return "A enquete foi excluida com sucesso!";
}
} else {
return "Erro! Não foi possível excluir a enquete selecionada pois ela não existe.";
}
}
public function CriaResposta($resposta, $codigo) {
$this->resposta = $resposta;
$this->codigo = $codigo;
$this->pasta = CAMINHO_ENQUETE . $this->codigo;
if (is_dir($this->pasta)) {
$total = scandir($this->pasta);
$t = count($total);
if ($t <= 11) {
$np = 0;
for ($i = 2; $i < $t; $i++) {
$np++;
}
if ($np == 1) {
$np = 1;
$this->arquivoResposta = "resposta_{$np}.txt";
} else {
$item = intval(substr($total[$t - 1], 9, 1));
$this->arquivoResposta = "resposta_" . ($item + 1) . ".txt";
}
return $this->CriaArquivo();
}
} else {
return "Erro! Não foi possível cadastrar a resposta pois a enquete não existe!";
}
}
public function ExcluiResposta($enquete, $resposta) {
$this->pasta = CAMINHO_ENQUETE . $enquete;
$this->id = $resposta;
$this->arquivoResposta = $this->pasta . "/" . "resposta_" . $this->id . ".txt";
if (is_dir($this->pasta)) {
if (file_exists($this->arquivoResposta)) {
if (unlink($this->arquivoResposta)) {
return "A resposta foi excluida com sucesso!";
}
} else {
return "Erro! Não foi possível excluir a resposta pois ela não existe.";
}
} else {
return "Erro! Não foi possível excluir a resposta pois a enquete não existe.";
}
}
private function GeraCodigo() {
$this->codigo = rand(1000, 9999);
}
private function CriaPasta() {
$this->pasta = CAMINHO_ENQUETE . $this->codigo;
if (!is_dir($this->pasta)) {
mkdir($this->pasta, 0777);
$handle = fopen($this->pasta . "/pergunta.txt", "w");
fwrite($handle, $this->pergunta);
fclose($handle);
return "A enquete foi criada com sucesso!";
} else {
return "Erro! Não foi possível criar a enquete pois ela já existe.";
}
}
private function CriaArquivo() {
$this->pasta = CAMINHO_ENQUETE . $this->codigo . "/";
$this->arquivoResposta = $this->pasta . $this->arquivoResposta;
$handle = fopen($this->arquivoResposta, "w+");
fwrite($handle, "$this->resposta\n0");
fclose($handle);
if (file_exists($this->arquivoResposta)) {
return "A resposta foi cadastrada com sucesso!";
} else {
return "Erro! Não foi possível cadastrar a resposta.";
}
}
}
?>
| 221315793f430717b04cfba130211149b9f16622 | [
"PHP"
] | 3 | PHP | moldher/enquetetexto | c08a51d5e028c47337d40312b1c7bd513feccc3b | b1ca0526e93e506a354a3c1264ee402077b6d035 |
refs/heads/master | <repo_name>zhandaaaulet/ConsoleJDBCApp<file_sep>/src/com/company/Main.java
package com.company;
import com.company.controllers.UserController;
import com.company.data.PostgresDB;
import com.company.data.interfaces.IDB;
import com.company.repositories.UserRepository;
import com.company.repositories.interfaces.IUserRepository;
public class Main {
public static void main(String[] args) {
IDB db = new PostgresDB();
IUserRepository repo = new UserRepository(db);
UserController controller = new UserController(repo);
MyApplication app = new MyApplication(controller);
app.start();
}
}
| c5b3a0f5b423ff2c7d703e79e0e4713d081369b8 | [
"Java"
] | 1 | Java | zhandaaaulet/ConsoleJDBCApp | ee8f1ccc793b33f84d99ddf90f8412952944c7e0 | 6490039fa51c701bd62fafcb721dc922ce7a3c5f |
refs/heads/master | <file_sep>import React, {useEffect} from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import * as taskActions from '../../actions/taskActions';
import Spinner from '../Global/Spinner';
import Fatal from '../Global/Fatal';
const Tasks = (props) => {
const { getAll, tasks, loading, error } = props;
useEffect(() => {
if(!Object.keys(tasks).length){
getAll();
}
}, [tasks, getAll]);
const showContent = () => {
if(error) {
return <Fatal/>;
}
if(loading) {
return <Spinner/>;
}
return Object.keys(tasks).map((user_id) => (
<div key={user_id}>
<h2>
User: {user_id}
</h2>
<div className='tasks_container'>
{ setTasks (user_id) }
</div>
</div>
))
}
const setTasks = (us_id) => {
const { tasks, updateCheck } = props;
const task_by_user = {
...tasks[us_id]
}
return Object.keys(task_by_user).map((ta_id) => (
<div key={ta_id}>
<input
type='checkbox'
defaultChecked={task_by_user[ta_id].completed}
onChange={
() => updateCheck(us_id, ta_id)
}
/>
{ task_by_user[ta_id].title }
<Link to={`/tasks/save/${us_id}/${ta_id}`} className="m_left">
Edit
</Link>
<Link to='/tasks/' className="m_left">
Delete
</Link>
</div>
));
}
return (
<div>
<Link to='/tasks/save'>
Add task
</Link>
{ showContent() }
</div>
);
}
const mapStateToProps = ({ tasksReducer }) => tasksReducer;
export default connect(mapStateToProps, taskActions)(Tasks);<file_sep>import { LOADING, ERROR, UPDATE_POSTS, UPDATE_COMMENTS, COM_LOADING, COM_ERROR } from '../types/postTypes';
const INITIAL_STATE = {
posts: [],
loading: false,
error: '',
com_loading: false,
com_error: ''
}
export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case LOADING:
return { ...state, loading: true };
case ERROR:
return { ...state, error: action.payload, loading: false }
case UPDATE_POSTS:
return {
...state,
posts: action.payload,
loading: false,
error: ''
}
case UPDATE_COMMENTS:
return {
...state,
posts: action.payload,
com_loading: false,
com_error: ''
}
case COM_LOADING:
return { ...state, com_loading: true };
case COM_ERROR:
return { ...state, com_error: action.payload, com_loading: false }
default: return state;
}
}<file_sep>import axios from 'axios';
import { ERROR, UPDATE_POSTS, LOADING, UPDATE_COMMENTS, COM_LOADING, COM_ERROR } from '../types/postTypes';
import * as userTypes from '../types/userTypes';
const { GET_ALL: USERS_GET_ALL } = userTypes;
export const getByUser = (key) => async (dispatch, getState) => {
dispatch({
type: LOADING
});
const { users } = getState().userReducer;
const { posts } = getState().postsReducer;
const user_id = users[key].id;
try {
const resp = await axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${user_id}`);
const new_posts = resp.data.map((post) => ({
...post,
comments: [],
opened: false
}));
const updated_posts = [
...posts,
new_posts
];
const posts_key = updated_posts.length - 1;
const updated_users = [ ...users];
updated_users[key] = {
...users[key],
posts_key
}
dispatch({
type: UPDATE_POSTS,
payload: updated_posts
});
dispatch({
type: USERS_GET_ALL,
payload: updated_users
});
} catch (error) {
dispatch({
type: ERROR,
payload: 'Post no available, try again later.'
})
}
}
export const togglePost = (posts_key, com_key) => (dispatch , getState) => {
const { posts } = getState().postsReducer;
const selected = posts[posts_key][com_key];
const updated = {
...selected,
opened: !selected.opened
}
const updatedPosts = [...posts];
updatedPosts[posts_key] = [
...posts[posts_key]
];
updatedPosts[posts_key][com_key] = updated;
dispatch({
type: UPDATE_POSTS,
payload: updatedPosts
});
}
export const getComments = (posts_key, com_key) => async (dispatch, getState) => {
dispatch({
type: COM_LOADING
});
const { posts } = getState().postsReducer;
const selected = posts[posts_key][com_key];
try {
const resp = await axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${selected.id}`);
const updated = {
...selected,
comments: resp.data
}
const updatedPosts = [...posts];
updatedPosts[posts_key] = [
...posts[posts_key]
];
updatedPosts[posts_key][com_key] = updated;
dispatch({
type: UPDATE_COMMENTS,
payload: updatedPosts
});
} catch (error) {
dispatch({
type: COM_ERROR,
payload: 'Comments no available, try again later.'
})
}
}<file_sep>import axios from 'axios';
import {
GET_ALL,
LOADING,
ERROR,
SET_USER_ID,
SET_TITLE,
TASK_SAVED,
TASK_UPDATE
} from '../types/taskTypes';
export const getAll = () => async (dispatch) => {
dispatch({
type: LOADING
});
try {
const resp = await axios.get(`https://jsonplaceholder.typicode.com/todos`);
const tasks = {};
resp.data.map((ele) => (
tasks[ele.userId] = {
...tasks[ele.userId],
[ele.id]: {
...ele
}
}
))
dispatch({
type: GET_ALL,
payload: tasks
});
} catch (error){
dispatch({
type: ERROR,
payload: 'Tasks info is wrong, try again later.'
});
}
}
export const setUserId = (user_id) => (dispatch) => {
dispatch({
type: SET_USER_ID,
payload: user_id
})
}
export const setTitle = (title) => (dispatch) => {
dispatch({
type: SET_TITLE,
payload: title
})
}
export const saveTask = (new_task) => async (dispatch) => {
dispatch({
type: LOADING
})
try {
const resp = await axios.post(`https:/jsonplaceholder.typicode.com/todos`, new_task);
console.log(resp.data);
dispatch({
type: TASK_SAVED
})
}
catch (error) {
console.log(error.message);
dispatch({
type: ERROR,
payload: 'Submit task is wrong, try again later.'
});
}
}
export const editTask = (edited_task) => async (dispatch) => {
dispatch({
type: LOADING
})
try {
const resp = await axios.put(`https:/jsonplaceholder.typicode.com/todos/${edited_task.id}`, edited_task);
dispatch({
type: TASK_UPDATE,
payload: resp.data
})
}
catch (error) {
console.log(error.message);
dispatch({
type: ERROR,
payload: 'Submit task is wrong, try again later.'
});
}
}
export const updateCheck = (us_id, ta_id) => (dispatch, getState) => {
const { tasks } = getState().tasksReducer;
const selected = tasks[us_id][ta_id];
const updated = {
...tasks
};
updated[us_id] = {
...tasks[us_id]
};
updated[us_id][ta_id] = {
...tasks[us_id][ta_id],
completed: !selected.completed
}
dispatch({
type: TASK_UPDATE,
payload: updated
})
};<file_sep>export const LOADING = 'POST_LOADING';
export const ERROR = 'POST_ERROR';
export const UPDATE_POSTS = 'POST_UPDATE';
export const UPDATE_COMMENTS = 'COMMENT_UPDATE';
export const COM_LOADING = 'COM_LOADING';
export const COM_ERROR = 'COM_ERROR';<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Spinner from '../Global/Spinner';
import Fatal from '../Global/Fatal';
import * as userActions from '../../actions/userActions';
import * as postActions from '../../actions/postActions';
import Comments from './Comments';
const { getAll: userGetAll } = userActions;
const {
getByUser: postGetByUser,
togglePost,
getComments
} = postActions;
class Posts extends Component {
async componentDidMount() {
const {
userGetAll,
postGetByUser,
match: { params: { key }}
} = this.props;
if(!this.props.userReducer.users.length) {
await userGetAll();
}
if(this.props.userReducer.error){
return;
}
if(!('posts_key' in this.props.userReducer.users[key])){
postGetByUser(key);
}
}
setUser = () => {
const {
userReducer,
match: { params: { key }}
} = this.props;
if(userReducer.error){
return <Fatal message={userReducer.error}/>;
}
if(!userReducer.users.length || userReducer.loading){
return <Spinner/>;
}
const name = userReducer.users[key].name;
return (
<h1> Post from {name}</h1>
);
}
setPosts = () => {
const {
userReducer,
userReducer: { users },
postsReducer,
postsReducer: { posts },
match: { params: { key }}
} = this.props;
if(!users.length) return;
if(userReducer.error) return;
if(postsReducer.loading) {
return <Spinner/>;
}
if(postsReducer.error){
return <Fatal message={postsReducer.error}/>;
}
if(!posts.length) return;
if(!('posts_key' in users[key])) return;
const { posts_key } = users[key];
return this.showInfo(posts[posts_key], posts_key);
}
showInfo = (posts, posts_key) => (
posts.map((post, com_key) => (
<div
className="post_title"
key={post.id}
onClick={
() => this.showComments(posts_key, com_key, post.comments)
}
>
<h2>
{ post.title }
</h2>
<h3>
{ post.body }
</h3>
{
post.opened ? <Comments comments={post.comments}/> : null
}
</div>
))
);
showComments = (posts_key, com_key, comments) => {
this.props.togglePost(posts_key, com_key);
if(!comments.length) {
this.props.getComments(posts_key, com_key);
}
}
render() {
return (
<div>
{ this.setUser() }
{ this.setPosts() }
</div>
);
}
}
const mapStateToProps = ({ userReducer, postsReducer }) => {
return {
userReducer,
postsReducer
};
};
const mapDispatchToProps = {
userGetAll,
postGetByUser,
togglePost,
getComments
}
export default connect(mapStateToProps, mapDispatchToProps)(Posts);<file_sep>import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import Spinner from '../Global/Spinner';
import Fatal from '../Global/Fatal';
import * as taskActions from '../../actions/taskActions';
import { Redirect } from 'react-router-dom';
const Save = (props) => {
useEffect(() => {
const {
match: { params: { us_id, ta_id } },
tasks,
setUserId,
setTitle
} = props;
if(us_id && ta_id){
const task = tasks[us_id][ta_id];
setUserId(task.userId);
setTitle(task.title);
}
}, [props]);
const handleSetUserId = e => {
props.setUserId(e.target.value)
}
const handleSetTitle = e => {
props.setTitle(e.target.value)
}
const hanldeSubmit = e => {
e.preventDefault();
const {
match: { params: { us_id, ta_id } },
tasks,
user_id,
title,
saveTask,
editTask
} = props;
const new_task = {
userId: user_id,
title: title,
completed: false
};
if(us_id && ta_id){
const task = tasks[us_id][ta_id];
const edited_task = {
...new_task,
completed: task.completed,
id: task.id
};
editTask(edited_task);
} else {
saveTask(new_task);
}
}
const disableSave = () => {
const {
user_id,
title,
loading
} = props;
return (loading || (!user_id || !title)) ? true : false;
}
const showAction = () => {
const { error, loading } = props;
if(loading) {
return <Spinner/>
}
if(error) {
return <Fatal message={error}/>
}
}
return (
<div>
{ props.go_back ? <Redirect to='/tasks'/> : null }
<h1>
Save task from
</h1>
User id:
<input
type='number'
id='user_id'
value={props.user_id}
onChange={handleSetUserId}
/>
<br/><br/>
Title:
<input
type='text'
id='title'
value={props.title}
onChange={handleSetTitle}
/>
<br/><br/>
<button
type="button"
onClick={hanldeSubmit}
disabled={ disableSave() }
>Submit</button>
{ showAction() }
</div>
);
}
const mapStateToProps = ({ tasksReducer }) => tasksReducer;
export default connect(mapStateToProps, taskActions)(Save); | 598e81c985cb276bafc10c89fe8aacff7739b05f | [
"JavaScript"
] | 7 | JavaScript | wemf/react-platzi-blog | 01c4aee025c46437a319204ea28729ab053e47d3 | ef1f3802c8569208f8ea8d3c5159478e4fd38f72 |
refs/heads/master | <file_sep>/**************************************************************************
** Author: <NAME>
** Date: 11/20/2019
** Description: Implementation of a simple Linux shell. Supports the
** built-in commands cd, status, and exit. It will also
** allow for redirection of standard input and output,
** and will support both forground and background processes
** (controllable by the command line and signals).
***************************************************************************/
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
//Set the max command line length and max arguments as constants,
//using lengths set in the program requirements.
#define MAX_COMMAND 2048
#define MAX_ARGS 512
//Global variable for catchSIGTSTP so it knows whether to enter
//foreground only mode or exit it.
int backgroundSwitch = 1;
//Declaring functions to avoid implicit declaration warning.
void exitStatus(int childExitMethod);
void catchSIGTSTP();
//Main function that contains the loop that keeps the shell running.
int main()
{
int i;
int continueLoop = 1;
int status = 0;
char userInput[MAX_COMMAND];
char* arguments[MAX_ARGS];
int processes[100];
int numOfProcesses = 0;
char* token;
char inputFile[100] = "\0";
char outputFile[100] = "\0";
char tempString[100] = "\0";
int fdIn = -1;
int fdOut = -1;
int dupRes;
//Declaring a pid_t variable and setting it to a bogus value,
//like how it was done in the lectures.
pid_t spawnpid = -5;
//Initialize every element in arguments array to be NULL.
for (i = 0; i < MAX_ARGS; i++)
arguments[i] = NULL;
//Initializing the required sigaction structs.
//Citation: Lecture 3.3 - Signals
struct sigaction SIGINT_action = {0};
SIGINT_action.sa_handler = SIG_IGN;
SIGINT_action.sa_flags = 0;
sigfillset(&SIGINT_action.sa_mask);
struct sigaction SIGTSTP_action = {0};
SIGTSTP_action.sa_handler = catchSIGTSTP;
SIGTSTP_action.sa_flags = 0;
sigfillset(&SIGTSTP_action.sa_mask);
sigaction(SIGINT, &SIGINT_action, NULL);
sigaction(SIGTSTP, &SIGTSTP_action, NULL);
while(continueLoop == 1)
{
//Declare (reset) argCount and background variables back to 0
//each time the loop starts over.
int argCount = 0;
int background = 0;
//Used with strlen to get the length of the argument in order to
//expand $$ into process ID. See below.
size_t argLength = 0;
//Prints the command prompt and flushes output buffer (recommended in program).
printf(": ");
fflush(stdout);
//Get user input from stdin and store in userInput variable.
fgets(userInput, MAX_COMMAND, stdin);
token = strtok(userInput, " \n");
//Parse user input. Handle the special cases for <, >, and &.
//Otherwise, add the input to the arguments array.
while (token != NULL)
{
if (!strcmp(token, ">"))
{
token = strtok(NULL, " \n");
if (token != NULL)
{
strcpy(outputFile, token);
token = strtok(NULL, " \n");
}
else
printf("No file specified. Not redirecting.\n");
}
else if(!strcmp(token, "<"))
{
token = strtok(NULL, " \n");
if (token != NULL)
{
strcpy(inputFile, token);
token = strtok(NULL, " \n");
}
else
printf("No file specified. Not redirecting.\n");
}
else
{
arguments[argCount] = token;
token = strtok(NULL, " \n");
argCount++;
}
//If the last argument is a & symbol, the command should be run
//int the background. Also reduces argCount by 1 and resets the
//last element of the arry to NULL since the & itself does not
//really count as an argument.
if(!strcmp(arguments[argCount - 1], "&"))
{
background = 1;
arguments[argCount - 1] = NULL;
argCount--;
}
}
//Expands $$ into process ID using a temporary string, argLength from above
//and the current element in the arguments array.
for(i = 0; i < argCount; i++)
{
argLength = strlen(arguments[i]);
if(arguments[i][argLength - 1] == '$' && arguments[i][argLength - 2] == '$')
{
arguments[i][argLength - 2] = 0;
sprintf(tempString, "%s%d", arguments[i], getpid());
arguments[i] = tempString;
}
}
//If nothing is entered or userInput is a comment (starting with #), do nothing.
if(arguments[0] == '\0' || strcmp(arguments[0], "#") == 0 || arguments[0][0] == '#')
{
for(i = 0; arguments[i]; i++)
arguments[i] = NULL;
continue;
}
//Citation: https://stackoverflow.com/questions/9493234/chdir-to-home-directory
else if(strcmp(arguments[0], "cd") == 0)
{
if(arguments[1] == NULL)
chdir(getenv("HOME"));
else
chdir(arguments[1]);
}
//If user chooses to exit, run a for loop to kill all current background processes before exiting the shell.
else if(strcmp(arguments[0], "exit") == 0)
{
if (numOfProcesses > 0)
{
for (i = 0; i < numOfProcesses; i++)
kill(processes[i], SIGKILL);
}
continueLoop = 0;
}
else if(strcmp(arguments[0], "status") == 0)
exitStatus(status);
else
{
//Idea and structure for fork and switch case below taken
//from Lecture 3.1 - Processes.
spawnpid = fork();
switch (spawnpid)
{
case -1:
perror("Hull Breach!");
exit(1);
break;
//Child
case 0:
//Per program requirements, terminate only foreground command if
//one is running, not the shell. Therefore, changing the SIGINT
//action back to default in child.
SIGINT_action.sa_handler = SIG_DFL;
sigaction(SIGINT, &SIGINT_action, NULL);
if(strcmp(inputFile, ""))
{
//Open input file in read only mode per program requirements.
fdIn = open(inputFile, O_RDONLY);
//Citation: Lecture 3.4 - More UNIX I/O
if(fdIn == -1)
{
printf("Hull breach - open() failed.\n");
fflush(stdout);
exit(1);
}
dupRes = dup2(fdIn, 0);
//Citation: Lecture 3.4 - More UNIX I/O
if(dupRes == -1)
{
perror("Error - dup2() failed.\n");
exit(2);
}
close(fdIn);
}
if(strcmp(outputFile, ""))
{
//Open output file in write only mode per program requirements.
fdOut = open(outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
//Citation: Lecture 3.4 - More UNIX I/O
if(fdOut == -1)
{
printf("Hull breach - open() failed.\n");
fflush(stdout);
exit(1);
}
dupRes = dup2(fdOut, 1);
//Citation: Lecture 3.4 - More UNIX I/O
if(dupRes == -1)
{
perror("Error - dup2() failed.\n");
exit(2);
}
close(fdOut);
}
//If process is in the background (and allowed) and no inputFile or outputFile
//are specified for redirection, redirect input/output to /dev/null/.
if(background == 1 && backgroundSwitch == 1)
{
if(!strcmp(inputFile, ""))
{
strcpy(inputFile, "/dev/null");
fdIn = open(inputFile, O_RDONLY);
//Citation: Lecture 3.4 - More UNIX I/O
if(fdIn == -1)
{
printf("Hull breach - open() failed.\n");
fflush(stdout);
exit(1);
}
dupRes = dup2(fdIn, 0);
//Citation: Lecture 3.4 - More UNIX I/O
if(dupRes == -1)
{
perror("Error - dup2() failed.\n");
exit(2);
}
close(fdIn);
}
if(!strcmp(outputFile, ""))
{
strcpy(outputFile, "/dev/null");
fdOut = open(outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
//Citation: Lecture 3.4 - More UNIX I/O
if(fdOut == -1)
{
printf("Hull breach - open() failed.\n");
fflush(stdout);
exit(1);
}
dupRes = dup2(fdOut, 1);
//Citation: Lecture 3.4 - More UNIX I/O
if(dupRes == -1)
{
perror("Error - dup2() failed.\n");
exit(2);
}
close(fdOut);
}
}
if(execvp(arguments[0], arguments))
{
printf("No command, file or directory called \"%s\"\n", arguments[0]);
fflush(stdout);
exit(1);
}
break;
//Parent
default:
//If user specifies background process and background
//processes are allowed, outputs the process ID of the
//background process, adds it to the background process,
//and increases numOfProcesses by 1.
if(background == 1 && backgroundSwitch == 1)
{
printf("background pid is %d\n", spawnpid);
fflush(stdout);
processes[numOfProcesses] = spawnpid;
numOfProcesses++;
break;
}
else
waitpid(spawnpid, &status, 0);
}
}
//Reset the elements in the arguments array, inputFile, and outputFile.
for(i = 0; arguments[i]; i++)
arguments[i] = NULL;
inputFile[0] = '\0';
outputFile[0] = '\0';
tempString[0] = '\0';
//Checks for background child processes to complete.
spawnpid = waitpid(-1, &status, WNOHANG);
while (spawnpid > 0)
{
printf("child %d terminated\n", spawnpid);
fflush(stdout);
exitStatus(status);
numOfProcesses--;
spawnpid = waitpid(-1, &status, WNOHANG);
}
}
}
//Simple function that prints the exit status or terminating
//signal of the last forground process.
//Citation: Lecture 3.1 - Processes
void exitStatus(int childExitMethod)
{
if (WIFEXITED(childExitMethod))
{
int status = WEXITSTATUS(childExitMethod);
printf("Exit status was %d\n", status);
fflush(stdout);
}
else
{
int termSignal = WTERMSIG(childExitMethod);
printf("The process was terminated by signal %d\n", termSignal);
fflush(stdout);
}
}
//When the SIGTSTP signal is caught, send an informational message to the
//console and update the backgroundSwitch variable.
void catchSIGTSTP()
{
if (backgroundSwitch == 1)
{
//Turning the switch off.
backgroundSwitch = 0;
//Outputting informative message per program requirements.
puts("\nNow entering foreground-only mode. The & character is ignored, and background processes cannot be run.");
fflush(stdout);
}
else
{
//Turning the switch back on.
backgroundSwitch = 1;
//Outputting informative message per program requirements.
puts("\nNow exiting foreground-only mode. The & character can once again be used, and background processes are allowed.");
fflush(stdout);
}
}
| d40d20ba1133fa4fa42fb2c0e89f6a219ab1c883 | [
"C"
] | 1 | C | shumack93/Smallsh-Linux-Shell | ec5a00391b50aea7cd0fcebcdb9c6526ef6545f7 | 4487d11d972a335f8f887740b77a7a530f423f36 |
refs/heads/master | <file_sep>//
// ViewController.swift
// EmptyDataViewDemo
//
// Created by USER on 2018/12/11.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func nodataAction(_ sender: Any) {
let vc = TableViewController()
vc.dataType = 0
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func licenseAction(_ sender: Any) {
let vc = TableViewController()
vc.dataType = 1
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func activityAction(_ sender: Any) {
let vc = TableViewController()
vc.dataType = 2
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func integralAction(_ sender: Any) {
let vc = TableViewController()
vc.dataType = 3
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func noNetAction(_ sender: Any) {
let vc = TableViewController()
vc.dataType = 4
navigationController?.pushViewController(vc, animated: true)
}
}
<file_sep>
//
// DDScanStyleConfig.swift
// DDScanDemo
//
// Created by USER on 2018/11/27.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import AVFoundation
/// 扫码区域动画效果
public enum DDScanViewAnimationStyle: Int {
case lineMove //线条上下移动
// case netGrid //网格
}
/// 扫码区域4个角位置类型
public enum DDScanViewPhotoframeAngleStyle: Int {
case inner//内嵌,一般不显示矩形框情况下
case outer//外嵌,包围在矩形框的4个角
case on //在矩形框的4个角上,覆盖
}
public enum DDScanShowStyle: Int {
case push
case present
}
public struct DDScanStyleConfig {
/// MARK --- navigationBar配置相关
public var navigationBarColor: UIColor? = #colorLiteral(red: 0.2039215686, green: 0.2039215686, blue: 0.2156862745, alpha: 1)
public var navigationBarTintColor: UIColor? = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
public var navigationBarTitle: String? = "扫一扫"
public var navigationBarTitleFont: UIFont? = UIFont.systemFont(ofSize: 18)
public var navigationBarBackImage: UIImage? = DDScanImage.image(for: "scan_close")
/// MARK --- 界面UI相关
public var introduceLabelTitle: String = NSLocalizedString("请将条形码/二维码放入框内", comment: "")
public var descLabelTitle: String = NSLocalizedString("若您使用扫码积分功能\n扫码成功后系统将自动赠送积分到您的账户", comment: "")
public var photoBtnTitle: String = NSLocalizedString("相册", comment: "")
public var photoBtnImage: UIImage? = DDScanImage.image(for: "scan_photo")
public var flashBtnTitle: String = NSLocalizedString("闪光灯", comment: "")
public var flashBtnImage: UIImage? = DDScanImage.image(for: "scan_flash")
/// MARK ---- modal样式
public var showStyle: DDScanShowStyle = .push
/// MARK ---- 扫码类型支持
//以下为条形码,如果项目只需要扫描二维码,只需要设置[.qr, .ean13, .code128]
//类型越多,扫描效率越低
// [.qr, .ean13, .ean8, .upce, .code39, .code39Mod43, .code93, .code128, .pdf417]
public var arrayCodeType: [AVMetadataObject.ObjectType] = [.qr, .ean13, .ean8, .upce, .code39, .code39Mod43, .code93, .code128, .pdf417]
// MARK: - -中心位置矩形框
/// 相机启动时提示的文字信息
public var readyString: String = ""
/// 是否需要绘制扫码矩形框,默认false
public var isNeedShowRetangle: Bool = false
/// 默认扫码区域为正方形,如果扫码区域不是正方形,设置宽高比
public var whRatio: CGFloat = 1.0
/// 矩形框(视频显示透明区)域向上移动偏移量,0表示扫码透明区域在当前视图中心位置,如果负值表示扫码区域下移
public var centerUpOffset: CGFloat = 44
/// 矩形框(视频显示透明区)域离界面左边及右边距离,默认70
public var xScanRetangleOffset: CGFloat = 70
/// 矩形框线条颜色,默认白色
public var colorRetangleLine = UIColor.white
// MARK: -矩形框(扫码区域)周围4个角
/// 扫码区域的4个角类型
public var photoframeAngleStyle: DDScanViewPhotoframeAngleStyle = .inner
/// 4个角的颜色
public var colorAngle: UIColor = #colorLiteral(red: 0, green: 0.6666666667, blue: 1, alpha: 1)
/// 扫码区域4个角的宽度和高度
public var photoframeAngleW: CGFloat = 18
public var photoframeAngleH: CGFloat = 18
/// 扫码区域4个角的线条宽度,
public var photoframeLineW: CGFloat = 2
// MARK: - ---动画效果
/// 扫码动画效果:线条
public var anmiationStyle: DDScanViewAnimationStyle = .lineMove
/// 动画效果的图像,如线条或网格的图像
public var animationImage: UIImage? = DDScanImage.image(for: "scan_part_net")
// MARK: - 非识别区域颜色,默认 RGBA (0,0,0,0.5),范围(0--1)
public var colorNotRecoginitonArea: UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5)
//是否需要返回识别后的当前图像
public var isNeedCodeImage = false
public init () {
}
}
/// 获取bundle中image
public class DDScanImage: NSObject {
public static func image(for name: String?) -> UIImage? {
guard let name = name else {
return nil
}
if let path = Bundle(for: DDScanImage.classForCoder()).path(forResource: "DDScan", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: name, in: bundle, compatibleWith: nil)
{
return image
}
return nil
}
}
<file_sep>//
// CHLog.swift
// CHLog
//
// Created by wanggw on 2018/5/28.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
import UIKit
// MARK: -
public typealias CHLogClosure = (_ info: String, _ attributedString: NSMutableAttributedString) -> Void
public typealias CHLogChangedClosure = (_ infoArray: [CHLogItem]) -> Void
fileprivate let Date_Formatter = DateFormatter()
public enum CHLogShowType {
case none //不打印
case all //所有
case error //错误
}
public protocol DDRequstItemProtocol {
var method: String? { get }
var url: String? { get }
var headers: [String: String]? { get }
var parameters: [String: String]? { get }
var response: [String: Any]? { get }
var isError: Bool? { get }
}
// MARK: - API
public extension CHLog {
/// 显示日志按钮
///
/// - Parameters:
/// - showType: 显示类型
/// - listenUrls: 白名单
public class func setup(with showType: CHLogShowType, listenUrls: [String]?) {
CHLog.shared.setup(with: showType, listenUrls: listenUrls)
}
/// 显示终端打印的日志,info:终端print信息、isError:是否是错误信息
public class func log(with info: String, isError: Bool = false) {
CHLog.shared.log(with: info, isError: isError)
}
public class func log(with request: DDRequstItemProtocol) {
CHLog.shared.log(with: request)
}
}
public extension CHLog {
/// 日志信息改变的回调
///
/// - Parameter logClosure: 回调
public class func logInfoChanged(logClosure: @escaping CHLogClosure) {
CHLog.shared.logInfoChang(logClosure: logClosure)
}
public class func logInfoArrayChanged(logClosure: @escaping CHLogChangedClosure) {
CHLog.shared.logInfoArrayChanged(logClosure: logClosure)
}
/// 当前的日志字符串
public class func currentLogInfo() -> String {
return CHLog.shared.currentLogInfo()
}
public class func currentInfoAttributedString() -> NSMutableAttributedString {
return CHLog.shared.currentInfoAttributedString()
}
class func currentLogArray() -> [CHLogItem] {
return CHLog.shared.currentLogArray()
}
public class func currentShowType() -> CHLogShowType {
return CHLog.shared.currentShowType()
}
class func clean() {
CHLog.shared.clean()
}
/// 隐藏日志按钮
class func show() {
CHLog.shared.show()
}
/// 隐藏日志按钮
class func hidden() {
CHLog.shared.hidden()
}
}
public class CHLog: NSObject {
fileprivate var window: UIWindow?
fileprivate var logButton: CHButton?
fileprivate var showType: CHLogShowType = .none
fileprivate var listenUrls: [String] = []
fileprivate var logInfoArray: [CHLogItem] = []
fileprivate var logChangedClosure: CHLogChangedClosure?
fileprivate var logInfo: String = ""
fileprivate var infoAttributedString: NSMutableAttributedString = NSMutableAttributedString(string: "")
fileprivate var logClosure: CHLogClosure?
static let shared = CHLog()
private override init() {
super.init()
customInit()
}
private func customInit() {
window = CHWindow.init(frame: UIScreen.main.bounds)
window?.rootViewController = UIViewController()
window?.rootViewController?.view.backgroundColor = UIColor.clear
window?.rootViewController?.view.isUserInteractionEnabled = false
window?.windowLevel = UIWindow.Level.alert-1
window?.alpha = 1.0
let bottom_space = (UIScreen.main.bounds.size.height == 812) ? CGFloat(49+34): CGFloat(49)
logButton = CHButton(type: .custom)
logButton?.frame = CGRect(x: UIScreen.main.bounds.width - 60 - 20, y: UIScreen.main.bounds.height - 60 - 20 - bottom_space, width: 60, height: 60)
logButton?.backgroundColor = UIColor.white
logButton?.setTitle("日志", for: .normal)
logButton?.setTitleColor(UIColor.red, for: .normal)
logButton?.clipsToBounds = true
logButton?.layer.cornerRadius = 30
logButton?.layer.borderWidth = 7
logButton?.layer.borderColor = UIColor.red.cgColor
if let logButton = logButton {
window?.addSubview(logButton)
}
let tap = UITapGestureRecognizer(target: self, action: #selector(showLogView))
logButton?.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(show), name: UIApplication.didBecomeActiveNotification, object: nil)
}
}
extension CHLog {
@objc private func show() {
window?.isHidden = false ///默认为YES,当你设置为NO时,这个Window就会显示了
}
private func setup(with showType: CHLogShowType, listenUrls: [String]?) {
self.showType = showType
self.listenUrls = listenUrls ?? []
}
private func hidden() {
window?.isHidden = true
}
/// 一、处理调试打印
private func log(with info: String, isError: Bool) {
let logItem: CHLogItem = CHLogItem()
logItem.logInfo = info
logItem.isError = isError
logItem.isRequest = false
logInfoArray.insert(logItem, at: 0)
if let logChangedClosure = self.logChangedClosure {
logChangedClosure(self.logInfoArray)
}
}
/// 二、处理请求日志
private func log(with request: DDRequstItemProtocol) {
guard let url = request.url, shouldListen(requestUrl: url) else {
return
}
let notificaitonAction = {
if let logChangedClosure = self.logChangedClosure {
logChangedClosure(self.logInfoArray)
}
}
var isContainted = false
var exIndex = -1
for (index, logInfo) in logInfoArray.enumerated() {
if let url = request.url, logInfo.requstFullUrl.isEqual(url) {
isContainted = true
exIndex = index
break
}
}
//1、不包含,是一个新的网络请求
if !isContainted {
//新请求
let logInfo = CHLogItem.item(with: request)
logInfoArray.insert(logInfo, at: 0)
notificaitonAction()
return
}
//2、已经包含,而且是第n次发起请求,替换位置到最前面
if request.response == nil {
logInfoArray.swapAt(exIndex, 0)
notificaitonAction()
return
}
//3、请求回调,即:request.response != nil
for logInfo in logInfoArray {
if let url = request.url, logInfo.requstFullUrl.isEqual(url) {
let responseLogInfo = CHLogItem.item(with: request)
//插入到 index:0 位置,相同的请求可能会有多个相应
logInfo.responses.insert(responseLogInfo, at: 0)
notificaitonAction()
break
}
}
}
private func shouldListen(requestUrl: String) -> Bool {
if listenUrls.isEmpty {
return true
}
var isShouldListen = false
listenUrls.forEach({ (url) in
if requestUrl.contains(url) {
isShouldListen = true
}
})
return isShouldListen
}
private func logInfoChang(logClosure: @escaping CHLogClosure) {
self.logClosure = logClosure
}
private func logInfoArrayChanged(logClosure: @escaping CHLogChangedClosure) {
self.logChangedClosure = logClosure
}
private func currentShowType() -> CHLogShowType {
return showType
}
private func currentLogInfo() -> String {
return logInfo
}
func currentLogArray() -> [CHLogItem] {
return logInfoArray
}
private func currentInfoAttributedString() -> NSMutableAttributedString {
return infoAttributedString
}
private func clean() {
logInfo = ""
infoAttributedString = NSMutableAttributedString(string: "")
if let logClosure = logClosure {
logClosure(logInfo, infoAttributedString)
}
logInfoArray.removeAll()
if let logChangedClosure = logChangedClosure {
logChangedClosure(logInfoArray)
}
}
private func currentTimeString() -> String {
Date_Formatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
return "\(Date_Formatter.string(from: Date()))"
}
@objc fileprivate func showLogView() {
let vc = CHLogListViewController()
let nav = UINavigationController.init(rootViewController: vc)
UIViewController.currentViewController()?.present(nav, animated: true, completion: {
self.hidden()
})
}
}
// MARK: - UIViewController
extension UIViewController {
/// 获取当前显示的视图
class func currentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return currentViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
return currentViewController(base: tab.selectedViewController)
}
if let presented = base?.presentedViewController {
return currentViewController(base: presented)
}
print("【DDDebug】+++++++++++++:推出日志的视图是:\(String(describing: base))")
return base
}
/// 获取导航栏视图
func log_navigationController() -> UINavigationController? {
if self is UINavigationController {
return self as? UINavigationController
}
else {
if self is UITabBarController, let tabbar = self as? UITabBarController {
return tabbar.selectedViewController?.log_navigationController()
}
else {
return self.navigationController
}
}
}
}
<file_sep>//
// DDVideoPlayerDelegate.swift
// mpdemo
//
// Created by USER on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import UIKit
public enum DDPlayerState: Int {
case none // default
case playing
case paused
case playFinished
case error
}
public enum DDPlayerBufferstate: Int {
case none // default
case readyToPlay
case buffering
case stop
case bufferFinished
}
public enum DDVideoGravityMode: Int {
case resize
case resizeAspect // default
case resizeAspectFill
}
public enum DDPlayerBackgroundMode: Int {
case suspend
case autoPlayAndPaused
case proceed
}
public protocol DDVideoPlayerDelegate: class {
// play state
func ddPlayer(_ player: DDVideoPlayer, stateDidChange state: DDPlayerState)
// playe Duration
func ddPlayer(_ player: DDVideoPlayer, playerDurationDidChange currentDuration: TimeInterval, totalDuration: TimeInterval)
// buffer state
func ddPlayer(_ player: DDVideoPlayer, bufferStateDidChange state: DDPlayerBufferstate)
// buffered Duration
func ddPlayer(_ player: DDVideoPlayer, bufferedDidChange bufferedDuration: TimeInterval, totalDuration: TimeInterval)
// play error
func ddPlayer(_ player: DDVideoPlayer, playerFailed error: DDVideoPlayerError)
}
// MARK: - delegate methods optional
public extension DDVideoPlayerDelegate {
func ddPlayer(_ player: DDVideoPlayer, stateDidChange state: DDPlayerState) {}
func ddPlayer(_ player: DDVideoPlayer, playerDurationDidChange currentDuration: TimeInterval, totalDuration: TimeInterval) {}
func ddPlayer(_ player: DDVideoPlayer, bufferStateDidChange state: DDPlayerBufferstate) {}
func ddPlayer(_ player: DDVideoPlayer, bufferedDidChange bufferedDuration: TimeInterval, totalDuration: TimeInterval) {}
func ddPlayer(_ player: DDVideoPlayer, playerFailed error: DDVideoPlayerError) {}
}
<file_sep>//
// ViewController.swift
// DDCustomCameraDemo
//
// Created by USER on 2018/12/4.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import Photos
import DDKit
class ViewController: UIViewController {
var manager = DDCustomCameraManager()
//demo只提供显示第一张的imageview
@IBOutlet weak var photoView: UIImageView!
//demo只提供显示第一张的imageview
@IBOutlet weak var albumView: UIImageView!
//相册回调结果接受
var albumArr:[DDPhotoGridCellModel]?
//拍照结果回调
var takePhotoArr: [DDCustomCameraResult]?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let file = FileManager.default
let subPathArr = try? file.contentsOfDirectory(atPath: NSTemporaryDirectory())
for subPath in (subPathArr ?? []) {
print(subPath)
}
DDCustomCameraManager.cleanMoviesFile()
photoView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
photoView.addGestureRecognizer(tap)
albumView.isUserInteractionEnabled = true
let tap2 = UITapGestureRecognizer(target: self, action: #selector(albumImageTapAction))
albumView.addGestureRecognizer(tap2)
// DDPhotoStyleConfig初始化实际项目中,可丢到AppDelegate中初始化
//UI方面的配置主要是针对e肚仔
// if let path = Bundle(for: DDPhotoPickerViewController.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
// let bundle = Bundle(path: path),
// let image = UIImage(named: "photo_nav_icon_back_black", in: bundle, compatibleWith: nil)
// {
// DDPhotoStyleConfig.shared.navigationBackImage = image
// }
// DDPhotoStyleConfig.shared.navigationBackgroudColor = UIColor.white
// DDPhotoStyleConfig.shared.navigationTintColor = UIColor.black
// DDPhotoStyleConfig.shared.navigationBarStyle = .default
//
// DDPhotoStyleConfig.shared.seletedImageCircleColor = UIColor.red
// DDPhotoStyleConfig.shared.bottomBarBackgroudColor = UIColor.white
// DDPhotoStyleConfig.shared.bottomBarTintColor = UIColor.red
// DDPhotoStyleConfig.shared.photoAssetType = .imageOnly
//若你的第一级入口为选择照片,那个在相册中的进入拍照时,是否允许摄像
// DDPhotoStyleConfig.shared.isEnableRecordVideo = false
DDPhotoStyleConfig.shared.maxSelectedNumber = 9
}
@objc func tapAction() {
guard let arr = takePhotoArr else {
return
}
//获取所有的asset数组
var assetArr = [PHAsset]()
for model in arr {
if let asset = model.asset {
assetArr.append(asset)
}
}
if assetArr.count > 0 {
DDPhotoPickerManager.showUploadBrowserController(uploadPhotoSource: assetArr, seletedIndex: 0)
}
}
@objc func albumImageTapAction() {
//获取所有的asset数组
let assetArr = albumArr?.map({ (cellModel) -> PHAsset in
return cellModel.asset
})
guard let arr = assetArr else {
return
}
DDPhotoPickerManager.showUploadBrowserController(uploadPhotoSource: arr, seletedIndex: 0)
}
@IBAction func albumAction(_ sender: Any) {
DDPhotoPickerManager.show {[weak self] (resultArr) in
guard let arr = resultArr else {
return
}
let model = resultArr?.first
self?.albumView.image = model?.image
self?.albumArr = arr
}
}
@IBAction func takePicAction(_ sender: Any) {
//请勿使用weak ,否则会被释放,获取不到回调,类方法block无需担心循环引用
DDCustomCameraManager.show { (arr) in
self.photoView.image = arr?.first?.image
self.getPath(asset: arr?.first?.asset)
self.takePhotoArr = arr
}
}
/// 上传视屏压缩时,导出的filePath,图片不需要调用
///
/// - Parameter asset: asset
func getPath(asset: PHAsset?) {
if asset?.mediaType != .video {
return
}
//presetName 参数主要使用一下三个
//AVAssetExportPresetLowQuality
//AVAssetExportPresetMediumQuality
//AVAssetExportPresetHighestQuality
DDCustomCameraManager.exportVideoFilePath(for: asset, type: .mp4, presetName: AVAssetExportPresetMediumQuality) { (path, err) in
//path默认存储在沙盒的tmp目录下
print(path)
}
//清除存储在tmp目录下的文件。需要就调用
DDCustomCameraManager.cleanMoviesFile()
}
}
<file_sep>//
// TextFieldVC.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class TextFieldVC: UIViewController {
@IBOutlet weak var input1: UITextField!
@IBOutlet weak var input2: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// input1 不需要设置代理
//支持最大长度限制
// 支持所有代理协议回调
// 支持输入抖动动画
//通过系统方法设置代理,只走协议方法
//不会走链式block回调
input1.placeholder("我是input1")
.addShouldBegindEditingBlock { (field) -> (Bool) in
return true
}
.addShouldChangeCharactersInRangeBlock { (field, range, text) -> (Bool) in
print("input1: \(text)")
return true
}
.maxLength(5)
.shake(true)
//通过系统方法设置代理,只走协议方法
//不会走链式block回调
input2.placeholder("我是input2")
.addShouldBegindEditingBlock({ (input) -> (Bool) in
print("不会调用")
return false
})
.addShouldChangeCharactersInRangeBlock { (input, range, text) -> (Bool) in
print("input2:不会调用调我:\(text)")
return true
}
.delegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
deinit {
print(self)
}
}
extension TextFieldVC: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.isEqual(input2) {
print("input2:调代理方法: \(string)")
return true
}
return false
}
}
<file_sep>//
// NavigationController.swift
// Example
//
// Created by USER on 2018/10/31.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
class NavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var shouldAutorotate: Bool {
return false
}
}
<file_sep># DDRouter -- 控制器之间的跳转路由
#### 1.常见的控制器之间的跳转
<img src="https://upload-images.jianshu.io/upload_images/2026287-fee2f66cec32dab4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=400 height=200 />
以上跳转存在哪些问题:<br/>
1.架构层面: 业务之间有耦合,界面之间也有耦合,a和b就紧紧的绑在一起<br/>
2.业务方面: 若控制器a和b不在一个业务模块中,就不利于模块间的拆分,将b剥离出,a中就会编译出错,无法实现业务的独立
#### 2.采用DDRouter的关系
<img src="https://upload-images.jianshu.io/upload_images/2026287-7eca5b3aaf0e1adc.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=400 height=180 />
#### 3.DDRouter的实现
采用字符串映射关系,实现对象创建。<br/>
核心代码
```
open func pushViewController(_ key: String, params: DDRouterParameter? = nil, animated: Bool = true, complete:((Any?)->())? = nil) {
let cls = classFromeString(key: key)
let vc = cls.init()
vc.params = params
vc.complete = complete
vc.hidesBottomBarWhenPushed = true
let topViewController = DDRouterUtils.currentTopViewController()
if topViewController?.navigationController != nil {
topViewController?.navigationController?.pushViewController(vc, animated: animated)
} else {
topViewController?.present(vc, animated: animated, completion: nil)
}
}
```
```
open func classFromeString(key: String) -> UIViewController.Type {
if key.contains(".") == true {
let clsName = key
let cls = NSClassFromString(clsName) as! UIViewController.Type
return cls
}
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
let clsName = namespace + "." + key
let cls = NSClassFromString(clsName) as! UIViewController.Type
return cls
}
```
#### 4.如何使用
* 1.key定义为对应的控制器名字
* 2.a->b 跳转 <br/>
```
let model = Model()
pushViewController("BViewController", params: ["model": model,"title": "hello"], animated: true) { (res) in
//上级界面回调
print(res)
}
```
#### 5.方法讲解
已经将DDRouter的方法全部扩展到UIViewController,更人性化的调用。
```
/// 路由入口 push
///
/// - Parameters:
/// - key: 定义的key
/// - params: 需要传递的参数
/// - parent: 是否是present显示
/// - animated: 是否需要动画
/// - complete: 上级控制器回调传值,只能层级传递
public func pushViewController(_ key: String, params: DDRouterParameter? = nil, animated: Bool = true, complete:((Any?)->())? = nil)
/// 路由入口 present
///
/// - Parameters:
/// - key: 路由key
/// - params: 参数
/// - animated: 是否需要动画
/// - complete: 上级控制器回调传值,只能层级传递
public func presentViewController(_ key: String, params: DDRouterParameter? = nil, animated: Bool = true, complete:((Any?)->())? = nil)
/// 正常的pop操作
///
/// - Parameters:
/// - vc: 当前控制器
/// - dismiss: true: dismiss退出,false: pop退出
/// - animated: 是否需要动画
public func pop(animated: Bool = true)
/// pop到指定的控制器
///
/// - Parameters:
/// - currentVC: 当前控制器
/// - toVC: 目标控制器对应的key
/// - animated: 是否需要动画
public func pop(ToViewController toVC: String, animated: Bool = true)
/// pop到根目录
///
/// - Parameters:
/// - currentVC: 当前控制器
/// - animated: 是否需要动画
public func pop(ToRootViewController animated: Bool = true)
/// dismiss操作
///
/// - Parameters:
/// - vc: 当前控制器
/// - animated: 是否需要动画
public func dismiss(_ animated: Bool = true)
```
并给每个控制器对象绑定一个params和complete属性,可任意的传值,以及控制器之间数据的回调
```
public var params: DDRouterParameter? {
set {
objc_setAssociatedObject(self, &DDRouterAssociatedKeys.paramsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &DDRouterAssociatedKeys.paramsKey) as? DDRouterParameter
}
}
/// 添加回调闭包,适用于反向传值,只能层级传递
public var complete: ((Any?)->())? {
set {
objc_setAssociatedObject(self, &DDRouterAssociatedKeys.completeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &DDRouterAssociatedKeys.completeKey) as? ((Any?) -> ())
}
}
```
#### 6.[查看demo更多场景使用](https://github.com/weiweilidd01/DDRouter.git)
#### 7.集成,已经上传至DDKit
<file_sep>
//
// DDCustomCameraResult.swift
// DDCustomCamera
//
// Created by USER on 2018/11/16.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import Photos
public struct DDCustomCameraResult {
//资源对象
public var asset: PHAsset?
//fale: 为图片, true为视屏
public var isVideo: Bool?
//图片 -- 若为视屏,则返回视屏首张图片
public var image: UIImage?
//时长
public var duration: String?
//从相册中选择照片, 如果此属性有值,上述属性都为空。
// public var albumArrs: [DDPhotoGridCellModel]?
//初始化方法
public init(asset: PHAsset?, isVideo: Bool? = false, image: UIImage?, duration: String? = "", albumArrs: [DDPhotoGridCellModel]? = nil) {
self.asset = asset
self.isVideo = isVideo
self.image = image
self.duration = duration
// self.albumArrs = albumArrs
}
}
<file_sep># DDMediator --模块(业务)间通信中间者
### 前言:
怎么去判断一个成功的模块化?<br/>
个人见解:每个模块相当于一个独立的项目,能够即插即用,脱离任何的关联,拉到任意的项目中能够正常编译和运行
```
本组件只适用于模块(业务)间的通信,作为一个中间媒介,减少模块间的耦合关系
控制器与控制器之间的解耦请使用DDRoute
```
[具体的使用请参照demo](https://github.com/weiweilidd01/DDMediator.git)
#### 1.app中常见的层级结构
<img src="https://upload-images.jianshu.io/upload_images/2026287-16311aa4a72a70a6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=400 height=500 />
#### 2.常见的业务之间关联关系
<img src="https://upload-images.jianshu.io/upload_images/2026287-5a014afade8e4d35.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=400 height=400 />
图中业务模块分类只是随便举例,模拟在业务间可能存在的耦合关系。<br/>
若业务众多,业务间实际的耦合关系可能会复杂。
#### 3.采用DDMediator业务之间的关系
<img src="https://upload-images.jianshu.io/upload_images/2026287-ea2695b2cafda3db.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=400 height=400 />
DDMediator作为一个中间者,协调各个模块之间的通信传输。<br/>
* 未采用中间媒介,业务间的传递关系为:<br/>
**A <---> B**<br/>
* 采用之后,关系为:<br/>
**A <---> Mediator <---> B**<br/>
* 从开发角度看,中间多了一层Mediator,感觉让人更复杂,觉得有点多余麻烦<br/>
* 从业务角度看,大大减少了不同业务间的耦合,更方便灵活的管理整个业务的版本迭代,对于产品线众多的情况,相同的业务可以更快速灵活的移植<br/>
* 对于多人开发同一产品,只需pod自己的业务模块即可,大大的提供xcode编译速度,大大减少github冲突问题<br/>
#### 4.模块化浅谈
* 1.什么情况下需要模块化<br/>
个人见解: 如果产品线单一,同一个产品人数不超过4人,个人觉得没必要模块化<br/>
* 2.在开发的哪个阶段模块化<br/>
个人见解: 在业务上线后,进入正常的迭代需求。再去着手模块化。若在项目的建立阶段,就统一模块化,会花费大量的时间和精力在一些基础劳动力上,大大影响写代码的心情,也会拖延前期产品规划的业务需求,前期开发对业务模块的划分还没有明确的清晰<br/>
#### 5.Mediator实现思路
核心代码非常简单,不到40行<br/>
采用了iOS大神[casatwy](https://github.com/casatwy/CTMediator.git)提出的Target-Action方式。<br/>
他的方案有个大痛点:就是没有callback回调。 业务场景:若A模块需求获取B模块的数据,需要B模块提供action响应此需求。网络请求存在延时回调。他的方案就不能解决<br/>
因此,本方案增加了callback,满足更多的业务需求场景。<br/>
将模块传的参数与callback统一封装到MediatorParams一个对象中传递。<br/>
```
extension DDMediator {
public func perform(Target targetName: String, actionName: String, params: MediatorParamDic?, complete: MediatorCallBack?) {
/// 获取targetClass字符串
let swiftModuleName = params?[kMediatorTargetModuleName] as? String
var targetClassString: String?
if (swiftModuleName?.count ?? 0) > 0 {
targetClassString = (swiftModuleName ?? "") + "." + "\(moduleName)_\(targetName)"
} else {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
targetClassString = namespace + "." + "Target_\(targetName)"
}
guard let classString = targetClassString else {
return
}
//获取Target对象
let targetClass = NSClassFromString(classString) as! NSObject.Type
let target = targetClass.init()
//获取Target对象中的方法Selector
let sel = Selector(actionName)
//定义回调block
let result: MediatorCallBack = { res in
complete?(res)
}
//创建参数model
let model = MediatorParams()
model.callBack = result
model.params = params
if target.responds(to: sel) == true {
target.perform(sel, with: model)
}
return
}
}
```
#### 7.模块间调用的流程图:
<img src="https://upload-images.jianshu.io/upload_images/2026287-68a3846717f57020.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=800 height=400 />
#### 8.集成,已经上传至DDKit
#### 9.总结:
**模块化只是一个架构思路,如何在不同模块之间建立一个桥梁。一千个开发者心中有一千个Mediator的方式。所完成的任务归根结底都是为了减少模块间的耦合,及处理模块间的数据传递途径**
<br/>
**本Demo方案不是最优,有更好的点子再采纳**
<file_sep>//
// BlankPageView.swift
// DDMall
//
// Created by cw on 2018/3/23.
// Copyright © 2018年 dd01. All rights reserved.
//
import SnapKit
import UIKit
/// EmptyDataManager用户管理dataSources
public class EmptyDataManager: NSObject {
public static let shared = EmptyDataManager()
public var dataSources: [EmptyDataConfig]?
}
public struct EmptyDataConfig {
public var title: String?
public var image: UIImage?
// Name的值请从0开始
public var name: EmptyDataConfig.Name
public init(name: EmptyDataConfig.Name, title: String?, image: UIImage?) {
self.name = name
self.title = title
self.image = image
}
}
extension EmptyDataConfig {
// Name的值请从0开始
public struct Name : Hashable, Equatable, RawRepresentable {
public var rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
}
public typealias EmptyDataClickBlock = (() -> Void)?
extension UIView {
private struct EmptyDataKey {
static var managerKey = "EmptyDateViewKey"
static var emptyDataSources = "emptyDataSources"
}
public var emptyDataSources: [EmptyDataConfig]? {
set (value) {
objc_setAssociatedObject(self, &EmptyDataKey.emptyDataSources, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &EmptyDataKey.emptyDataSources) as? [EmptyDataConfig]
}
}
fileprivate var blankView: EmptyDataView? {
set (value) {
objc_setAssociatedObject(self, &EmptyDataKey.managerKey, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &EmptyDataKey.managerKey) as? EmptyDataView
}
}
fileprivate var blankPageContainer: UIView {
var bView = self
for view in subviews {
if let view = view as? UIScrollView {
bView = view
}
}
return bView
}
/// scrollView或者view直接调用
///
/// - Parameters:
/// - type: 类型
/// - offSet: 中心点偏移的位置
/// - showImage: 是否显示图片
/// - showButton: 是否显示按钮
/// - btnTitle: 按钮的title
/// - hasData: 是否有数据
/// - clickAction: 按钮点击回调
public func emptyDataView(name: EmptyDataConfig.Name,
hasData: Bool,
offSet: CGPoint = CGPoint.zero,
showImage: Bool = true,
showButton: Bool = false,
btnTitle: String = "确定",
clickAction: EmptyDataClickBlock = nil) {
guard !hasData,
let dataSources = EmptyDataManager.shared.dataSources else {
cleanBlankView()
setScrollEnabled(true)
return
}
if blankView == nil {
blankView = EmptyDataView(frame: bounds)
blankView?.isUserInteractionEnabled = true
}
blankView?.isHidden = false
blankView?.backgroundColor = backgroundColor
if let blankView = blankView {
blankPageContainer.insertSubview(blankView, at: 0)
}
setScrollEnabled(false)
let result: EmptyDataClickBlock = {[weak self] in
self?.cleanBlankView()
self?.setScrollEnabled(true)
clickAction?()
}
blankView?.config(name: name,
sources: dataSources,
offSet: offSet,
showImage: showImage,
showButton: showButton,
btnTitle: btnTitle,
hasData: hasData,
clickAction: result)
}
private func cleanBlankView() {
blankView?.isHidden = true
blankView?.removeFromSuperview()
blankView = nil
}
private func setScrollEnabled(_ enabled: Bool) {
if let scroll = blankPageContainer as? UIScrollView {
scroll.isScrollEnabled = enabled
}
}
}
public class EmptyDataView: UIView {
public let blankImage = UIImageView(frame: CGRect.zero)
public let tipLabel = UILabel(frame: CGRect.zero)
public let operateButton = UIButton(type: .custom)
var clickBlock: EmptyDataClickBlock
override public init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func config(name: EmptyDataConfig.Name,
sources: [EmptyDataConfig],
offSet: CGPoint,
showImage: Bool,
showButton: Bool,
btnTitle: String,
hasData: Bool,
clickAction: EmptyDataClickBlock) {
guard !hasData else {
removeFromSuperview()
return
}
blankImage.isHidden = !showImage
addSubview(blankImage)
blankImage.snp.makeConstraints { make in
make.centerX.equalTo(snp.centerX).offset(offSet.x)
make.centerY.equalTo(snp.centerY).offset(-40 + offSet.y)
}
tipLabel.font = UIFont.systemFont(ofSize: 16)
tipLabel.textColor = #colorLiteral(red: 0.7215686275, green: 0.7215686275, blue: 0.7215686275, alpha: 1)
tipLabel.textAlignment = .center
addSubview(tipLabel)
tipLabel.snp.makeConstraints { make in
make.left.equalTo(snp.left).offset(20)
make.right.equalTo(snp.right).offset(-20)
if showImage {
make.top.equalTo(blankImage.snp.bottom).offset(10)
} else {
make.centerY.equalTo(snp.centerY).offset(-40 + offSet.y)
}
}
operateButton.isHidden = !showButton
addSubview(operateButton)
operateButton.snp.makeConstraints { make in
make.width.equalTo(200)
make.height.equalTo(44)
make.centerX.equalTo(snp.centerX).offset(offSet.x)
make.top.equalTo(tipLabel.snp.bottom).offset(40)
}
operateButton.setTitleColor( #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
operateButton.backgroundColor = #colorLiteral(red: 0, green: 0.5803921569, blue: 1, alpha: 1)
operateButton.setTitle(btnTitle, for: .normal)
operateButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
operateButton.addTarget(self, action: #selector(clickBtnAction), for: .touchUpInside)
clickBlock = clickAction
updateContent(name: name, dataSources: sources)
}
@objc func clickBtnAction() {
clickBlock?()
}
private func updateContent(name: EmptyDataConfig.Name, dataSources: [EmptyDataConfig]) {
print(name.rawValue)
if name.rawValue < dataSources.count && name.rawValue >= 0 {
let config = dataSources[name.rawValue]
blankImage.image = config.image
tipLabel.text = config.title
return
}
}
}
<file_sep>//
// PageTabsBaseController.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/19.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
/// PageTabsBaseController 此类为抽象类,只能继承,不能直接创建对象
open class PageTabsBaseController: UIViewController {
//记录content是否可以滑动,无需手动设置
public var canContentScroll = false
//记录tabsType,无需手动设置
public var tabsType: PageTabsType = .multiWork
public lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .plain)
return tableView
}()
override open func viewDidLoad() {
super.viewDidLoad()
setupUI()
NotificationCenter.default.addObserver(self, selector: #selector(notifactionContentOffsetZero), name: NSNotification.Name.kPageTabsContainerAllCotentoffsetZero, object: nil)
}
@objc public func notifactionContentOffsetZero() {
tableView.contentOffset = CGPoint.zero
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
tableView.reloadData()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension PageTabsBaseController {
//子类重写此方法,下拉刷新
@objc open func requesetPullData(currentIndex: Int) {}
//发送结束下拉刷新通知
public func endPullData() {
NotificationCenter.default.post(name: NSNotification.Name.kPageTabsContainerEndHeaderRefresh, object: nil)
}
}
extension PageTabsBaseController {
private func setupUI() {
view.backgroundColor = UIColor.white
view.addSubview(tableView)
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 34, right: 0)
}
}
}
extension PageTabsBaseController: UIScrollViewDelegate {
@objc open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if tabsType == .segmented {
canContentScroll = true
return
}
if canContentScroll == false {
// 这里通过固定contentOffset,来实现不滚动
scrollView.contentOffset = CGPoint.zero
} else if (scrollView.contentOffset.y <= 0) {
canContentScroll = false
// 通知容器可以开始滚动
NotificationCenter.default.post(name: NSNotification.Name.kPageTabsContainerCanScrollName, object: nil, userInfo: nil)
}
scrollView.showsVerticalScrollIndicator = canContentScroll
}
}
<file_sep>//
// ViewController.swift
// Example
//
// Created by USER on 2018/5/22.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
class ViewController: UIViewController {
var names = ["0、Toast 参照README 0.5.6",
"1、Alert",
"2、Sheet",
"3、pop",
"4、PhotoPicker",
"5、Refresh 请直接参照源码",
"6、Request",
"7、Hud 参照README 0.5.6",
"8、VideoPlayer",
"9、WebJS",
"10、player tableView",
"11、Request 请直接参照源码",
"12、PhotoBrowser 参照READNE O.5.9",
"13、CustomCamera",
"14、Scan",
"15、Mediator(用于不同模块间通信)",
"16、Router(页面之间的跳转)",
"17、MagicTextField(参照README 0.5.2)",
"18、EmptyDataView空白页占位图,参照README 0.5.7",
"19、DevelopConfig 使用",
"20、PageTabsController (参照README 0.6.0)",
"21、Picker (参照README 0.6.3)",
"22、Core(参照README 0.6.4)",
"23、CityList(参照README 0.6.16)",
"24、NumberSelect(数字选择)",
"25、Chainalbe(参照README 0.7.5)",
]
@IBOutlet weak var tbView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tbView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tbView.rowHeight = 80
setRightButtonItem(titles: ["关闭", "关闭"]) { (btn) in
}
setLeftButtonItem(title: "返回") { (btn) in
print("2222")
}
print(UIViewController.getTopViewController as Any)
title = "DDKit大全"
// // 先注册 (一般情况在app启动是就注册)scheme://module/page
// let error = Router.register(route: "Example://user/login") { routerURL in
// print(routerURL.route)
// print(routerURL.params ?? "")
// print("push loginViewController")
// let pushViewController = UIViewController()
// pushViewController.view.backgroundColor = UIColor.white
// return pushViewController
// }
// print(error ?? "")
//
// let error2 = Router.register(route: "Example://user/present") { routerURL in
// print(routerURL.route)
// print(routerURL.params ?? "")
// print("present ViewController")
// let storyBoard = UIStoryboard(name: "Main", bundle: nil)
// let presentViewController = storyBoard.instantiateViewController(withIdentifier: "PresentController")
// return presentViewController
// }
// print(error2 ?? "")
//
// //注册模块 (一般情况在app启动是就注册)
// ServiceManager.registerAll(serviceMap: ["AccountServiceAPI": "AccountService"])
//
// //模块实例
// let accountModule: AccountServiceAPI? = API()
// accountModule?.register(userName: "", passWord: "", verifyCode: "", complete: { _ in
//
// })
// accountModule?.login(userName: "", passWord: "", complete: { _ in
//
// })
// accountModule?.logout()
}
private func pop(_ indexPath: IndexPath) {
var items = [MenuItem]()
let commodityManageItem = MenuItem(title: NSLocalizedString("分類管理", comment: ""), image: nil, isShowRedDot: false) {
}
items.append(commodityManageItem)
let addCommodityItem = MenuItem(title: NSLocalizedString("添加商品", comment: ""), image: nil, isShowRedDot: false) {
}
items.append(addCommodityItem)
let menuViewController = MenuViewController(items: items)
if let cell = tbView.cellForRow(at: indexPath) {
menuViewController.popoverPresentationController?.sourceView = cell
menuViewController.popoverPresentationController?.sourceRect = cell.bounds
}
present(menuViewController, animated: true, completion: nil)
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if let cell = cell {
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = names[indexPath.row]
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// if indexPath.row == 0 {
// Router.push(urlStr: "Example://user/login?username=dd01&password=<PASSWORD>")
// } else if indexPath.row == 1 {
// Router.present(urlStr: "Example://user/present") {
//
// }
// } else if indexPath.row == 2 {
// print("公共模块")
// } else
if indexPath.row == 0 {
// navigationController?.pushViewController(ToastVC(style: .grouped), animated: true)
return
} else if indexPath.row == 1 {
navigationController?.pushViewController(AlertVC(), animated: true)
} else if indexPath.row == 2 {
navigationController?.pushViewController(SheetTableVC(), animated: true)
} else if indexPath.row == 3 {
pop(indexPath)
} else if indexPath.row == 4 {
DDPhotoPickerManager.show { (arr) in
}
} else if indexPath.row == 5 {
// navigationController?.pushViewController(NextVC(style: .grouped), animated: true)
return
} else if indexPath.row == 6 {
performSegue(withIdentifier: "RequestTableVC", sender: nil)
} else if indexPath.row == 7 {
navigationController?.pushViewController(HudVC(), animated: true)
return
} else if indexPath.row == 8 {
navigationController?.pushViewController(PlayerViewController(), animated: true)
} else if indexPath.row == 9 {
navigationController?.pushViewController(WKWeb(), animated: true)
} else if indexPath.row == 10 {
navigationController?.pushViewController(TablePlayerController(), animated: true)
} else if indexPath.row == 11 {
// navigationController?.pushViewController(PhotoTableVC(), animated: true)
return
} else if indexPath.row == 12 {
return
// navigationController?.pushViewController(BrowserController(), animated: true)
} else if indexPath.row == 13 {
return
// navigationController?.pushViewController(CustomPhotoController(), animated: true)
} else if indexPath.row == 14 {
navigationController?.pushViewController(ScanController(), animated: true)
} else if indexPath.row == 15 {
navigationController?.pushViewController(MediatorController(), animated: true)
} else if indexPath.row == 16 {
navigationController?.pushViewController(RouterController(), animated: true)
} else if indexPath.row == 17 {
return
} else if indexPath.row == 18 {
return
} else if indexPath.row == 19 {
navigationController?.pushViewController(DevelopConfigVC(nibName: "DevelopConfigVC", bundle: nil), animated: true)
} else if indexPath.row == 20 {
return
} else if indexPath.row == 21 {
Picker(stringPickerOrigin: view, rows: ["白起","李白","曹操","妲己", "貂蝉", "刘备"], initialSelection: 0) { (selectedIndex, value) in
// print(selectedIndex)
// print(value)
}
return
} else if indexPath.row == 22 {
return
} else if indexPath.row == 23 {
let vc = CityListViewController(style: .grouped)
vc.hotCitys = ["深圳对方水电费健康","广州", "北京", "上海"]
vc.currentCity = "深圳"
vc.selectedComplete = { city in
// print(city)
}
vc.title = "城市选择"
navigationController?.pushViewController(vc, animated: true)
return
} else if indexPath.row == 24 {
navigationController?.pushViewController(NumberSelectVC(), animated: true)
return
} else if indexPath.row == 25 {
return
}
}
}
<file_sep>//
// PageSegmentViewCell.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/18.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class PageSegmentViewCell: UICollectionViewCell {
public lazy var titleLabel: UILabel = {
let titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textAlignment = .center
return titleLabel
}()
public lazy var bottomLine: UIView = {
let bottomLine = UIView()
bottomLine.clipsToBounds = true
bottomLine.backgroundColor = UIColor.red
return bottomLine
}()
public var lineHeight: CGFloat = 2.0
public var lineWidth: CGFloat = 0.0
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(titleLabel)
contentView.addSubview(bottomLine)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutFrame()
}
private func layoutFrame() {
let lineW = lineWidth == 1.0 ? bounds.width : lineWidth
let lineFrame = CGRect(x: (bounds.width - lineW) / 2.0, y: bounds.height - lineHeight, width: lineW, height: lineHeight)
bottomLine.frame = lineFrame
var titleFrame = bounds
titleFrame.size.height = titleFrame.height - lineHeight
titleLabel.frame = titleFrame
}
func displayCell(title: String,
font: UIFont,
itemTitleSelectedColor: UIColor,
itemTitleNormalColor: UIColor,
itemBackgroudNormalColor: UIColor,
itemBackgroudSelectedColor: UIColor,
bottomLineWidth: CGFloat,
bottomLineHeight: CGFloat,
bottomLineColor: UIColor,
currentIndex: Int,
indexPath: IndexPath) {
titleLabel.text = title
titleLabel.font = font
titleLabel.textColor = (currentIndex == indexPath.row ? itemTitleSelectedColor : itemTitleNormalColor)
if currentIndex == indexPath.row {
bottomLine.isHidden = false
bottomLine.backgroundColor = bottomLineColor
lineWidth = bottomLineWidth
lineHeight = bottomLineHeight
setNeedsLayout()
layoutIfNeeded()
} else {
bottomLine.isHidden = true
}
}
}
<file_sep>//
// DDVideoPlayerTipsView.swift
// DDKit
//
// Created by leo on 2018/11/1.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
import SnapKit
public class DDVideoPlayerTipsView: UIView {
lazy private var contentLab: UILabel = {
let lab = UILabel()
lab.text = "您正在使用非wifi网络"
lab.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
lab.font = UIFont.systemFont(ofSize: 12)
lab.textAlignment = .center
return lab
}()
lazy private var continuePlayBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("点击继续播放", for: .normal)
btn.setTitleColor(#colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1), for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
return btn
}()
public var continuePlayBtnCallBack: (()->())?
public override init(frame : CGRect) {
super.init(frame : frame)
setupUI()
}
public convenience init() {
self.init(frame:CGRect.zero)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override public func layoutSubviews() {
super.layoutSubviews()
}
}
private extension DDVideoPlayerTipsView {
func setupUI() {
addSubview(contentLab)
addSubview(continuePlayBtn)
continuePlayBtn.addTarget(self, action: #selector(continueBtnAction(btn:)), for: .touchUpInside)
contentLab.snp.makeConstraints { (make) in
make.left.right.equalTo(0)
make.top.equalTo(20)
}
continuePlayBtn.snp.makeConstraints { (make) in
make.width.equalTo(100)
make.height.equalTo(30)
make.top.equalTo(self.contentLab.snp_bottomMargin).offset(10)
make.centerX.equalTo(self)
}
}
@objc func continueBtnAction(btn: UIButton) {
if let callBack = continuePlayBtnCallBack {
isHidden = true
callBack()
}
}
}
<file_sep>//
// DevelopConfigVC.swift
// Example
//
// Created by shenzhen-dd01 on 2018/12/17.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
import DDKit
class DevelopConfigVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
developConfigUse()
}
func developConfigUse() {
let environments = ["开发环境": "http://hotel-api.dadi01.net",
"预发布环境": "http://hotel-api.dadi01.net1",
"生产环境": "http://hotel-api.dadi01.net2"]
DevelopManager.registerHost(environments: environments,
notificationName: "DevelopmentsNotification")
DevelopManager.startNetworkMonitoring { (status) in
//网络状态发生改变...
}
}
@IBAction func switchHostAction(_ sender: Any) {
DevelopManager.showSettingsVC(currentHost: "http://hotel-api.dadi01.net") {
/*
切换地址后执行:
1、退出登录
2、切换Tabbar
3、清除缓存
....
*/
}
}
}
<file_sep>//
// NextVC.swift
// Example
//
// Created by senyuhao on 2018/7/2.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
import MJRefresh
class NextVC: UITableViewController {
private var items = ["gif-header", "gif-footer", "gif-nodata"]
private var index = 0
override init(style: UITableView.Style) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
tableView.mj_header = MJRefreshGifHeader.inits(gifName: "mj1", handler: { [weak self] in
self?.resetNormal()
})
tableView.mj_footer = MJRefreshBackGifFooter.inits(gifName: "mj1", handler: { [weak self] in
self?.resetNormal()
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") {
cell.textLabel?.text = items[indexPath.row]
return cell
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
tableView.mj_header.beginRefreshing()
} else if indexPath.row == 1 {
index = 1
tableView.mj_footer.beginRefreshing()
} else if indexPath.row == 2 {
index = 2
tableView.mj_footer.beginRefreshing()
}
}
}
extension NextVC {
private func resetNormal() {
let deadLineTime = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadLineTime) { [weak self] in
self?.tableView.mj_footer.endRefreshing()
if self?.index == 1 {
self?.tableView.mj_header.endRefreshing()
} else {
self?.tableView.mj_footer.endRefreshingWithNoMoreData()
}
}
}
}
<file_sep>
//
// UIApplication+Permissions.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/18.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
extension UIApplication {
// MARK: - ---获取相册权限
static func authorizePhoto(_ comletion:@escaping (Bool) -> Void) {
let granted = PHPhotoLibrary.authorizationStatus()
switch granted {
case PHAuthorizationStatus.authorized:
comletion(true)
case PHAuthorizationStatus.denied, PHAuthorizationStatus.restricted:
comletion(false)
case PHAuthorizationStatus.notDetermined:
PHPhotoLibrary.requestAuthorization({ (status) in
DispatchQueue.main.async {
comletion(status == .authorized ? true:false)
}
})
}
}
// MARK: - --相机权限
static func authorizeCamera(_ comletion: @escaping (Bool) -> Void ) {
let granted = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch granted {
case AVAuthorizationStatus.authorized:
comletion(true)
case AVAuthorizationStatus.denied:
comletion(false)
case AVAuthorizationStatus.restricted:
comletion(false)
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) in
DispatchQueue.main.async {
if granted {
comletion(granted)
}
}
})
}
}
// MARK: - --麦克风授权
static func authorizeMicrophone(_ comletion: @escaping (Bool) -> Void ) {
let granted = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
switch granted {
case AVAuthorizationStatus.authorized:
comletion(true)
case AVAuthorizationStatus.denied:
comletion(false)
case AVAuthorizationStatus.restricted:
comletion(false)
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.audio, completionHandler: { (granted: Bool) in
DispatchQueue.main.async {
if granted {
comletion(granted)
}
}
})
}
}
/// 是否有相册访问权限
///
/// - Returns: bool
static func isHaveAuthorizePhoto() -> Bool {
let status = PHPhotoLibrary.authorizationStatus()
if status == .authorized {
return true
}
return false
}
/// 是否有相册访问权限
///
/// - Returns: bool
static func isHaveAuthorizeMicrophone() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
if status == .authorized {
return true
}
return false
}
/// 是否有相册访问权限
///
/// - Returns: bool
static func isHaveAuthorizeCamera() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if status == .authorized {
return true
}
return false
}
}
<file_sep>//
// CHLogListCell.swift
// CHLog
//
// Created by wanggw on 2018/6/30.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
import UIKit
class CHLogListCell: UITableViewCell {
private var titleLabel = UILabel()
// MARK: - init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
accessoryType = .disclosureIndicator
backgroundColor = UIColor.groupTableViewBackground
contentView.backgroundColor = UIColor.groupTableViewBackground
if (self.responds(to: #selector(setter: UIView.layoutMargins))) {
self.layoutMargins = UIEdgeInsets.zero
}
if (self.responds(to: #selector(setter: UITableViewCell.separatorInset))) {
self.separatorInset = UIEdgeInsets.zero
}
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: -
private func setupUI() {
titleLabel.frame = contentView.bounds
titleLabel.font = UIFont.systemFont(ofSize: 12)
titleLabel.textColor = UIColor.black
titleLabel.numberOfLines = 0
contentView.addSubview(titleLabel)
}
// MARK: - updateContent
public func updateContent(response: CHLogItem) {
titleLabel.text = response.requstType
titleLabel.textColor = response.isRequestError ? UIColor.red : UIColor.black
titleLabel.frame = CGRect(x: 60, y: 0, width: self.bounds.size.width - 75, height: self.bounds.size.height)
}
}
<file_sep>//
// UIView+Responder.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/21.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
// MARK: - 获取view上的当前控制器
extension UIView {
public func viewController() -> UIViewController? {
var next: UIResponder?
next = self.next
repeat {
if (next as? UIViewController) != nil {
return next as? UIViewController
} else {
next = next?.next
}
} while next != nil
return UIViewController()
}
}
<file_sep>//
// UICollectionView+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UICollectionView {
@discardableResult
func collectionViewLayout(_ layout: UICollectionViewLayout) -> Self {
collectionViewLayout = layout
return self
}
@discardableResult
@available(iOS 10.0, *)
func isPrefetchingEnabled(_ enabled: Bool) -> Self {
isPrefetchingEnabled = enabled
return self
}
@discardableResult
@available(iOS 11.0, *)
func dragInteractionEnabled(_ enabled: Bool) -> Self {
dragInteractionEnabled = enabled
return self
}
@discardableResult
@available(iOS 11.0, *)
func reorderingCadence(_ cadence: UICollectionView.ReorderingCadence) -> Self {
reorderingCadence = cadence
return self
}
@discardableResult
func backgroundView(_ view: UIView?) -> Self {
backgroundView = view
return self
}
@discardableResult
func registerCell(_ cellClass: AnyClass?, ReuseIdentifier identifier: String) -> Self {
register(cellClass, forCellWithReuseIdentifier: identifier)
return self
}
@discardableResult
func registerCellNib(_ nib: UINib?, ReuseIdentifier identifier: String) -> Self {
register(nib, forCellWithReuseIdentifier: identifier)
return self
}
@discardableResult
func registerSupplementaryView(_ viewClass: AnyClass?,forSupplementaryViewOfKind kind: String, ReuseIdentifier identifier: String) -> Self {
register(viewClass, forSupplementaryViewOfKind: kind, withReuseIdentifier: identifier)
return self
}
@discardableResult
func registerSupplementaryViewNib(_ nib: UINib?,forSupplementaryViewOfKind kind: String, ReuseIdentifier identifier: String) -> Self {
register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: identifier)
return self
}
@discardableResult
func allowsSelection(_ bool: Bool) -> Self {
allowsSelection = bool
return self
}
@discardableResult
func allowsMultipleSelection(_ bool: Bool) -> Self {
allowsMultipleSelection = bool
return self
}
@discardableResult
func reload() -> Self {
reloadData()
return self
}
}
// MARK: - UICollectionViewDataSource
public extension UIKitChainable where Self: UICollectionView {
@discardableResult
public func addNumberOfItemsInSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ section: Section)->(Int))) -> Self {
setNumberOfItemsInSectionBlock(handler)
return self
}
@discardableResult
public func addCellForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(UICollectionViewCell))) -> Self {
setCellForItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addNumberOfSectionsBlock(_ handler: @escaping((_ collectionView: UICollectionView)->(Int))) -> Self {
setNumberOfSectionsBlock(handler)
return self
}
@discardableResult
public func addViewForSupplementaryElementOfKindAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ kind: ElementKind, _ indexPath: IndexPath)->(UICollectionReusableView))) -> Self {
setViewForSupplementaryElementOfKindAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addCanMoveItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) -> Self {
setCanMoveItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addMoveItemAtSourceIndexPathToDestinationIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ sourceIndexPath: IndexPath, _ destinationIndexPath: IndexPath)->())) -> Self {
setMoveItemAtSourceIndexPathToDestinationIndexPathBlock(handler)
return self
}
@discardableResult
public func addIndexTitlesBlock(_ handler: @escaping((_ collectionView: UICollectionView)->([String]?))) -> Self {
setIndexTitlesBlock(handler)
return self
}
@discardableResult
public func addIndexPathForIndexTitleAtIndexBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ title: String, _ index: Int)->(IndexPath))) -> Self {
setIndexPathForIndexTitleAtIndexBlock(handler)
return self
}
}
// MARK: - UICollectionViewDelegate
public extension UIKitChainable where Self: UICollectionView {
@discardableResult
public func addShouldHighlightItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) -> Self {
setShouldHighlightItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addDidHighlightItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) -> Self {
setDidHighlightItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addDidUnhighlightItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) -> Self {
setDidUnhighlightItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addShouldSelectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) -> Self {
setShouldSelectItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addShouldDeselectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) -> Self {
setShouldDeselectItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addDidSelectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) -> Self {
setDidSelectItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addDidDeselectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) -> Self {
setDidDeselectItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addWillDisplayCellforItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ cell: UICollectionViewCell, _ indexPath: IndexPath)->())) -> Self {
setWillDisplayCellforItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addWillDisplaySupplementaryViewForElementKindBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ view: UICollectionReusableView, _ elementKind: String, _ indexPath: IndexPath)->())) -> Self {
setWillDisplaySupplementaryViewForElementKindBlock(handler)
return self
}
@discardableResult
public func addDidEndDisplayingCellForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ cell: UICollectionViewCell,_ indexPath: IndexPath)->())) -> Self {
setDidEndDisplayingCellForItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addDidEndDisplayingSupplementaryViewForElementOfKindBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ view: UICollectionReusableView, _ elementKind: String, _ indexPath: IndexPath)->())) -> Self {
setDidEndDisplayingSupplementaryViewForElementOfKindBlock(handler)
return self
}
@discardableResult
public func addShouldShowMenuForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) -> Self {
setShouldShowMenuForItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addCanPerformActionforItemAtIndexPathWithSenderBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ action: Selector,_ indexPath: IndexPath, _ sender: Any?)->(Bool))) -> Self {
setCanPerformActionforItemAtIndexPathWithSenderBlock(handler)
return self
}
@discardableResult
public func addPerformActionforItemAtIndexPathWithSenderBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ action: Selector,_ indexPath: IndexPath, _ sender: Any?)->())) -> Self {
setPerformActionforItemAtIndexPathWithSenderBlock(handler)
return self
}
}
// MARK: - UICollectionViewDelegateFlowLayout
public extension UIKitChainable where Self: UICollectionView {
@discardableResult
public func addLayoutCollectionViewLayoutSizeForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ indexPath: IndexPath)->(CGSize))) -> Self {
setLayoutCollectionViewLayoutSizeForItemAtIndexPathBlock(handler)
return self
}
@discardableResult
public func addLayoutCollectionViewLayoutInsetForSectionAtSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(UIEdgeInsets))) -> Self {
setLayoutCollectionViewLayoutInsetForSectionAtSectionBlock(handler)
return self
}
@discardableResult
public func addLayoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGFloat))) -> Self {
setLayoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionBlock(handler)
return self
}
@discardableResult
public func addLayoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGFloat))) -> Self {
setLayoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionBlock(handler)
return self
}
@discardableResult
public func addLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGSize))) -> Self {
setLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock(handler)
return self
}
@discardableResult
public func addLayoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGSize))) -> Self {
setLayoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionBlock(handler)
return self
}
}
<file_sep>//
// DDPhotoGridCellModel.swift
// Photo
//
// Created by USER on 2018/10/25.
// Copyright © 2018年 leo. All rights reserved.
//
import UIKit
import Photos
public enum DDAssetMediaType: Int {
case unknown
case image
case gif
case livePhoto
case video
case audio
}
public class DDPhotoGridCellModel: NSObject {
//资源对象
public var asset: PHAsset
//缩略图 -- 若为视屏,则返回视屏首张图片
public var image: UIImage?
//视屏时长
public var duration: String = ""
//当前资源类型
public var type: DDAssetMediaType?
//MARK: -- 下述属性调用无需关心
//当前cell的indexpath
public var indexPath: IndexPath?
//是否选择当前图片
public var isSelected: Bool = false
//是否是gif
public var isGIF: Bool = false
//asset唯一标识符
public var localIdentifier: String = ""
public var index: Int = 0
init(asset: PHAsset, type: DDAssetMediaType, duration: String) {
self.asset = asset
self.type = type
self.duration = duration
self.localIdentifier = asset.localIdentifier
if type == .gif {
self.isGIF = true
} else {
self.isGIF = false
}
}
}
<file_sep>//
// CountDownTimer.swift
// CountDownTimerDemo
//
// Created by USER on 2018/12/7.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
extension NSObject {
/*
1、 针对于NSTimer定时器的生命周期管理的不方便性,若管理不当,容易造成循环引用,因此封装了一个基于GCDTimer的定时器,常用于验证码等倒计时的功能
2、 当用户进入后台,此定时器依然生效
*/
// 计时器只在程序active时工作,当用户按起HOME键时,计时器停止,因为当程序进入后台时,这个线程就被挂起不工作,当然计时器就会被“暂停”。
// 系统原理: iOS为了让设备尽量省电,减少不必要的开销,保持系统流畅,因而对后台机制采用“假后台”模式。一般开发者开发出来的应用程序后台受到以下限制:
// 1.用户按Home之后,App转入后台进行运行,此时拥有180s后台时间(iOS7)或者600s(iOS6)运行时间可以处理后台操作
// 2.当180S或者600S时间过去之后,可以告知系统未完成任务,需要申请继续完成,系统批准申请之后,可以继续运行,但总时间不会超过10分钟(系统提供beginBackgroundTaskWithExpirationHandler方法)。
// 3.当10分钟时间到之后,无论怎么向系统申请继续后台,系统会强制挂起App,挂起所有后台操作、线程,直到用户再次点击App之后才会继续运行。
/// 倒计时
/// 基于GCDTimers实现
/// - Parameters:
/// - timeInterval: 时间间隔
/// - handler: 每次时间间隔的回调
@discardableResult static func dispathTimer(timeInterval: Double = 1.0, handler:@escaping (DispatchSourceTimer?)->()) -> DispatchSourceTimer {
let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
timer.schedule(deadline: .now(), repeating: timeInterval)
timer.setEventHandler {
DispatchQueue.main.async {
handler(timer)
}
}
timer.resume()
// beginBackgroundTaskWithExpirationHandler是向系统发出申请延长后台不被挂起时间
// endBackgroundTask是告诉系统已完事,可以结束了,
var bgTask: UIBackgroundTaskIdentifier?
bgTask = UIApplication.shared.beginBackgroundTask {
DispatchQueue.main.async(execute: {
if bgTask != UIBackgroundTaskInvalid {
if var task = bgTask {
UIApplication.shared.endBackgroundTask(task)
task = UIBackgroundTaskInvalid
}
}
})
}
return timer
}
}
/* 使用demo
NSObject.dispathTimer(timeInterval: 1) {[weak self] (timer) in
print("~~~~~~~~\(String(describing: self?.total))~~~~~~~~~~~~")
guard let strongSelf = self else {
timer?.cancel()
return
}
strongSelf.total = strongSelf.total - 1
if strongSelf.total < 0 {
timer?.cancel()
return
}
strongSelf.lab.text = "\(strongSelf.total)"
}
*/
<file_sep>//
// EBGifTool.swift
// EatojoyBiz
//
// Created by senyuhao on 23/03/2018.
// Copyright © 2018 dd01. All rights reserved.
//
import MobileCoreServices
import UIKit
class EBGifTool: NSObject {
public class func loadingGif(gifName: String, handler: @escaping (_ images: [UIImage]?, _ duration: Double) -> Void) {
if let path = Bundle.main.path(forResource: gifName, ofType: "gif") {
let data = NSData(contentsOfFile: path)
let imagesources = imageSourceFromData(data: data)
let images = imagesFromImageSource(sources: imagesources)
if let images = images, let imageinfo = images.images {
handler(imageinfo, images.duration)
} else {
handler(nil, 0.0)
}
} else {
handler(nil, 0.0)
}
}
private class func imageSourceFromData(data: NSData?) -> CGImageSource? {
if let data = data {
let options = [kCGImageSourceShouldCache: true, kCGImageSourceTypeIdentifierHint: kUTTypeGIF] as [CFString: Any]
return CGImageSourceCreateWithData(data, options as CFDictionary)
}
return nil
}
private class func imagesFromImageSource(sources: CGImageSource?) -> (images: [UIImage]?, duration: Double)? {
if let sources = sources {
let count = CGImageSourceGetCount(sources)
var images = [UIImage]()
var gifDuration = 0.0
let options = [kCGImageSourceShouldCache: true, kCGImageSourceTypeIdentifierHint: kUTTypeGIF] as [CFString: Any]
for i in 0 ..< count {
guard let imageRef = CGImageSourceCreateImageAtIndex(sources, i, options as CFDictionary) else {
return (images, gifDuration)
}
if count == 1 {
gifDuration = Double.infinity
} else {
guard let properties = CGImageSourceCopyPropertiesAtIndex(sources, i, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
let frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else {
return (images, gifDuration)
}
gifDuration += frameDuration.doubleValue
let image = UIImage(cgImage: imageRef, scale: UIScreen.main.scale, orientation: .up)
images.append(image)
}
}
return (images, gifDuration)
}
return nil
}
}
<file_sep>//
// Foundation+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
extension NSObject: Chainable {}
<file_sep>//
// DevelopInputConfigCell.swift
// Hotel
//
// Created by senyuhao on 2018/12/3.
// Copyright © 2018 HK01. All rights reserved.
//
import UIKit
import SnapKit
class DevelopInputConfigCell: UITableViewCell {
public var inputBlock: ((_ value: String, _ isBeginEdit: Bool) -> Void)?
private var textField = UITextField(frame: .zero)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configView()
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configView()
}
public func updateCell(_ sender: String) {
textField.text = sender
}
private func configView() {
textField.placeholder = "输入环境"
textField.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
textField.font = UIFont.systemFont(ofSize: 16)
textField.clearButtonMode = .whileEditing
textField.addTarget(self, action: #selector(textFieldDidBeginAction(_:)), for: .editingDidBegin)
textField.addTarget(self, action: #selector(textFieldChangedAction(_:)), for: .editingChanged) //allEditingEvents
addSubview(textField)
textField.snp.makeConstraints { make in
make.left.equalTo(self).offset(16)
make.right.equalTo(self).offset(-16)
make.top.equalTo(self)
make.bottom.equalTo(self)
}
}
@objc private func textFieldDidBeginAction(_ sender: UITextField) {
let value = textField.text ?? ""
let settingValue = value.count > 0 ? value : "http://"
textField.text = settingValue
inputBlock?(settingValue, true)
}
@objc private func textFieldChangedAction(_ sender: UITextField) {
inputBlock?(sender.text ?? "", false)
}
}
<file_sep>//
// EBAlert.swift
// EatojoyBiz
//
// Created by senyuhao on 20/03/2018.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
extension AlertView {
// 设置Title
private func configTitle(title: String?, height: CGFloat) -> CGFloat {
var now = height
if let title = title {
addSubview(lbFromInfo(rect: CGRect(x: 0, y: height, width: frame.size.width, height: 24), title: title, font: 18))
now += 24
}
return now
}
// 设置subTitle
private func configSubTitle(subTitle: NSMutableAttributedString?, height: CGFloat) -> CGFloat {
var now = height
if let subTitle = subTitle {
let label = lbFromInfo(rect: CGRect(x: 15, y: now + 10, width: frame.size.width - 30, height: 0), title: "", font: 16)
label.attributedText = subTitle
let size = label.sizeThatFits(CGSize(width: frame.size.width - 30, height: 0))
label.frame = CGRect(x: 15, y: now + 10, width: frame.size.width - 30, height: size.height)
addSubview(label)
now += size.height + 10
}
return now
}
}
class AlertView: UIView {
deinit {
NotificationCenter.default.removeObserver(self)
}
public var alertBlock: ((Int) -> Void)?
public var inputBlock: ((String) -> Void)?
convenience init(info: AlertInfo, handler: @escaping (_ tag: Int) -> Void, inputHandler: @escaping (_ value: String) -> Void) {
self.init(info: info, handler: handler)
inputBlock = inputHandler
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardShow(notification: Notification) {
if let userInfo = notification.userInfo as Dictionary? {
let keyboardRec = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
if let heightValue = keyboardRec?.size.height {
let offSetY = heightValue + self.frame.height / 2 - self.center.y
if offSetY > 0 {
self.transform = CGAffineTransform(translationX: 0, y: -(offSetY + 10))
}
}
}
}
@objc func keyboardHide(notification: Notification) {
self.transform = CGAffineTransform.identity
}
convenience init(info: AlertInfo, handler: @escaping (_ tag: Int) -> Void) {
self.init()
backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
alertBlock = handler
frame = CGRect(x: 0, y: 0, width: 280, height: 120)
var height: CGFloat = 20
height = configTitle(title: info.title, height: height)
height = configSubTitle(subTitle: info.subTitle, height: height)
if let content = info.content, !content.isEmpty {
let contentLb = lbFromInfo(rect: .zero, title: content, font: 15)
contentLb.textColor = Alert.shared.contentColor
contentLb.textAlignment = info.subTitle != nil ? .left : Alert.shared.contentAlign
let size = contentLb.sizeThatFits(CGSize(width: frame.size.width - 30, height: 0))
contentLb.frame = CGRect(x: 15, y: height + 10, width: frame.size.width - 30.0, height: size.height)
addSubview(contentLb)
height += size.height + 10
}
if info.needInput != nil {
addSubview(fieldInfo(rect: CGRect(x: 20, y: height + 10, width: frame.size.width - 40, height: 36)))
height += 46
}
addSubview(lineFromRect(rect: CGRect(x: 0, y: height + 18, width: frame.size.width, height: 0.5)))
height += 18.5
var bnwidth: CGFloat = 0
if let cancel = info.cancel, !cancel.isEmpty {
bnwidth = frame.size.width / 2
let cancelBn = bnFromInfo(rect: CGRect(x: 0, y: height, width: bnwidth, height: 48), tag: 0, title: cancel)
cancelBn.setTitleColor(Alert.shared.cancelColor, for: .normal)
addSubview(cancelBn)
addSubview(lineFromRect(rect: CGRect(x: bnwidth, y: height, width: 0.5, height: 48)))
bnwidth += 0.5
}
addSubview(bnFromInfo(rect: CGRect(x: bnwidth, y: height, width: frame.size.width - bnwidth, height: 48), tag: 1, title: info.sure))
frame = CGRect(x: 0, y: 0, width: frame.size.width, height: height + 48)
clipsToBounds = true
layer.cornerRadius = 7
}
public func show(targetView: UIView) {
if let window = targetView.window {
if !existView(container: window) {
showOnView(container: window)
}
} else {
if let window = UIApplication.shared.keyWindow {
if !existView(container: window) {
showOnView(container: window)
}
}
}
}
private func existView(container: UIView) -> Bool {
var exist = false
for item in container.subviews where item.tag == NSIntegerMax - 1 {
exist = true
}
return exist
}
public func showOnView(container: UIView) {
let backView = UIView(frame: container.frame)
backView.tag = NSIntegerMax - 1
let maskView = UIView(frame: backView.frame)
maskView.alpha = 0
maskView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
backView.addSubview(maskView)
backView.addSubview(self)
center = backView.center
container.addSubview(backView)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
maskView.addGestureRecognizer(tap)
UIView.animate(withDuration: 0.3,
animations: {
maskView.alpha = 0.5
}, completion: { _ in
})
}
@objc private func tapAction() {
endEditing(true)
}
private func hiddenAction() {
UIView.animate(withDuration: 0.3,
animations: {
self.alpha = 0.0
}, completion: { finished in
if finished {
let backview = self.superview
if backview?.tag == NSIntegerMax - 1 {
backview?.removeFromSuperview()
}
}
})
}
// MARK: - 界面元素方法生成
private func lineFromRect(rect: CGRect) -> UIView {
let label = UIView(frame: rect)
label.autoresizingMask = .flexibleWidth
label.backgroundColor = #colorLiteral(red: 0.8666666667, green: 0.8666666667, blue: 0.8666666667, alpha: 1)
return label
}
private func bnFromInfo(rect: CGRect, tag: Int, title: String) -> UIButton {
let btn = UIButton(type: .system)
btn.autoresizingMask = .flexibleWidth
btn.frame = rect
btn.tag = tag
btn.setTitle(title, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
btn.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
btn.setTitleColor(Alert.shared.sureColor, for: .normal)
btn.addTarget(self, action: #selector(dismiss(_ : )), for: .touchUpInside)
btn.clipsToBounds = true
return btn
}
private func lbFromInfo(rect: CGRect, title: String, font: CGFloat) -> UILabel {
let label = UILabel(frame: rect)
label.text = title
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: font)
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textColor = Alert.shared.titleColor
label.autoresizingMask = .flexibleWidth
return label
}
private func fieldInfo(rect: CGRect) -> UITextField {
let field = UITextField(frame: rect)
field.placeholder = NSLocalizedString("請輸入", comment: "")
field.font = UIFont.systemFont(ofSize: 15)
field.addTarget(self, action: #selector(textFieldChanged( _ :)), for: .editingChanged)
field.borderStyle = .roundedRect
return field
}
@objc func textFieldChanged(_ sender: UITextField) {
if let text = sender.text, let input = inputBlock {
input(text)
}
}
@objc private func dismiss(_ sender: UIButton) {
if inputBlock != nil, let value = Alert.shared.inputValue, !value.isEmpty {
alertBlock?(sender.tag)
hiddenAction()
return
}
if inputBlock == nil, Alert.shared.inputValue == nil {
alertBlock?(sender.tag)
hiddenAction()
return
}
if sender.tag == 0 {
alertBlock?(sender.tag)
hiddenAction()
Alert.shared.inputValue = nil
}
}
}
public struct AlertInfo {
var title: String?
var subTitle: NSMutableAttributedString?
var needInput: Bool?
var cancel: String?
var sure: String
var content: String?
var targetView: UIView
public init(title: String? = nil,
subTitle: NSMutableAttributedString? = nil,
needInput: Bool? = nil,
cancel: String? = nil,
sure: String,
content: String? = nil,
targetView: UIView) {
self.title = title
self.subTitle = subTitle
self.needInput = needInput
self.cancel = cancel
self.sure = sure
self.content = content
self.targetView = targetView
}
}
public class Alert: NSObject {
public static let shared = Alert()
public var cancelColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
public var sureColor: UIColor = #colorLiteral(red: 0.2139216065, green: 0.8187626004, blue: 0.6359331608, alpha: 1)
public var titleColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
public var contentColor: UIColor = #colorLiteral(red: 0.5333333333, green: 0.5333333333, blue: 0.5333333333, alpha: 1)
public var contentAlign: NSTextAlignment = .center
var inputValue: String?
public func show(info: AlertInfo,
handler: @escaping (Int) -> Void) {
let alertView = AlertView(info: info) { tag in
handler(tag)
}
alertView.show(targetView: info.targetView)
}
public func show(info: AlertInfo,
handler: @escaping (Int) -> Void,
input: @escaping ((String) -> Void)) {
let alertView = AlertView(info: info,
handler: { tag in
handler(tag)
},
inputHandler: { value in
input(value)
})
alertView.show(targetView: info.targetView)
}
}
<file_sep>//
// Toast.swift
// EatojoyBiz
//
// Created by senyuhao on 21/03/2018.
// Copyright © 2018 dd01. All rights reserved.
//
import Foundation
import PKHUD
extension PKHUD {
public class func loading(onView view: UIView? = nil) {
EBGifTool.loadingGif(gifName: "loading") { images, duration in
if let images = images {
let scale = UIScreen.main.scale
let rect = CGRect(x: 0, y: 0, width: 52 * scale, height: 42.5 * scale)
let imageview = UIImageView(frame: rect)
imageview.contentMode = .scaleAspectFill
imageview.animationImages = images
imageview.animationDuration = duration
imageview.animationRepeatCount = 0
imageview.startAnimating()
imageview.clipsToBounds = true
PKHUD.sharedHUD.contentView = imageview
loadingConfig(onView: view)
}
}
}
public class func loadingHidden() {
PKHUD.sharedHUD.hide(false)
}
public class func show(image: UIImage, title: String?, completion: ((Bool) -> Void)? = nil) {
let contentView = HUDSquareBaseView(image: image, title: nil, subtitle: title)
PKHUD.sharedHUD.contentView = contentView
baseConfig { result in
if let completion = completion {
completion(result)
}
}
}
public class func show(rotateImage: UIImage) {
let contentView = PKHUDRotatingImageView(image: rotateImage, title: nil, subtitle: nil)
contentView.frame = CGRect(x: 0, y: 0, width: 36.0 * UIScreen.main.scale, height: 36.0 * UIScreen.main.scale)
PKHUD.sharedHUD.contentView = contentView
baseConfigUnhide()
}
public class func show(rotateImage: UIImage, title: String) {
let contentView = HUDRotatingImageView(image: rotateImage, title: nil, subtitle: title)
PKHUD.sharedHUD.contentView = contentView
baseConfig { _ in
}
}
public class func show(title: String, completion: ((Bool) -> Void)? = nil) {
let contentView = HUDTextView(text: title)
let maxinumLabelSize = CGSize(width: 220, height: 999)
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)] as [NSAttributedString.Key: Any]
let expectLabelSize = title.boundingRect(with: maxinumLabelSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
contentView.frame = CGRect(x: 0, y: 0, width: expectLabelSize.width + 20, height: expectLabelSize.height + 20)
PKHUD.sharedHUD.contentView = contentView
baseConfig { result in
if let completion = completion {
completion(result)
}
}
}
private class func baseConfig(completion: ((Bool) -> Void)? = nil) {
PKHUD.sharedHUD.dimsBackground = false
PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = false
PKHUD.sharedHUD.contentView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.8)
PKHUD.sharedHUD.contentView.superview?.layer.cornerRadius = 4
PKHUD.sharedHUD.contentView.superview?.superview?.layer.cornerRadius = 4
PKHUD.sharedHUD.show()
PKHUD.sharedHUD.hide(afterDelay: 1.5) { result in
if let completion = completion {
completion(result)
}
}
}
private class func baseConfigUnhide() {
PKHUD.sharedHUD.dimsBackground = false
PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = false
PKHUD.sharedHUD.contentView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.8)
PKHUD.sharedHUD.contentView.superview?.layer.cornerRadius = 4
PKHUD.sharedHUD.contentView.superview?.superview?.layer.cornerRadius = 4
PKHUD.sharedHUD.show()
}
private class func loadingConfig(onView view: UIView? = nil) {
PKHUD.sharedHUD.effect = nil
PKHUD.sharedHUD.dimsBackground = false
PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = false
PKHUD.sharedHUD.contentView.backgroundColor = .clear
PKHUD.sharedHUD.contentView.superview?.backgroundColor = .clear
PKHUD.sharedHUD.contentView.superview?.superview?.backgroundColor = .clear
PKHUD.sharedHUD.show(onView: view)
}
}
class HUDSquareBaseView: PKHUDSquareBaseView {
override init(image: UIImage?, title: String?, subtitle: String?) {
super.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 90, height: 90)))
subtitleLabel.font = UIFont.systemFont(ofSize: 14)
subtitleLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
self.imageView.image = image
subtitleLabel.text = subtitle
addSubview(imageView)
addSubview(subtitleLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
let viewWidth = bounds.size.width
let viewHeight = bounds.size.height
var hasSub = false
if let text = subtitleLabel.text, !text.isEmpty {
hasSub = true
}
let halfHeight = CGFloat(ceilf(CFloat(viewHeight / 2.0)))
let quarterHeight = hasSub ? CGFloat(ceilf(CFloat(viewHeight / 7.0))) : CGFloat(ceilf(CFloat(viewHeight / 4.0)))
let threeQuarterHeight = hasSub ? CGFloat(ceilf(CFloat(viewHeight / 24.0 * 17.0))) : CGFloat(ceilf(CFloat(viewHeight / 4.0 * 3.0)))
imageView.frame = CGRect(origin: CGPoint(x: 0.0, y: quarterHeight), size: CGSize(width: viewWidth, height: halfHeight))
subtitleLabel.frame = CGRect(origin: CGPoint(x: 0.0, y: threeQuarterHeight), size: CGSize(width: viewWidth, height: quarterHeight))
}
}
class HUDTextView: PKHUDTextView {
override init(text: String?) {
super.init(text: text)
titleLabel.font = UIFont.systemFont(ofSize: 14)
titleLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class HUDRotatingImageView: PKHUDRotatingImageView {
override init(image: UIImage?, title: String?, subtitle: String?) {
super.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 90, height: 90)))
subtitleLabel.font = UIFont.systemFont(ofSize: 14)
subtitleLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
self.imageView.image = image
subtitleLabel.text = subtitle
addSubview(imageView)
addSubview(subtitleLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
let viewWidth = bounds.size.width
let viewHeight = bounds.size.height
var hasSub = false
if let text = subtitleLabel.text, !text.isEmpty {
hasSub = true
}
let halfHeight = CGFloat(ceilf(CFloat(viewHeight / 2.0)))
let quarterHeight = hasSub ? CGFloat(ceilf(CFloat(viewHeight / 7.0))) : CGFloat(ceilf(CFloat(viewHeight / 4.0)))
let threeQuarterHeight = hasSub ? CGFloat(ceilf(CFloat(viewHeight / 24.0 * 17.0))) : CGFloat(ceilf(CFloat(viewHeight / 4.0 * 3.0)))
imageView.frame = CGRect(origin: CGPoint(x: 0.0, y: quarterHeight), size: CGSize(width: viewWidth, height: halfHeight))
subtitleLabel.frame = CGRect(origin: CGPoint(x: 0.0, y: threeQuarterHeight), size: CGSize(width: viewWidth, height: quarterHeight))
}
}
<file_sep>
//
// DDVideoPlayerSlider.swift
// mpdemo
//
// Created by leo on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import UIKit
class DDVideoPlayerSlider: UISlider {
public var progressView : UIProgressView = UIProgressView()
public var touchChangedCallBack: ((Float) -> ())?
private var sliderPercent: CGFloat = 0.0
public override init(frame: CGRect) {
super.init(frame: frame)
configureSlider()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
let rect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let newRect = CGRect(x: rect.origin.x, y: rect.origin.y + 1, width: rect.width, height: rect.height)
return newRect
}
override open func trackRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.trackRect(forBounds: bounds)
let newRect = CGRect(origin: rect.origin, size: CGSize(width: rect.size.width, height: 2.0))
configureProgressView(newRect)
return newRect
}
func configureSlider() {
maximumValue = 1.0
minimumValue = 0.0
value = 0.0
maximumTrackTintColor = UIColor.clear
minimumTrackTintColor = #colorLiteral(red: 0.262745098, green: 0.4549019608, blue: 1, alpha: 1)
if let path = Bundle(for: DDVideoPlayerSlider.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let thumbImage = UIImage(named: "dd_video_slider_thumb", in: bundle, compatibleWith: nil) {
let normalThumbImage = DDVideoPlayerUtils.imageSize(image: thumbImage, scaledToSize: CGSize(width: 20, height: 20))
setThumbImage(normalThumbImage, for: .normal)
let highlightedThumbImage = DDVideoPlayerUtils.imageSize(image: thumbImage, scaledToSize: CGSize(width: 25, height: 25))
setThumbImage(highlightedThumbImage, for: .highlighted)
}
backgroundColor = UIColor.clear
progressView.tintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7988548801)
progressView.trackTintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.2964201627)
}
func configureProgressView(_ frame: CGRect) {
progressView.frame = frame
insertSubview(progressView, at: 0)
}
public func setProgress(_ progress: Float, animated: Bool) {
progressView.setProgress(progress, animated: animated)
}
}
extension DDVideoPlayerSlider {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
updateTouchPoint(touches)
callbackTouchEnd(false)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
updateTouchPoint(touches)
callbackTouchEnd(false)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
updateTouchPoint(touches)
callbackTouchEnd(true)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
updateTouchPoint(touches)
callbackTouchEnd(true)
}
private func updateTouchPoint(_ touches: Set<UITouch>) {
let touchPoint = touches.first?.location(in: self)
let width = frame.size.width
sliderPercent = (touchPoint?.x ?? 0.0) / width
self.value = Float(sliderPercent)
}
private func callbackTouchEnd(_ isTouchEnd: Bool) {
if isTouchEnd == true {
self.sendActions(for: .valueChanged)
//回调
if let callBack = touchChangedCallBack {
callBack(Float(sliderPercent))
}
}
}
}
<file_sep>//
// ViewController.swift
// MediatorDemo
//
// Created by weiwei.li on 2019/3/19.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Mediator().getModuleBData()
}
}
<file_sep># EmptyDataView
[更多功能,参照demo](https://github.com/weiweilidd01/EmptyDataView.git)
#### 1.基本使用
* 1.注册EmptydataSources, 在实际使用中,在AppdDelegate中提前注册好
```
// MARK: - 注册时:一定要从0依次升序,否则出问题
extension EmptyDataConfig.Name {
static let common = EmptyDataConfig.Name(rawValue: 0)
static let license = EmptyDataConfig.Name(rawValue: 1)
static let activity = EmptyDataConfig.Name(rawValue: 2)
static let integral = EmptyDataConfig.Name(rawValue: 3)
static let wifi = EmptyDataConfig.Name(rawValue: 4)
}
let config1 = EmptyDataConfig(name: EmptyDataConfig.Name.common, title: "暂无内容", image: UIImage(named: "blankpage_common"))
let config2 = EmptyDataConfig(name: EmptyDataConfig.Name.license, title: "您目前没有绑定任何车牌", image: UIImage(named: "blankpage_search"))
let config3 = EmptyDataConfig(name: EmptyDataConfig.Name.activity, title: "暂无活动", image: UIImage(named: "blankpage_activity"))
let config4 = EmptyDataConfig(name: EmptyDataConfig.Name.integral, title: "暂无卡券", image: UIImage(named: "blankpage_integral"))
let config5 = EmptyDataConfig(name: EmptyDataConfig.Name.wifi, title: "oops!沒有网络讯号", image: UIImage(named: "blankpage_wifi"))
let arr = [config1, config2, config3, config4, config5]
EmptyDataManager.shared.dataSources = arr
```
* 2.在网络请求返回后
```
//网络请求回来后,调用此方法 hasData:值需要自己判断。false为显示,true为隐藏
tableView.emptyDataView(name: EmptyDataConfig.Name.common, hasData: false)
```
#### 2.更多demo展示
<file_sep># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
use_frameworks!
inhibit_all_warnings!
target 'Example' do
use_frameworks!
pod 'MJRefresh'
pod 'DDKit', :path => '.'
pod 'DDKit/Codable', :path => '.'
pod 'DDKit/Hud', :path => '.'
pod 'DDKit/Pop', :path => '.'
pod 'DDKit/Refresh', :path => '.'
pod 'DDKit/Request', :path => '.'
pod 'DDKit/WebJS', :path => '.'
pod 'DDKit/VideoPlayer', :path => '.'
pod 'DDKit/PhotoBrowser', :path => '.'
pod 'DDKit/CustomCamera', :path => '.'
pod 'DDKit/Scan', :path => '.'
pod 'DDKit/Mediator', :path => '.'
pod 'DDKit/Router', :path => '.'
pod 'DDKit/MagicTextField', :path => '.'
pod 'DDKit/EmptyDataView', :path => '.'
pod 'DDKit/DevelopConfig', :path => '.'
pod 'DDKit/PageTabsController', :path => '.'
pod 'DDKit/Picker', :path => '.'
pod 'DDKit/CityList', :path => '.'
pod 'DDKit/NumberSelect', :path => '.'
pod 'DDKit/Chainable', :path => '.'
pod 'CryptoSwift'
pod 'SwiftLint'
end
target 'DDKit' do
pod 'Alamofire'
pod 'PromiseKit'
pod 'PKHUD'
pod 'SnapKit'
pod 'Kingfisher'
pod 'MBProgressHUD'
pod 'MJRefresh'
pod 'Cache'
pod 'DDKit/CustomCamera', :path => '.'
pod 'SwiftLint'
pod 'AFNetworking/Reachability'
pod 'ActionSheetPicker-3.0'
pod 'RxSwift'
pod 'RxCocoa'
end
post_install do |installer|
system("git config --local core.hooksPath '.githooks'")
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['CODE_SIGN_STYLE'] = "Automatic"
end
end
end
<file_sep>//
// TableViewController.swift
// CoreDemo
//
// Created by USER on 2018/12/28.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
setRightButtonItem(image: UIImage(named: "nav_icon_back_black")) {[weak self] (btn) in
//点击事件回调
self?.navigationController?.popViewController(animated: true)
}
setRightButtonItem(title: "关闭") { (btn) in
//点击事件回调
}
// setLeftButtonItem(image: UIImage(named: "nav_icon_back_black")) { (btn) in
//
// }
setLeftButtonItem(image: UIImage(named: "nav_icon_back_black")) {[weak self] (btn) in
//点击事件回调
self?.navigationController?.popViewController(animated: true)
}
if #available(iOS 11.0, *) {
self.tableView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isTranslucent = true
changeNavBackgroundImageWithAlpha(alpha: 0)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
changeNavBackgroundImageWithAlpha(alpha: 1)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let value = scrollView.contentOffset.y
let alpha = value / 64
changeNavBackgroundImageWithAlpha(alpha: alpha)
}
}
<file_sep>//
// DDPhotoUploadBrowserController.swift
// DDCustomCameraDemo
//
// Created by USER on 2018/12/7.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import Photos
class DDPhotoUploadBrowserController: UIViewController {
/// 默认滚动下标
public var currentIndex = 0
//最大选择数量
public var maxSelectedNumber: Int = Int.max
//数据源
public var photoArr: [DDPhotoGridCellModel]? {
didSet {
photoCollectionView?.reloadData()
}
}
//导航view
public lazy var navigationView = DDPhotoPickerNavigationView(frame: CGRect(x: 0, y: 0, width: DDPhotoScreenWidth, height: DDPhotoNavigationTotalHeight), leftBtnCallBack: { [weak self] in
let orientation = UIDevice.current.orientation
if orientation == .landscapeLeft || orientation == .landscapeRight {
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
} else {
if self?.navigationController == nil {
self?.dismiss(animated: true, completion: nil)
return
}
self?.navigationController?.popViewController(animated: true)
}
}, rightBtnCallBack: nil)
private var photoCollectionView: UICollectionView?
private let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
private var scrollDistance: CGFloat = 0
private var requestImageIDs = [PHImageRequestID]()
//旋转之前index
private var indexBeforeRotation: Int = 0
private var isDrag: Bool = false
override public func viewDidLoad() {
super.viewDidLoad()
//初始化旋转之前的index
indexBeforeRotation = currentIndex
//设置ui
setupUI()
//添加屏幕旋转通知
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationChanged(_:)), name: UIApplication.willChangeStatusBarOrientationNotification, object: nil)
}
@objc func deviceOrientationChanged(_ notify: Notification) {
indexBeforeRotation = currentIndex
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//一定要放在viewWillAppear中,否则会偶尔导致手势失效
navigationController?.interactivePopGestureRecognizer?.delegate = self
navigationController?.setNavigationBarHidden(true, animated: animated)
//初始化导航栏标题
changeNavigationTitle(currentIndex + 1)
DDLandscapeManager.shared.isForceLandscape = true
photoCollectionView?.isScrollEnabled = true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//设置gif播放,主要是防止第一次点击进来的图片是gif不播放的问题
setCellGif()
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
DDLandscapeManager.shared.isForceLandscape = false
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
var inset = UIEdgeInsets.init(top: 20, left: 0, bottom: 0, right: 0);
if #available(iOS 11.0, *) {
inset = view.safeAreaInsets
}
navigationView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: inset.top + DDPhotoNavigationHeight)
flowLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
flowLayout.itemSize = CGSize(width: screenWidth + 10, height: screenHeight)
photoCollectionView?.frame = CGRect(x: 0, y: 0, width: screenWidth + 10, height: screenHeight)
//滚动cell
if isDrag == false {
photoCollectionView?.setContentOffset(CGPoint(x: Int(screenWidth + 10) * indexBeforeRotation, y: 0), animated: false)
}
}
override public func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
//如果dismiss就取消所有在下载的图片
if parent == nil {
for id in requestImageIDs {
DDPhotoImageManager.default().cancelImageRequest(id)
}
}
}
deinit {
DDPhotoImageManager.default().removeAllCache()
NotificationCenter.default.removeObserver(self)
print(self)
}
}
extension DDPhotoUploadBrowserController: UICollectionViewDelegate, UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoArr?.count ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//图片cell
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DDPhotoPickerBorwserCell", for: indexPath) as? DDPhotoPickerBorwserCell {
let model:DDPhotoGridCellModel? = photoArr?[indexPath.row]
cell.type = .uploadBrowser
cell.disPlayCell(model)
cell.oneTapClosure = {[weak self] tap in
self?.updateLayout()
}
return cell
}
return UICollectionViewCell()
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let model:DDPhotoGridCellModel? = photoArr?[indexPath.row]
//设置原图
setPreviewImage(cell: cell as? DDPhotoPickerBorwserCell, model: model)
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//重新改变cell的默认缩放
(cell as? DDPhotoPickerBorwserCell)?.defaultScale = 1
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
}
}
extension DDPhotoUploadBrowserController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollDistance = scrollView.contentOffset.x
isDrag = true
//gif操作.停止播放gif
let model: DDPhotoGridCellModel? = photoArr?[currentIndex]
if model?.isGIF == true {
let currentCell = photoCollectionView?.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? DDPhotoPickerBorwserCell
currentCell?.photoImages?.removeAll()
currentCell?.photoImageView.stopAnimating()
//每次都清除所有的cache,否则内存过大,后续再优化是否需要本地持久缓存
DDPhotoImageManager.default().removeAllCache()
return
}
//如果视屏,停止播放视屏
if model?.type == .video {
let currentCell = photoCollectionView?.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? DDPhotoPickerBorwserCell
currentCell?.videoView.pause()
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
currentIndex = Int(round(scrollView.contentOffset.x/scrollView.bounds.width))
if currentIndex >= photoArr?.count ?? 0 {
currentIndex = (photoArr?.count ?? 0) - 1
} else if currentIndex < 0 {
currentIndex = 0
}
//改变导航栏标题
changeNavigationTitle(currentIndex + 1)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
isDrag = false
//gif操作.播放gif
setCellGif()
}
}
private extension DDPhotoUploadBrowserController {
func setCellGif() {
//gif操作.播放gif
let model: DDPhotoGridCellModel? = photoArr?[currentIndex]
if model?.isGIF == false { return }
let currentCell = photoCollectionView?.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? DDPhotoPickerBorwserCell
guard let localIdentifier = model?.localIdentifier,
let images = DDPhotoImageManager.default().getImagesCache(localIdentifier),
let duration = DDPhotoImageManager.default().getImagesDurationCache(localIdentifier) else {
return
}
currentCell?.photoImages = images
currentCell?.photoImageView.stopAnimating()
currentCell?.animationDuration = duration
}
func updateLayout() {
UIView.animate(withDuration: 0.25) {
self.navigationView.isHidden = !self.navigationView.isHidden
}
}
func setPreviewImage(cell: DDPhotoPickerBorwserCell?, model: DDPhotoGridCellModel?) {
cell?.setPreviewImage(model)
}
func setupUI() {
view.backgroundColor = UIColor.black
//添加 navigationview
view.addSubview(navigationView)
//add collectionView
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.itemSize = CGSize(width: DDPhotoScreenWidth + 10, height: DDPhotoScreenHeight)
photoCollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: DDPhotoScreenWidth + 10, height: DDPhotoScreenHeight), collectionViewLayout: flowLayout)
if let photoCollectionView = photoCollectionView {
photoCollectionView.isPagingEnabled = true
photoCollectionView.register(DDPhotoPickerBorwserCell.self,
forCellWithReuseIdentifier: "DDPhotoPickerBorwserCell")
photoCollectionView.delegate = self
photoCollectionView.dataSource = self
view.addSubview(photoCollectionView)
if #available(iOS 11.0, *) {
photoCollectionView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
}
//添加底部bottom
view.bringSubviewToFront(navigationView)
}
func changeNavigationTitle(_ index: Int) {
let text = "\(index)/\(photoArr?.count ?? 0)"
navigationView.titleLabel.text = text
}
}
extension DDPhotoUploadBrowserController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
photoCollectionView?.isScrollEnabled = false
return true
}
}
<file_sep>//
// PlayerViewController.swift
// Example
//
// Created by USER on 2018/10/29.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
import SnapKit
import DDKit
class PlayerViewController: UIViewController {
var player = DDVideoPlayer()
var isHidden:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// let url1 = URL(string: "https://ylmtst.yejingying.com/asset/video/20180525184959_mW8WVQVd.mp4")!
let url = URL(string: "http://tb-video.bdstatic.com/videocp/12045395_f9f87b84aaf4ff1fee62742f2d39687f.mp4")!
self.player.replaceVideo(url)
self.player.isEnableLandscape = true
//设置frame,请使用下面CGRect,暂时还没兼容Snapkit,后续改进
//原因: 需要在init中获取displayView的frame。 Snapkit在初始化方法中不能获取
self.player.displayView.frame = CGRect(x: 0, y: 64, width: DDVPScreenWidth, height: DDVPScreenWidth * (9.0/16.0))
view.addSubview(self.player.displayView)
//后台模式,关于前后台切换回来的播放模式
self.player.backgroundMode = .proceed
//横盘设置要显示的标题
self.player.displayView.titleLabel.text = "DD01"
//必须设置代理
self.player.displayView.delegate = self
//下面协议按需要是否实现
//self.player.delegate = self
//获取视屏首帧图片
let imageView = UIImageView()
view.addSubview(imageView)
imageView.frame = CGRect(x: 0, y: 300, width: 100, height: 100)
DDVideoPlayer.firstFrame(videoUrl: url, size: CGSize(width: 100, height: 100)) { (image) in
imageView.image = image
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
player.play()
}
deinit {
print(self)
}
//mark 下面三个方法必须要实现
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .none
}
override var prefersStatusBarHidden: Bool {
return isHidden
}
override var shouldAutorotate: Bool {
return false
}
}
extension PlayerViewController: DDPlayerViewDelegate {
//此协议必须实现才能隐藏导航栏
func ddPlayerView(_ playerView: DDVideoPlayerView, willFullscreen isFullscreen: Bool, orientation: UIInterfaceOrientation) {
if orientation == .portrait {
isHidden = false
} else {
isHidden = true
}
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
}
<file_sep>
//
// DDVideoPlayerLoadingIndicator.swift
// mpdemo
//
// Created by leo on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import UIKit
private let kRotationAnimationKey = "kRotationAnimationKey.rotation"
class DDVideoPlayerLoadingIndicator: UIView {
private let indicatorLayer = CAShapeLayer()
var timingFunction : CAMediaTimingFunction!
var isAnimating = false
private let imageView: UIImageView = {
let imageView = UIImageView()
if let path = Bundle(for: DDVideoPlayerLoadingIndicator.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "video_ratation", in: bundle, compatibleWith: nil) {
imageView.image = image
}
imageView.contentMode = .scaleAspectFill
return imageView
}()
// public var lineWidth: CGFloat {
// get {
// return indicatorLayer.lineWidth
// }
// set(newValue) {
// indicatorLayer.lineWidth = newValue
// updateIndicatorLayerPath()
// }
// }
public override init(frame : CGRect) {
super.init(frame : frame)
commonInit()
}
public convenience init() {
self.init(frame:CGRect.zero)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
commonInit()
}
override open func layoutSubviews() {
// indicatorLayer.frame = bounds
// updateIndicatorLayerPath()
imageView.frame = bounds
}
}
//MARK --- public method
extension DDVideoPlayerLoadingIndicator {
func startAnimating() {
if self.isAnimating {
return
}
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.duration = 1
animation.fromValue = 0
animation.toValue = (2 * Double.pi)
animation.repeatCount = Float.infinity
animation.isRemovedOnCompletion = false
// indicatorLayer.add(animation, forKey: kRotationAnimationKey)
imageView.layer.add(animation, forKey: kRotationAnimationKey)
isAnimating = true;
}
func stopAnimating() {
if !isAnimating {
return
}
imageView.layer.removeAnimation(forKey: kRotationAnimationKey)
// indicatorLayer.removeAnimation(forKey: kRotationAnimationKey)
isAnimating = false;
}
}
//MARK --- private method
private extension DDVideoPlayerLoadingIndicator {
private func commonInit(){
// timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// setupIndicatorLayer()
addSubview(imageView)
}
// private func setupIndicatorLayer() {
// indicatorLayer.strokeColor = UIColor.white.cgColor
// indicatorLayer.fillColor = nil
// indicatorLayer.lineWidth = 2.0
// indicatorLayer.lineJoin = kCALineJoinRound;
// indicatorLayer.lineCap = kCALineCapRound;
// layer.addSublayer(indicatorLayer)
//// updateIndicatorLayerPath()
// }
// private func updateIndicatorLayerPath() {
// let center = CGPoint(x: bounds.midX, y: bounds.midY)
// let radius = min(bounds.width / 2, bounds.height / 2) - indicatorLayer.lineWidth / 2
// let startAngle: CGFloat = 0
// let endAngle: CGFloat = 2 * CGFloat(Double.pi)
// let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
// indicatorLayer.path = path.cgPath
//
// indicatorLayer.strokeStart = 0.1
// indicatorLayer.strokeEnd = 1.0
// }
//
// private var strokeColor: UIColor {
// get {
// return UIColor(cgColor: indicatorLayer.strokeColor!)
// }
// set(newValue) {
// indicatorLayer.strokeColor = newValue.cgColor
// }
// }
}
<file_sep>//
// UIViewController+NavigationBarItem.swift
// CoreDemo
//
// Created by USER on 2018/12/21.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
// MARK: - 改变导航栏透明色
extension UIViewController {
/// 改变导航栏透明度
///
/// - Parameters:
/// - alpha: 透明值
/// - backgroundColor: 非透明时背景颜色
/// - shadowColor: 非透明是shadow阴影颜色
public func changeNavBackgroundImageWithAlpha(alpha: CGFloat, backgroundColor: UIColor = .white, shadowColor: UIColor = #colorLiteral(red: 0.9311618209, green: 0.9279686809, blue: 0.9307579994, alpha: 1)) {
var value = alpha >= 1 ? 1 : alpha
value = value >= 0 ? value : 0
let color = backgroundColor.withAlphaComponent(alpha)
let image = UIColor.imageFromColor(color: color)
navigationController?.navigationBar.setBackgroundImage(image, for: .default)
if alpha > 0.5 {
let shadowImage = UIColor.imageFromColor(color: shadowColor)
navigationController?.navigationBar.shadowImage = shadowImage
} else {
navigationController?.navigationBar.shadowImage = UIImage()
}
}
}
extension UIViewController {
/// 添加右边带文字的ButtonItem
///
/// - Parameters:
/// - title: item的标题
/// - actionBlock: 点击事件回调
/// - Returns: 按钮
@discardableResult public func setRightButtonItem(title: String, actionBlock: ((UIButton) -> Void)?) -> UIButton {
return setRightButtonItem(frame: CGRect(x: 0, y: 0, width: 70, height: 44), title: title, image: nil, actionBlock: actionBlock)
}
/// 添加右边带图片的ButtonItem
///
/// - Parameters:
/// - image: 图片
/// - actionBlock: 点击事件回调
/// - Returns: 按钮
@discardableResult public func setRightButtonItem(image: UIImage?, actionBlock: ((UIButton) -> Void)?) -> UIButton {
return setRightButtonItem(frame: CGRect(x: 0, y: 12, width: 15, height: 20), title: nil, image: image, actionBlock: actionBlock)
}
/// 添加自定义view的ButtonItem
///
/// - Parameters:
/// - customView: 自定义view
/// - actionBlock: 点击事件回调
public func setRightButtonItem(customView: UIView, actionBlock: ((UIView, UITapGestureRecognizer) -> Void)?) {
customView.tap { (custom, tap) in
actionBlock?(custom,tap)
}
let rightButtonItem = UIBarButtonItem(customView: customView)
navigationController?.topViewController?.navigationItem.rightBarButtonItem = rightButtonItem
}
/// 添加右边带标题数组的ButtonItem
///
/// - Parameters:
/// - titles: 标题数组
/// - actionBlock: 点击事件回调,多个按钮,通过tag区分
public func setRightButtonItem(titles: [String], actionBlock: ((UIButton) -> Void)?) {
assert(titles.count > 0, "请传入非空的标题数组")
var items: [UIBarButtonItem] = [UIBarButtonItem]()
for (index, title) in titles.enumerated() {
let titleStr: NSString = title as NSString
let titleSize = titleStr.boundingRect(with: CGSize(width: 200, height: 44), options: .usesFontLeading, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0)], context: nil).size
let btn = buttomItem(frame: CGRect(x: 0, y: 0, width: titleSize.width, height: titleSize.height), title: title, image: nil)
btn.press { (btn) in
actionBlock?(btn)
}
btn.tag = index
let rightButtonItem = UIBarButtonItem(customView: btn)
items.append(rightButtonItem)
//
// let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
// negativeSpacer.width = 10
// items.append(negativeSpacer)
}
navigationController?.topViewController?.navigationItem.rightBarButtonItems = items
}
/// 添加右边带图片数组的ButtonItem
///
/// - Parameters:
/// - images: 图片数组
/// - actionBlock: 点击回调
public func setRightButtonItem(images: [UIImage?], actionBlock: ((UIButton) -> Void)?) {
assert(images.count > 0, "请传入非空的标题数组")
var items: [UIBarButtonItem] = [UIBarButtonItem]()
for (index, image) in images.enumerated() {
let btn = buttomItem(frame: CGRect(x: 0, y: 12, width: 15, height: 20), title: nil, image: image)
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0)
btn.tag = index
btn.press { (sender) in
actionBlock?(sender)
}
let rightButtonItem = UIBarButtonItem(customView: btn)
items.append(rightButtonItem)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = 10
items.append(negativeSpacer)
}
navigationController?.topViewController?.navigationItem.rightBarButtonItems = items
}
/// 添加左边带标题的ButtonItem
///
/// - Parameters:
/// - title: 标题
/// - actionBlock: 点击回调
/// - Returns: 左边按钮
@discardableResult public func setLeftButtonItem(title: String, actionBlock: ((UIButton) -> Void)?) -> UIButton {
let leftBtn = buttomItem(frame: CGRect(x: 0, y: 0, width: 44, height: 44), title: title, image: nil)
leftBtn.contentHorizontalAlignment = .left
leftBtn.press { (btn) in
actionBlock?(btn)
}
let leftBtnItem = UIBarButtonItem(customView: leftBtn)
navigationController?.topViewController?.navigationItem.leftBarButtonItem = leftBtnItem
return leftBtn
}
/// 添加左边带图片的ButtonItem
///
/// - Parameters:
/// - image: 图片
/// - actionBlock: 点击回调
/// - Returns: 左边按钮
@discardableResult public func setLeftButtonItem(image: UIImage?, actionBlock: ((UIButton) -> Void)?) -> UIButton {
let leftBtn = buttomItem(frame: CGRect(x: 0, y: 12, width: 20, height: 20), title: nil, image: image)
leftBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
leftBtn.press { (btn) in
actionBlock?(btn)
}
let leftButtonItem = UIBarButtonItem(customView: leftBtn)
navigationController?.topViewController?.navigationItem.leftBarButtonItem = leftButtonItem
return leftBtn
}
/// 添加左边带图片数组的ButtonItem
///
/// - Parameters:
/// - images: 图片数组
/// - actionBlock: 点击回调
public func setLeftButtonItem(images: [UIImage?], actionBlock: ((UIButton) -> Void)?) {
var items: [UIBarButtonItem] = [UIBarButtonItem]()
for (index, image) in images.enumerated() {
let btn = buttomItem(frame: CGRect(x: 0, y: 12, width: 15, height: 20), title: nil, image: image)
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0)
btn.tag = index
btn.press { (sender) in
actionBlock?(sender)
}
let rightButtonItem = UIBarButtonItem(customView: btn)
items.append(rightButtonItem)
// let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
// negativeSpacer.width = 10
// items.append(negativeSpacer)
}
navigationController?.topViewController?.navigationItem.leftBarButtonItems = items
}
/// 添加左边带标题数组的ButtonItem
///
/// - Parameters:
/// - titles: 标题数组
/// - actionBlock: 点击事件回调,多个按钮,通过tag区分
public func setLeftButtonItem(titles: [String], actionBlock: ((UIButton) -> Void)?) {
assert(titles.count > 0, "请传入非空的标题数组")
var items: [UIBarButtonItem] = [UIBarButtonItem]()
for (index, title) in titles.enumerated() {
let titleStr: NSString = title as NSString
let titleSize = titleStr.boundingRect(with: CGSize(width: 200, height: 44), options: .usesFontLeading, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0)], context: nil).size
let btn = buttomItem(frame: CGRect(x: 0, y: 0, width: titleSize.width, height: titleSize.height), title: title, image: nil)
btn.press { (btn) in
actionBlock?(btn)
}
btn.tag = index
let rightButtonItem = UIBarButtonItem(customView: btn)
items.append(rightButtonItem)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
negativeSpacer.width = 10
items.append(negativeSpacer)
}
navigationController?.topViewController?.navigationItem.leftBarButtonItems = items
}
/// 添加自定义view的ButtonItem
///
/// - Parameters:
/// - customView: 自定义view
/// - actionBlock: 点击事件回调
public func setLeftButtonItem(customView: UIView, actionBlock: ((UIView, UITapGestureRecognizer) -> Void)?) {
customView.tap { (custom, tap) in
actionBlock?(custom,tap)
}
let leftBarButtonItem = UIBarButtonItem(customView: customView)
// let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
// negativeSpacer.width = -4
// navigationController?.topViewController?.navigationItem.rightBarButtonItems = [negativeSpacer, rightButtonItem]
navigationController?.topViewController?.navigationItem.leftBarButtonItem = leftBarButtonItem
}
}
extension UIViewController {
fileprivate func setRightButtonItem(frame: CGRect, title: String?, image: UIImage?, actionBlock:((UIButton) -> Void)?) -> UIButton {
let rightBtn = buttomItem(frame: frame, title: title, image: image)
if image != nil {
rightBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
}
rightBtn.press { (btn) in
actionBlock?(btn)
}
let rightButtonItem = UIBarButtonItem(customView: rightBtn)
// let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
// negativeSpacer.width = -4
// navigationController?.topViewController?.navigationItem.rightBarButtonItems = [negativeSpacer, rightButtonItem]
navigationController?.topViewController?.navigationItem.rightBarButtonItem = rightButtonItem
return rightBtn
}
fileprivate func buttomItem(frame: CGRect, title: String?, image: UIImage?) -> UIButton {
let btn = UIButton(type: .system)
btn.backgroundColor = UIColor.clear
btn.frame = frame
if let title = title {
btn.contentHorizontalAlignment = .right
btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
btn.setTitle(title, for: .normal)
}
if let image = image {
// btn.setBackgroundImage(image, for: .normal)
btn.setImage(image, for: .normal)
}
return btn
}
}
<file_sep>
//
// DDPhotoPickerBorwserCell.swift
// Photo
//
// Created by USER on 2018/11/12.
// Copyright © 2018 leo. All rights reserved.
//
import UIKit
import Photos
public enum DDPhotoPickerBorwserCellType {
case picker
case uploadBrowser
}
class DDPhotoPickerBorwserCell: UICollectionViewCell {
private var currentScale: CGFloat = 1
private let maxScale: CGFloat = 2
private let minScale: CGFloat = 1
private var requestId: PHImageRequestID?
private var model: DDPhotoGridCellModel?
public var type: DDPhotoPickerBorwserCellType = .picker
//单击回调
var oneTapClosure: ((UITapGestureRecognizer?) -> Void)?
var photoImage: UIImage? {
didSet {
photoImageView.image = photoImage
guard let size = photoImage?.size else {
return
}
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
let scaleImage = size.height / size.width
let imageHeight = screenWidth * scaleImage
var frame = CGRect(x: 0, y: 0, width: screenWidth, height: imageHeight)
//转换后的图片高度还超过屏幕高度,就再次转换
if imageHeight > screenHeight {
let imageW = screenHeight / scaleImage
frame = CGRect(x: 0, y: 0, width: imageW, height: screenHeight)
}
//比列超过3的,超长图片重新计算宽高
if scaleImage > 3 {
let imageHeight = screenWidth * scaleImage
frame = CGRect(x: 0, y: 0, width: screenWidth, height: imageHeight)
}
photoImageView.frame = frame
//高度大于设备高度,不居中显示
if frame.height > screenHeight {
} else {
photoImageView.center = photoImageScrollView.center
}
photoImageScrollView.contentSize = photoImageView.frame.size
}
}
var animationDuration: TimeInterval? {
didSet {
photoImageView.animationDuration = animationDuration ?? 0
photoImageView.startAnimating()
}
}
var photoImages: [UIImage]? {
didSet {
photoImageView.animationImages = photoImages
}
}
lazy var photoImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = true
return imageView
}()
lazy var photoImageScrollView: UIScrollView = {
let scrollView = UIScrollView()
var frame = self.contentView.bounds
scrollView.delegate = self
scrollView.isUserInteractionEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.maximumZoomScale = self.maxScale
scrollView.minimumZoomScale = self.minScale
let oneTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(oneTap(oneTapGestureRecognizer:)))
oneTapGestureRecognizer.numberOfTapsRequired = 1
oneTapGestureRecognizer.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(oneTapGestureRecognizer)
let doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTap(doubleTapGestureRecognizer:)))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
doubleTapGestureRecognizer.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(doubleTapGestureRecognizer)
oneTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
scrollView.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleHeight]
return scrollView
}()
//MARK -- 视屏播放相关
public let videoView: DDPhotoVideoView = {
let videoView = DDPhotoVideoView()
videoView.backgroundColor = UIColor.black
return videoView
}()
// 初始缩放大小
var defaultScale: CGFloat = 1 {
didSet {
photoImageScrollView.setZoomScale(defaultScale, animated: false)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
var frame = contentView.bounds
frame.size.width -= 10
//初始化默认zoom
currentScale = 1.0
photoImageScrollView.setZoomScale(currentScale, animated: true)
photoImageScrollView.frame = frame
photoImageView.frame = frame
/// 横竖屏切换,重新布局
if photoImageView.image != nil {
photoImage = photoImageView.image
}
videoView.frame = frame
}
deinit {
print(self)
}
}
extension DDPhotoPickerBorwserCell {
public func disPlayCell(_ model: DDPhotoGridCellModel?) {
self.model = model
if model?.type != .video {
photoImageView.isHidden = false
videoView.isHidden = true
photoImageView.removeFromSuperview()
photoImageScrollView.addSubview(photoImageView)
return
}
//当前cell是视屏播放
videoView.isHidden = false
photoImageView.removeFromSuperview()
videoView.addSubview(photoImageView)
photoImageView.isHidden = false
videoView.model = model
videoView.hiddenPreviewCallBack = {[weak self] (isPlay) in
//除了第一次加载显示一下封面,后续一直隐藏
self?.photoImageView.isHidden = true
if self?.type == .uploadBrowser {
//隐藏导航栏和底部栏
let vc = self?.ddPhotoViewController() as? DDPhotoUploadBrowserController
if isPlay == false {
vc?.navigationView.isHidden = false
} else {
vc?.navigationView.isHidden = true
}
return
}
//隐藏导航栏和底部栏
let vc = self?.ddPhotoViewController() as! DDPhotoPickerBorwserController
if isPlay == false {
vc.navigationView.isHidden = false
vc.bottomView.isHidden = false
} else {
vc.navigationView.isHidden = true
vc.bottomView.isHidden = true
}
}
}
public func setPreviewImage(_ model: DDPhotoGridCellModel?) {
//取消之前的requeset
if let id = requestId {
if id > 0 {
DDPhotoImageManager.default().cancelImageRequest(id)
}
}
requestId = DDPhotoPickerSource.requestPreviewImage(for: model
, callBack: {[weak self] (image) in
self?.photoImage = image
})
}
}
//MARK: -UIScrollView delegate
extension DDPhotoPickerBorwserCell: UIScrollViewDelegate {
// 单击手势
@objc func oneTap(oneTapGestureRecognizer: UITapGestureRecognizer) {
if let callBack = oneTapClosure {
callBack(oneTapGestureRecognizer)
}
}
// 双击手势
@objc func doubleTap(doubleTapGestureRecognizer: UITapGestureRecognizer) {
//当前倍数等于最大放大倍数
//双击默认为缩小到原图
let aveScale = minScale + (maxScale - minScale) / 2.0 //中间倍数
if currentScale >= aveScale {
currentScale = minScale
self.photoImageScrollView.setZoomScale(currentScale, animated: true)
} else if currentScale < aveScale {
currentScale = maxScale
let touchPoint = doubleTapGestureRecognizer.location(in: doubleTapGestureRecognizer.view)
self.photoImageScrollView.zoom(to: CGRect(x: touchPoint.x, y: touchPoint.y, width: 10, height: 10), animated: true)
}
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.photoImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
var xcenter = scrollView.center.x , ycenter = scrollView.center.y
//目前contentsize的width是否大于原scrollview的contentsize,如果大于,设置imageview中心x点为contentsize的一半,以固定imageview在该contentsize中心。如果不大于说明图像的宽还没有超出屏幕范围,可继续让中心x点为屏幕中点,此种情况确保图像在屏幕中心。
xcenter = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width/2 : xcenter;
ycenter = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height/2 : ycenter;
self.photoImageView.center = CGPoint(x: xcenter, y: ycenter)
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
currentScale = scale
}
}
private extension DDPhotoPickerBorwserCell {
func setupUI() {
contentView.backgroundColor = UIColor.black
photoImageScrollView.addSubview(photoImageView)
contentView.addSubview(photoImageScrollView)
contentView.addSubview(videoView)
if #available(iOS 11.0, *) {
photoImageScrollView.contentInsetAdjustmentBehavior = .never
}
}
}
extension UIView {
func ddPhotoViewController () -> UIViewController? {
var next: UIResponder?
next = self.next
repeat {
if (next as? UIViewController) != nil {
return next as? UIViewController
} else {
next = next?.next
}
} while next != nil
return UIViewController()
}
}
<file_sep>//
// WKWeb.swift
// Example
//
// Created by senyuhao on 2018/10/25.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
import WebKit
import DDKit
class WKWeb: UIViewController {
private var web: WKWebView = WKWebView(frame: CGRect(), configuration: WKWebViewConfiguration())
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
web.navigationDelegate = self
web.uiDelegate = self
view.addSubview(web)
web.snp.makeConstraints { make in
make.top.left.right.bottom.equalTo(view)
}
WebManager.shared.configManager(web)
WebManager.shared.configBlock = { value, block in
let param = ["vendor": "123",
"ios": "234"]
if let value = WebManager.shared.callback(err: nil, response: param) {
print("config = \(value)")
block?(value)
}
}
WebManager.shared.sendBlock = { value, block in
if let value = WebManager.shared.callback(err: nil, response: "send response") {
print("send = \(value)")
block?(value)
}
}
WebManager.shared.requestBlock = { value, block in
if let value = WebManager.shared.callback(err: nil, response: "request response") {
print("request = \(value)")
block?(value)
}
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交", style: .done, target: self, action: #selector(itemClick))
loadPage(webView: web)
}
private func loadPage(webView: WKWebView) {
if let path = Bundle.main.path(forResource: "demo1", ofType: "html"),
let html = try? String(contentsOfFile: path, encoding: .utf8) {
let url = URL(fileURLWithPath: path)
webView.loadHTMLString(html, baseURL: url)
}
}
@objc private func itemClick() {
if let param = WebManager.shared.callback(err: nil, response: "request response") {
WebManager.shared.push(param: param) { value in
print("push result = \(String(describing: value))")
}
}
}
}
extension WKWeb: WKNavigationDelegate {
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation) {
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation) {
print("开始加载")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation) {
print("加载完成")
WebManager.shared.configFinished()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation, withError error: Error) {
print("加载失败")
}
}
extension WKWeb: WKUIDelegate {
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
}
@available(iOS 10.0, *)
func webView(_ webView: WKWebView, shouldPreviewElement elementInfo: WKPreviewElementInfo) -> Bool {
return true
}
func webView(_ webView: WKWebView, commitPreviewingViewController previewingViewController: UIViewController) {
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
}
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
print("message \(message)")
let vc = UIAlertController(title: "弹窗", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "确定", style: .default) { _ in
completionHandler()
}
vc.addAction(action)
self.present(vc, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
print("message \(message)")
let vc = UIAlertController(title: "弹窗", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "确定", style: .default) { _ in
completionHandler(true)
}
vc.addAction(action)
self.present(vc, animated: true, completion: nil)
}
}
<file_sep>//
// UITableView+Chainable.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UITableView
public extension UIKitChainable where Self: ChainableTableView {
/// 刷新 `reloadData`
///
/// - Returns: self
@discardableResult
func reload() -> Self {
reloadData()
return self
}
// @discardableResult
// @available(iOS 10.0, *)
// func prefetchDataSource(_ prefetching: UITableViewDataSourcePrefetching?) -> UITableView {
// prefetchDataSource = prefetching
// return self
// }
//
// @discardableResult
// @available(iOS 11.0, *)
// func dragDelegate(_ delegate: UITableViewDragDelegate?) -> UITableView {
// dragDelegate = delegate
// return self
// }
//
// @discardableResult
// @available(iOS 11.0, *)
// func dropDelegate(_ delegate: UITableViewDropDelegate?) -> UITableView {
// dropDelegate = delegate
// return self
// }
//
@discardableResult
func rowHeight(_ height: CGFloat) -> Self {
rowHeight = height
return self
}
@discardableResult
func sectionHeaderHeight(_ height: CGFloat) -> Self {
sectionHeaderHeight = height
return self
}
@discardableResult
func sectionFooterHeight(_ height: CGFloat) -> Self {
sectionFooterHeight = height
return self
}
@discardableResult
func estimatedRowHeight(_ height: CGFloat) -> Self {
estimatedRowHeight = height
return self
}
@discardableResult
func estimatedSectionHeaderHeight(_ height: CGFloat) -> Self {
estimatedSectionHeaderHeight = height
return self
}
@discardableResult
func estimatedSectionFooterHeight(_ height: CGFloat) -> Self {
estimatedSectionFooterHeight = height
return self
}
@discardableResult
func separatorInset(_ inset: UIEdgeInsets) -> Self {
separatorInset = inset
return self
}
@discardableResult
@available(iOS 11.0, *)
func separatorInsetReference(_ reference: UITableView.SeparatorInsetReference) -> Self {
separatorInsetReference = reference
return self
}
@discardableResult
func backgroundView(_ view: UIView?) -> Self {
backgroundView = view
return self
}
@discardableResult
func isEditing(_ bool: Bool) -> Self {
isEditing = bool
return self
}
@discardableResult
func allowsSelection(_ bool: Bool) -> Self {
allowsSelection = bool
return self
}
@discardableResult
func allowsSelectionDuringEditing(_ bool: Bool) -> Self {
allowsSelectionDuringEditing = bool
return self
}
@discardableResult
func allowsMultipleSelection(_ bool: Bool) -> Self {
allowsMultipleSelection = bool
return self
}
@discardableResult
func allowsMultipleSelectionDuringEditing(_ bool: Bool) -> Self {
allowsMultipleSelectionDuringEditing = bool
return self
}
@discardableResult
func sectionIndexMinimumDisplayRowCount(_ count: Int) -> Self {
sectionIndexMinimumDisplayRowCount = count
return self
}
@discardableResult
func sectionIndexColor(_ color: UIColor?) -> Self {
sectionIndexColor = color
return self
}
@discardableResult
func sectionIndexBackgroundColor(_ color: UIColor?) -> Self {
sectionIndexBackgroundColor = color
return self
}
@discardableResult
func sectionIndexTrackingBackgroundColor(_ color: UIColor?) -> Self {
sectionIndexTrackingBackgroundColor = color
return self
}
@discardableResult
func separatorStyle(_ style: UITableViewCell.SeparatorStyle) -> Self {
separatorStyle = style
return self
}
@discardableResult
func separatorColor(_ color: UIColor?) -> Self {
separatorColor = color
return self
}
@discardableResult
func separatorEffect(_ effect: UIVisualEffect?) -> Self {
separatorEffect = effect
return self
}
@discardableResult
func cellLayoutMarginsFollowReadableWidth(_ bool: Bool) -> Self {
cellLayoutMarginsFollowReadableWidth = bool
return self
}
@discardableResult
@available(iOS 11.0, *)
func insetsContentViewsToSafeArea(_ bool: Bool) -> Self {
insetsContentViewsToSafeArea = bool
return self
}
@discardableResult
func tableHeaderView(_ view: UIView?) -> Self {
tableHeaderView = view
return self
}
@discardableResult
func tableFooterView(_ view: UIView?) -> Self {
tableFooterView = view
return self
}
@discardableResult
func register(for nib: UINib?, cellReuseIdentifier identifier: String) -> Self {
register(nib, forCellReuseIdentifier: identifier)
return self
}
@discardableResult
func register(for cellClass: AnyClass?, cellReuseIdentifier identifier: String) -> Self {
register(cellClass, forCellReuseIdentifier: identifier)
return self
}
@discardableResult
func register(for nib: UINib?, headerFooterViewReuseIdentifier identifier: String) -> Self {
register(nib, forHeaderFooterViewReuseIdentifier: identifier)
return self
}
@discardableResult
func register(for aClass: AnyClass?, headerFooterViewReuseIdentifier identifier: String) -> Self {
register(aClass, forHeaderFooterViewReuseIdentifier: identifier)
return self
}
@discardableResult
func remembersLastFocusedIndexPath(_ bool: Bool) -> Self {
remembersLastFocusedIndexPath = bool
return self
}
@discardableResult
@available(iOS 11.0, *)
func dragInteractionEnabled(_ enabled: Bool) -> Self {
dragInteractionEnabled = enabled
return self
}
}
// MARK: - UITableViewDataSource
public extension UIKitChainable where Self: ChainableTableView {
@discardableResult
func addNumberOfRowsInSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ section: Section)->(Int))) -> Self {
self.numberOfRowsInSectionBlock = handler
return self
}
@discardableResult
public func addCellForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(UITableViewCell))) -> Self {
self.cellForRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addNumberOfSectionsBlock(_ handler: @escaping((_ tableView: UITableView)->(Int))) -> Self {
self.numberOfSectionsBlock = handler
return self
}
@discardableResult
func addTitleForHeaderInSectionBlock(_ handler: @escaping((_ tableView: UITableView, _ section: Section)->(String))) -> Self {
self.titleForHeaderInSectionBlock = handler
return self
}
@discardableResult
func addTitleForFooterInSectionBlock(_ handler: @escaping((_ tableView: UITableView, _ section: Int)->(String))) -> Self {
self.titleForFooterInSectionBlock = handler
return self
}
@discardableResult
func addCanEditRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView, _ indexPath: IndexPath)->(Bool))) -> Self {
self.canEditRowAtIndexPathBlock = handler
return self
}
@discardableResult
func addCanMoveRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView, _ indexPath: IndexPath)->(Bool))) -> Self {
self.canMoveRowAtIndexPathBlock = handler
return self
}
@discardableResult
func addSectionIndexTitlesBlock(_ handler: @escaping((_ tableView: UITableView)->([String]?))) -> Self {
self.sectionIndexTitlesBlock = handler
return self
}
@discardableResult
func addSectionForSectionIndexTitleAtIndexBlock(_ handler: @escaping((_ tableView: UITableView, _ title: String, _ index: Int)->(Int))) -> Self {
self.sectionForSectionIndexTitleAtIndexBlock = handler
return self
}
@discardableResult
func addCommitEditingStyleForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView, _ editingStyle: UITableViewCell.EditingStyle, _ indexPath: IndexPath)->())) -> Self {
self.commitEditingStyleForRowAtIndexPathBlock = handler
return self
}
@discardableResult
func addMoveRowAtSourceIndexPathtoDestinationIndexPathBlock(_ handler: @escaping((_ tableView: UITableView, _ sourceIndexPath: IndexPath,_ destinationIndexPath: IndexPath)->())) -> Self {
self.moveRowAtSourceIndexPathtoDestinationIndexPathBlock = handler
return self
}
}
// MARK: - UITableVieDelegate
public extension UIKitChainable where Self: ChainableTableView {
@discardableResult
public func addWillDisplayCellForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ cell: UITableViewCell, _ indexPath: IndexPath)->())) -> Self {
self.willDisplayCellForRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addWillDisplayHeaderViewForSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ view: UIView, _ section: Section)->())) -> Self {
self.willDisplayHeaderViewForSectionBlock = handler
return self
}
@discardableResult
public func addWillDisplayFooterViewForSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ view: UIView, _ section: Section)->())) -> Self {
self.willDisplayFooterViewForSectionBlock = handler
return self
}
@discardableResult
public func addDidEndDisplayingforRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ cell: UITableViewCell, _ indexPath: IndexPath)->())) -> Self {
self.didEndDisplayingforRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addDidEndDisplayingHeaderViewForSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ view: UIView, _ section: Section)->())) -> Self {
self.didEndDisplayingHeaderViewForSectionBlock = handler
return self
}
@discardableResult
public func addDidEndDisplayingFooterViewforSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ view: UIView, _ section: Section)->())) -> Self {
self.didEndDisplayingFooterViewforSectionBlock = handler
return self
}
@discardableResult
public func addHeightForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(CGFloat))) -> Self {
self.heightForRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addHeightForHeaderInSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ section: Section)->(CGFloat))) -> Self {
self.heightForHeaderInSectionBlock = handler
return self
}
@discardableResult
public func addHeightForFooterInSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ section: Section)->(CGFloat))) -> Self {
self.heightForFooterInSectionBlock = handler
return self
}
// @discardableResult
// public func addEstimatedHeightForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(CGFloat))) -> UITableView {
// setEstimatedHeightForRowAtIndexPathBlock(handler)
// return self
// }
//
// @discardableResult
// public func addEstimatedHeightForHeaderInSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ section: Section)->(CGFloat))) -> UITableView {
// setEstimatedHeightForHeaderInSectionBlock(handler)
// return self
// }
//
// @discardableResult
// public func addEstimatedHeightForFooterInSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ section: Section)->(CGFloat))) -> UITableView {
// setEstimatedHeightForFooterInSectionBlock(handler)
// return self
// }
@discardableResult
public func addViewForHeaderInSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ section: Section)->(UIView?))) -> Self {
self.viewForHeaderInSectionBlock = handler
return self
}
@discardableResult
public func addViewForFooterInSectionBlock(_ handler: @escaping((_ tableView: UITableView,_ section: Section)->(UIView?))) -> Self {
self.viewForFooterInSectionBlock = handler
return self
}
@discardableResult
public func addAccessoryButtonTappedForRowWithBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->())) -> Self {
self.accessoryButtonTappedForRowWithBlock = handler
return self
}
@discardableResult
public func addShouldHighlightRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(Bool))) -> Self {
self.shouldHighlightRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addDidHighlightRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->())) -> Self {
self.didHighlightRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addDidUnhighlightRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->())) -> Self {
self.didUnhighlightRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addWillSelectRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(IndexPath?))) -> Self {
self.willSelectRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addWillDeselectRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(IndexPath?))) -> Self {
self.willDeselectRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addDidSelectRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->())) -> Self {
self.didSelectRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addDidDeselectRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->())) -> Self {
self.didDeselectRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addEditingStyleForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(UITableViewCell.EditingStyle))) -> Self {
self.editingStyleForRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addTitleForDeleteConfirmationButtonForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(String?))) -> Self {
self.titleForDeleteConfirmationButtonForRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addEditActionsForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->([UITableViewRowAction]?))) -> Self {
self.editActionsForRowAtIndexPathBlock = handler
return self
}
// @discardableResult
// @available(iOS 11.0, *)
// public func addLeadingSwipeActionsConfigurationForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(UISwipeActionsConfiguration?))) -> Self {
// self.addLeadingSwipeActionsConfigurationForRowAtIndexPathBlock = handler
// return self
// }
//
// @discardableResult
// @available(iOS 11.0, *)
// public func addTrailingSwipeActionsConfigurationForRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(UISwipeActionsConfiguration?))) -> Self {
// setTrailingSwipeActionsConfigurationForRowAtIndexPathBlock(handler)
// return self
// }
@discardableResult
public func addShouldIndentWhileEditingRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->(Bool))) -> Self {
self.shouldIndentWhileEditingRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addWillBeginEditingRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath)->())) -> Self {
self.willBeginEditingRowAtIndexPathBlock = handler
return self
}
@discardableResult
public func addDidEndEditingRowAtIndexPathBlock(_ handler: @escaping((_ tableView: UITableView,_ indexPath: IndexPath?)->())) -> Self {
self.didEndEditingRowAtIndexPathBlock = handler
return self
}
}
<file_sep>
//
// DDCustomCameraToolView.swift
// DDCustomCamera
//
// Created by USER on 2018/11/15.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
let kBottomViewScale: CGFloat = 0.7
let kTopViewScale: CGFloat = 0.5
let kAnimateDuration: CGFloat = 0.1
protocol DDCustomCameraToolViewDelegate: class {
//拍照
func onTakePicture()
//录制
func onStartRecord()
//结束录制
func onFinishRecord()
//重新拍照或录制
func onRetake()
//点击确定
func onOkClick()
//点击相册
func onPhotoAlbum()
}
class DDCustomCameraToolView: UIView {
private lazy var bottomView: UIView = {
let bottomView = UIView()
bottomView.layer.masksToBounds = true
bottomView.backgroundColor = UIColor.clear
return bottomView
}()
private lazy var tipLab: UILabel = {
let tipLab = UILabel()
tipLab.text = Bundle.localizedString("cameraTip")
tipLab.font = UIFont(name: "PingFangSC-Regular", size: 16)
tipLab.textAlignment = .center
tipLab.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
return tipLab
}()
private lazy var shootBtn: UIButton = {
let btn = UIButton(type: .custom)
if let path = Bundle(for: DDCustomCameraController.classForCoder()).path(forResource: "DDCustomCamera", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "btnShoot", in: bundle, compatibleWith: nil)
{
btn.setImage(image, for: .normal)
}
btn.isUserInteractionEnabled = false
return btn
}()
private lazy var photoAlbumBtn: UIButton = {
let photoAlbumBtn = UIButton(type: .custom)
if let path = Bundle(for: DDCustomCameraController.classForCoder()).path(forResource: "DDCustomCamera", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "photographyGallery", in: bundle, compatibleWith: nil)
{
photoAlbumBtn.setImage(image, for: .normal)
}
photoAlbumBtn.addTarget(self, action: #selector(photoAlbumBtnAction), for: .touchUpInside)
photoAlbumBtn.setTitle(Bundle.localizedString("相册"), for: .normal)
photoAlbumBtn.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 12)
return photoAlbumBtn
}()
private lazy var cancelBtn: UIButton = {
let cancelBtn = UIButton(type: .custom)
if let path = Bundle(for: DDCustomCameraController.classForCoder()).path(forResource: "DDCustomCamera", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "photographyBtnReturn", in: bundle, compatibleWith: nil)
{
cancelBtn.setImage(image, for: .normal)
}
cancelBtn.addTarget(self, action: #selector(retake), for: .touchUpInside)
cancelBtn.layer.masksToBounds = true
cancelBtn.isHidden = true
return cancelBtn
}()
private lazy var doneBtn: UIButton = {
let doneBtn = UIButton(type: .custom)
if let path = Bundle(for: DDCustomCameraController.classForCoder()).path(forResource: "DDCustomCamera", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "photographyBtnSelect", in: bundle, compatibleWith: nil)
{
doneBtn.setImage(image, for: .normal)
}
doneBtn.addTarget(self, action: #selector(doneClick), for: .touchUpInside)
doneBtn.layer.masksToBounds = true
doneBtn.isHidden = true
return doneBtn
}()
private lazy var animateLayer: CAShapeLayer = {
let animateLayer = CAShapeLayer(layer: self)
let width = self.bottomView.frame.height * kBottomViewScale
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width, height: width), cornerRadius: width/2)
animateLayer.strokeColor = self.circleProgressColor.cgColor
animateLayer.fillColor = UIColor.clear.cgColor
animateLayer.path = path.cgPath
animateLayer.lineWidth = 8
return animateLayer
}()
private var layoutOK: Bool = false
private var stopRecord: Bool = false
//layer圆圈的颜色
public var circleProgressColor: UIColor = UIColor(red: 99.0/255.0, green: 181.0/255.0, blue: 244.0/255.0, alpha: 1)
//是否获取限制区域中的图片
public var isShowClipperView: Bool? {
didSet {
if isShowClipperView == true {
tipLab.removeFromSuperview()
photoAlbumBtn.removeFromSuperview()
}
}
}
//是否允许拍照
public var isEnableTakePhoto: Bool? {
didSet {
if isEnableTakePhoto == true {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
bottomView.addGestureRecognizer(tap)
}
}
}
//是否允许摄像
public var isEnableRecordVideo: Bool? {
didSet {
if isEnableRecordVideo == true {
let tap = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
tap.minimumPressDuration = 0.3
tap.delegate = self
bottomView.addGestureRecognizer(tap)
} else {
tipLab.removeFromSuperview()
}
}
}
//最大录制时长
public var maxRecordDuration: Int = 15
//设置代理
public weak var delegate : DDCustomCameraToolViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
if layoutOK == true {
return
}
layoutOK = true
let height = self.frame.size.height
tipLab.frame = CGRect(x: 20, y: -30, width: frame.size.width - 40, height: 25)
bottomView.frame = CGRect(x: 0, y: 0, width: height * kBottomViewScale, height: height * kBottomViewScale)
bottomView.center = CGPoint(x: bounds.midX, y: bounds.midY)
bottomView.layer.cornerRadius = height * kBottomViewScale / 2
shootBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
shootBtn.center = bottomView.center
photoAlbumBtn.frame = CGRect(x: 60, y: bounds.size.height/2-70/2, width: 40, height: 70)
photoAlbumBtn.cameraImagePositionTop()
cancelBtn.frame = bottomView.frame
doneBtn.frame = bottomView.frame
}
deinit {
}
}
extension DDCustomCameraToolView {
public func startAnimate() {
photoAlbumBtn.isHidden = true
tipLab.isHidden = true
bottomView.backgroundColor = UIColor.white
UIView.animate(withDuration: TimeInterval(kAnimateDuration), animations: {
self.bottomView.layer.transform = CATransform3DScale(CATransform3DIdentity, 1.0/kBottomViewScale, 1/kBottomViewScale, 1)
self.shootBtn.layer.transform = CATransform3DScale(CATransform3DIdentity, 0.7, 0.7, 1)
}) { (finished) in
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.toValue = 1
animation.duration = CFTimeInterval(self.maxRecordDuration)
animation.delegate = self
self.animateLayer.add(animation, forKey: nil)
self.bottomView.layer.addSublayer(self.animateLayer)
}
}
}
// MARK: - CAAnimationDelegate
extension DDCustomCameraToolView: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if stopRecord == true {
return
}
stopRecord = true
stopAnimate()
delegate?.onFinishRecord()
}
}
// MARK: - UIGestureRecognizerDelegate
extension DDCustomCameraToolView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
let res1 = gestureRecognizer.isKind(of: UILongPressGestureRecognizer.self)
let res2 = otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
if res1 == true && res2 == true {
return true
}
return false
}
}
private extension DDCustomCameraToolView {
func setupUI() {
addSubview(bottomView)
addSubview(shootBtn)
addSubview(photoAlbumBtn)
addSubview(tipLab)
photoAlbumBtn.frame = CGRect(x: 60, y: bounds.size.height/2-25/2, width: 25, height: 25)
addSubview(cancelBtn)
addSubview(doneBtn)
doneBtn.frame = bottomView.frame
}
func resetUI() {
if animateLayer.superlayer != nil {
animateLayer.removeAllAnimations()
animateLayer.removeFromSuperlayer()
}
photoAlbumBtn.isHidden = false
tipLab.isHidden = false
bottomView.isHidden = false
shootBtn.isHidden = false
cancelBtn.isHidden = true
doneBtn.isHidden = true
cancelBtn.frame = bottomView.frame
doneBtn.frame = bottomView.frame
}
func stopAnimate() {
animateLayer.removeFromSuperlayer()
animateLayer.removeAllAnimations()
bottomView.isHidden = true
shootBtn.isHidden = true
photoAlbumBtn.isHidden = true
tipLab.isHidden = true
bottomView.layer.transform = CATransform3DIdentity
shootBtn.layer.transform = CATransform3DIdentity
bottomView.backgroundColor = UIColor.white
showCancelDoneBtn()
}
func showCancelDoneBtn() {
cancelBtn.isHidden = false
doneBtn.isHidden = false
var cancelRect = cancelBtn.frame
cancelRect.origin.x = 40
var doneRect = doneBtn.frame
doneRect.origin.x = frame.size.width - doneRect.size.width - 40
UIView.animate(withDuration: TimeInterval(kAnimateDuration)) {
self.cancelBtn.frame = cancelRect
self.doneBtn.frame = doneRect
}
}
@objc func photoAlbumBtnAction() {
delegate?.onPhotoAlbum()
}
@objc func retake() {
resetUI()
delegate?.onRetake()
}
@objc func doneClick() {
delegate?.onOkClick()
}
@objc func tapAction(_ tap: UITapGestureRecognizer) {
stopAnimate()
delegate?.onTakePicture()
}
@objc func longPressAction(_ long: UILongPressGestureRecognizer) {
switch long.state {
case .began:
//此处不启动动画,由控制器开始录制后启动
stopRecord = false
delegate?.onStartRecord()
case .cancelled:break
case .ended:
if stopRecord == true {
return
}
stopRecord = true
stopAnimate()
delegate?.onFinishRecord()
default:
break
}
}
}
extension UIView {
func ddCameraViewController () -> UIViewController? {
var next: UIResponder?
next = self.next
repeat {
if (next as? UIViewController) != nil {
return next as? UIViewController
} else {
next = next?.next
}
} while next != nil
return UIViewController()
}
}
extension UIButton {
func cameraImagePositionTop () {
if self.imageView != nil, let titleLabel = self.titleLabel {
let imageSize = self.imageRect(forContentRect: self.frame)
var titleSize = CGRect.zero
if let txtFont = titleLabel.font, let str = titleLabel.text {
titleSize = (str as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: txtFont], context: nil)
}
let spacing: CGFloat = 6
titleEdgeInsets = UIEdgeInsets(top: imageSize.height + titleSize.height + spacing, left: -imageSize.width, bottom: 0, right: 0)
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
}
}
}
<file_sep>//
// TestCController.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/19.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class TestCController: PageTabsBaseController {
let webview = UIWebView()
deinit {
print(self)
}
override func viewDidLoad() {
super.viewDidLoad()
//不需要tableview就移除
tableView.removeFromSuperview()
// 添加webview
webview.backgroundColor = UIColor.white
if let url = URL(string: "http://www.baidu.com") {
webview.loadRequest(URLRequest(url: url))
}
webview.scrollView.delegate = self // 主要是为了在 scrollViewDidScroll: 中处理是否可以滚动
view.addSubview(webview)
webview.backgroundColor = UIColor.white
if #available(iOS 11.0, *) {
webview.scrollView.contentInsetAdjustmentBehavior = .never
webview.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 34, right: 0)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
webview.frame = view.bounds
}
}
<file_sep>
//
// DDPhotoVideoBottom.swift
// PhotoDemo
//
// Created by USER on 2018/11/19.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class DDPhotoVideoBottom: UIView {
weak public var videoView : DDPhotoVideoView?
//进度条slider
lazy private var timeSlider = DDPhotoSlider()
lazy private var currentLab: UILabel = {
let currentLab = UILabel()
currentLab.textColor = UIColor.white
currentLab.font = UIFont.systemFont(ofSize: 12)
currentLab.textAlignment = .center
currentLab.text = "00:00"
return currentLab
}()
lazy private var totalLab: UILabel = {
let totalLab = UILabel()
totalLab.textColor = UIColor.white
totalLab.font = UIFont.systemFont(ofSize: 12)
totalLab.textAlignment = .center
totalLab.text = "00:00"
return totalLab
}()
lazy private var playBtn: UIButton = {
let playBtn = UIButton(type: .custom)
if let path = Bundle(for: DDPhotoSlider.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "video_btn_play", in: bundle, compatibleWith: nil) {
playBtn.setImage(image, for: .normal)
}
playBtn.addTarget(self, action: #selector(playBtnAction(_:)), for: .touchUpInside)
return playBtn
}()
lazy private var fullScreenBtn: UIButton = {
let fullScreenBtn = UIButton(type: .custom)
if let path = Bundle(for: DDPhotoSlider.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "ic_fullscreen", in: bundle, compatibleWith: nil) {
fullScreenBtn.setImage(image, for: .normal)
}
fullScreenBtn.addTarget(self, action: #selector(fullScreenBtnAction(_:)), for: .touchUpInside)
return fullScreenBtn
}()
//是否全屏
private var isFullScreen : Bool = false
//是否拖拽进度条
private var isTimeSliding : Bool = false
private var totalDuration : TimeInterval = 0
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let y = (bounds.height - 25) / 2
playBtn.frame = CGRect(x: 6 , y: y, width: 26, height: 26)
currentLab.frame = CGRect(x: 6 + 15 + 26, y: y, width: 50, height: 25)
let timeSliderW = screenWidth - 6 - 26 - 15 - 50 - 50 - 26 - 15
timeSlider.frame = CGRect(x: 6 + 15 + 26 + 50, y: y, width: timeSliderW, height: 25)
totalLab.frame = CGRect(x: screenWidth - 32 - 15 - 50, y: y, width: 50, height: 25)
fullScreenBtn.frame = CGRect(x: screenWidth - 32, y: y, width: 26, height: 26)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension DDPhotoVideoBottom {
func playerDurationDidChange(_ currentDuration: TimeInterval, totalDuration: TimeInterval) {
self.totalDuration = totalDuration
var current = formatSecondsToString(currentDuration)
if totalDuration.isNaN {
current = "00:00"
}
if isTimeSliding == false {
currentLab.text = current
totalLab.text = formatSecondsToString(totalDuration)
let value = Float(currentDuration / totalDuration)
timeSlider.value = value
}
}
func changePlayBtnImage(_ isPlay: Bool) {
playBtn.isSelected = isPlay
if isPlay == true {
if let path = Bundle(for: DDPhotoSlider.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "video_btn_stop", in: bundle, compatibleWith: nil) {
playBtn.setImage(image, for: .normal)
}
} else {
if let path = Bundle(for: DDPhotoSlider.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "video_btn_play", in: bundle, compatibleWith: nil) {
playBtn.setImage(image, for: .normal)
}
}
}
func changeFullScreenBtnAction(_ isFull: Bool) {
if isFull == true {
if let path = Bundle(for: DDPhotoSlider.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "ic_fullscreen_exit", in: bundle, compatibleWith: nil) {
fullScreenBtn.setImage(image, for: .normal)
}
} else {
if let path = Bundle(for: DDPhotoSlider.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "ic_fullscreen", in: bundle, compatibleWith: nil) {
fullScreenBtn.setImage(image, for: .normal)
}
}
}
@objc func timeSliderValueChanged(_ sender: DDPhotoSlider) {
isTimeSliding = true
let currentTime = Double(sender.value) * totalDuration
currentLab.text = formatSecondsToString(currentTime)
}
@objc func playBtnAction(_ sender: UIButton) {
playBtn.isSelected = !playBtn.isSelected
if playBtn.isSelected == true {
videoView?.play()
} else {
videoView?.pause()
isHidden = false
}
changePlayBtnImage(playBtn.isSelected)
}
@objc func fullScreenBtnAction(_ sender: UIButton) {
fullScreenBtn.isSelected = !fullScreenBtn.isSelected
isFullScreen = fullScreenBtn.isSelected
// NotificationCenter.default.post(name: Notification.Name.DDPhotoFullScreenNotification, object: nil)
changeFullScreenBtnAction(fullScreenBtn.isSelected)
let orientation = UIDevice.current.orientation
if orientation == .portrait {
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
} else {
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
}
@objc internal func deviceOrientationDidChange(_ sender: Notification) {
let orientation = UIDevice.current.orientation
if orientation == .portrait {
fullScreenBtn.isSelected = false
} else {
fullScreenBtn.isSelected = true
}
changeFullScreenBtnAction(fullScreenBtn.isSelected)
}
}
private extension DDPhotoVideoBottom {
func setupUI() {
addSubview(timeSlider)
addSubview(currentLab)
addSubview(totalLab)
addSubview(playBtn)
addSubview(fullScreenBtn)
timeSlider.addTarget(self, action: #selector(timeSliderValueChanged(_:)), for: .valueChanged)
timeSlider.touchChangedCallBack = {[weak self] value in
self?.timeSliderTouchMoved()
}
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
}
func timeSliderTouchMoved() {
isTimeSliding = true
let currentTime = Double(timeSlider.value) * totalDuration
videoView?.seekTime(currentTime, completion: {[weak self] (finished) in
if finished {
self?.isTimeSliding = false
}
})
currentLab.text = formatSecondsToString(currentTime)
}
func formatSecondsToString(_ seconds: TimeInterval) -> String {
if seconds.isNaN{
return "00:00"
}
let interval = Int(seconds)
let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
let min = interval / 60
return String(format: "%02d:%02d", min, sec)
}
}
<file_sep>//
// DevelopSettingVC.swift
// Hotel
//
// Created by senyuhao on 2018/12/3.
// Copyright © 2018 HK01. All rights reserved.
//
import UIKit
class DevelopSettingVC: UITableViewController {
private var currentHost = "" //已经设置的 Host
private var selectedHost = "" //选中或输入的 Host
private var isInput = false
override func viewDidLoad() {
super.viewDidLoad()
configView()
}
private func configView() {
if let hostStr = UserDefaults.standard.value(forKey: "DD-Environment-Host") as? String {
currentHost = hostStr
} else {
currentHost = DevelopManager.shared.currentHost
}
selectedHost = currentHost
navigationItem.title = NSLocalizedString("开发者选项", comment: "")
navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("取消", comment: ""), style: .plain, target: self, action: #selector(cancelBtnClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("确定", comment: ""), style: .plain, target: self, action: #selector(confirmBtnClick))
navigationItem.rightBarButtonItem?.tintColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
navigationItem.leftBarButtonItem?.tintColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
tableView.register(DevelopInputConfigCell.self, forCellReuseIdentifier: "DevelopInputConfigCell")
isInput = !DevelopManager.shared.hostInfos.values.contains(currentHost)
let gesture = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
gesture.delegate = self
tableView.addGestureRecognizer(gesture)
}
// MARK: Action
@objc private func tapAction(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
@objc private func cancelBtnClick() {
view.endEditing(true)
dismiss(animated: true, completion: nil)
}
@objc private func confirmBtnClick() {
view.endEditing(true)
let updateClosure:((_ isChanged: Bool) -> Void) = { [weak self] (isChanged) in
if isChanged {
print("DevelopManager is setting host:\(self?.selectedHost ?? "unKnow host")")
UserDefaults.standard.set(self?.selectedHost, forKey: "DD-Environment-Host")
NotificationCenter.default.post(name: NSNotification.Name("\(DevelopManager.shared.notificationN)"), object: nil)
DevelopManager.shared.changeHostHandle?()
}
self?.dismiss(animated: isChanged, completion: nil)
}
guard selectedHost != currentHost else {
updateClosure(false)
return
}
guard selectedHost.lowercased().contains("http://") else {
self.showAlert("host 输入错误,请重新输入!")
return
}
updateClosure(true)
}
func showAlert(_ message: String) {
let alertController = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
// MARK: - TableView Delegate
extension DevelopSettingVC {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row < DevelopManager.shared.hostInfos.count {
let values = Array(DevelopManager.shared.hostInfos.values)
selectedHost = values[indexPath.row]
tableView.reloadData()
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? DevelopManager.shared.hostInfos.count : 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "DevelopInputConfigCell") as? DevelopInputConfigCell
if DevelopManager.shared.hostInfos.values.contains(selectedHost) {
cell?.updateCell("")
}
else {
cell?.updateCell(selectedHost)
}
cell?.inputBlock = { [weak self] (value, isBeginEdit) in
self?.selectedHost = value
if isBeginEdit {
self?.tableView.reloadSections(IndexSet(arrayLiteral: 0), with: .automatic)
}
}
return cell ?? UITableViewCell()
}
var cell = tableView.dequeueReusableCell(withIdentifier: "devReuseIdentifier")
if cell == nil {
cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "devReuseIdentifier")
}
let keys = Array(DevelopManager.shared.hostInfos.keys)
let values = Array(DevelopManager.shared.hostInfos.values)
cell?.textLabel?.text = "\(keys[indexPath.row])"
cell?.detailTextLabel?.text = "\(values[indexPath.row])"
cell?.accessoryType = values[indexPath.row] == selectedHost ? .checkmark : .none
return cell ?? UITableViewCell()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? NSLocalizedString("host的切换", comment: "") : NSLocalizedString("host的自定义输入", comment: "")
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return section == 1 ? NSLocalizedString("切换host以后应该重新登录", comment: "") : nil
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return section == 0 ? 0.0001 : 30
}
}
// MARK: - UIGestureRecognizerDelegate
extension DevelopSettingVC: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if let touchView = touch.view {
let className = String(describing: touchView.self)
if className.contains("UITableViewCellContentView") {
return false
}
}
return true
}
}
<file_sep>//
// UITextField+Shake.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/9.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public enum ShakeDirection {
case horizontal
case vertical
}
extension UITextField {
/// 输入框震动
///
/// - Parameters:
/// - times: 震动次数
/// - delta: 震动的宽度
/// - speed: shake的持续时间
/// - shakeDirection: 震动的方向
/// - completion: 震动完成回调
public func shake(times: Int = 10, delta: CGFloat = 5, speed: TimeInterval = 0.03, shakeDirection: ShakeDirection = .horizontal, completion: (()->())? = nil) {
_shake(times: times, direction: 1, currentTimes: 0, delta: delta, speed: speed, shakeDirection: shakeDirection, completion: completion)
}
}
extension UITextField {
fileprivate func _shake(times: Int, direction: Int, currentTimes: Int, delta: CGFloat, speed: TimeInterval, shakeDirection: ShakeDirection, completion:(()->())?) {
UIView.animate(withDuration: speed, animations: {[weak self] in
self?.transform = (shakeDirection == .horizontal) ? CGAffineTransform(translationX: delta * CGFloat(direction), y: 0) : CGAffineTransform(translationX: 0, y: delta * CGFloat(direction))
}) {[weak self] (finished) in
if currentTimes >= times {
UIView.animate(withDuration: speed, animations: {
self?.transform = .identity
}, completion: { (finished) in
completion?()
})
return
}
self?._shake(times: times - 1, direction: direction * -1, currentTimes: currentTimes + 1, delta: delta, speed: speed, shakeDirection: shakeDirection, completion: completion)
}
}
}
<file_sep>
//
// DDPhotoBrowerController.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/11/22.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import Photos
//import DDKit
let kPhotoViewPadding: CGFloat = 10
class DDPhotoBrowerController: UIViewController {
public var previousStatusBarStyle: UIStatusBarStyle = .default
/// 是否需要显示状态栏
public var isStatusBarShow: Bool = false {
didSet {
self.setNeedsStatusBarAppearanceUpdate()
}
}
///滑动消失时是否隐藏原来的视图
public var isHideSourceView: Bool = false
///横屏时是否充满屏幕宽度,默认YES,为NO时图片自动填充屏幕
public var isFullWidthForLandSpace: Bool = true
/// 长按是否自动保存图片到相册,若为true,则长按代理不在回调。若为false,返回长按代理
public var isLongPressAutoSaveImageToAlbum: Bool = true
/// 配置保存图片权限提示
public var photoPermission: String = "请在iPhone的\"设置-隐私-照片\"选项中,允许访问您的照片"
/// 当前索引
public var currentIndex: Int = 0
public weak var deleagte: DDPhotoBrowerDelegate?
public lazy var contentView: UIView = UIView()
private lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.hidesForSinglePage = true
return pageControl
}()
private var photos: [DDPhoto]?
private var isPortraitToUp: Bool = true
private var isStatusBarShowing: Bool = false
private var isDismissing: Bool = false
private var photoCollectionView: UICollectionView?
private let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//旋转之前index
private var isDrag: Bool = false
private lazy var singleTap:UITapGestureRecognizer = {
let single = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(_:)))
return single
}()
private lazy var doubleTap: UITapGestureRecognizer = {
let tap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
return tap
}()
private lazy var longPress: UILongPressGestureRecognizer = {
let long = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
return long
}()
/// 拖拽手势
private lazy var panGesture: UIPanGestureRecognizer = {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
return panGesture
}()
public init(Photos photos: [DDPhoto]?, currentIndex: Int?) {
super.init(nibName: nil, bundle: nil)
self.photos = photos
self.currentIndex = currentIndex ?? 0
let photo = photos?[self.currentIndex]
photo?.isFirstPhoto = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
addGestureRecognizer()
NotificationCenter.default.addObserver(self, selector: #selector(closeNotification), name: NSNotification.Name("PhotoBrowserVideoViewCloseKey"), object: nil)
}
@objc func closeNotification() {
handleSingleTap(singleTap)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if isDismissing {
return
}
layoutSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//代理回调
deleagte?.photoBrowser(controller: self, didChanged: currentIndex)
}
deinit {
photoCollectionView?.removeFromSuperview()
photoCollectionView = nil
photos?.removeAll()
photos = nil
NotificationCenter.default.removeObserver(self)
}
}
extension DDPhotoBrowerController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//图片cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DDPhotoBrowerCell", for: indexPath) as! DDPhotoBrowerCell
let photo = photos?[indexPath.row]
if photo?.isFirstPhoto == true {
cell.browserZoomShow(photo)
} else {
cell.photoView.setupPhoto(photo)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let photoView = (cell as! DDPhotoBrowerCell).photoView
photoView.scrollView.setZoomScale(1, animated: false)
//判断cell是否是视屏,若是则停止播放
if let photo = photos?[indexPath.row],
photo.isVideo == true,
photoView.videoView.isPlay() == true {
photoView.videoView.reset()
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
}
}
// MARK: - UIScrollViewDelegate
extension DDPhotoBrowerController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isDrag = true
//拖拽的时候停止播放gif
guard let photo = currentPhoto() else {
return
}
if photo.isGif == true {
currentPhotoView().imageView.stopAnimating()
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
currentIndex = Int(round(scrollView.contentOffset.x/scrollView.bounds.width))
if let count = photos?.count {
if currentIndex >= count {
currentIndex = count - 1
}
if currentIndex < 0 {
currentIndex = 0
}
}
removeGestureRecognizer()
pageControl.isHidden = true
if currentPhoto()?.isVideo == false {
addGestureRecognizer()
pageControl.isHidden = false
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
isDrag = false
let offsetX = scrollView.contentOffset.x
let scrollW = photoCollectionView?.frame.width ?? 0
let index: Int = Int((offsetX + scrollW * 0.5) / scrollW)
pageControl.currentPage = index
//代理回调
deleagte?.photoBrowser(controller: self, didChanged: index)
if (currentPhotoView().scrollView.zoomScale) > CGFloat(1.0) {
removePanGesture()
} else {
addPanGesture(false)
}
//当前停止的cell若为播放gif,则播放
guard let photo = currentPhoto() else {
return
}
if photo.isGif == true {
currentPhotoView().imageView.startAnimating()
}
}
}
// MARK: - private method
private extension DDPhotoBrowerController {
/// 获取当前的photo
func currentPhoto() -> DDPhoto? {
if currentIndex >= (photos?.count ?? 0) {
return nil
}
return photos?[currentIndex]
}
/// 获取当前cell中的photoView
///
/// - Returns: photoView
func currentPhotoView() -> DDPhotoView {
let indexPath = IndexPath(row: currentIndex, section: 0)
let cell = photoCollectionView?.cellForItem(at: indexPath) as! DDPhotoBrowerCell
return cell.photoView
}
/// 设置UI
func setupUI() {
view.backgroundColor = UIColor.black
contentView.backgroundColor = UIColor.clear
contentView.clipsToBounds = true
view.addSubview(contentView)
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
let DDPhotoScreenWidth: CGFloat = UIScreen.main.bounds.size.width
let DDPhotoScreenHeight: CGFloat = UIScreen.main.bounds.size.height
flowLayout.itemSize = CGSize(width: DDPhotoScreenWidth + 10, height: DDPhotoScreenHeight)
photoCollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: DDPhotoScreenWidth + 10, height: DDPhotoScreenHeight), collectionViewLayout: flowLayout)
if let photoCollectionView = photoCollectionView {
photoCollectionView.isPagingEnabled = true
photoCollectionView.register(DDPhotoBrowerCell.self,
forCellWithReuseIdentifier: "DDPhotoBrowerCell")
photoCollectionView.delegate = self
photoCollectionView.dataSource = self
photoCollectionView.backgroundColor = UIColor.clear
photoCollectionView.showsVerticalScrollIndicator = false
photoCollectionView.showsHorizontalScrollIndicator = false
contentView.addSubview(photoCollectionView)
if #available(iOS 11.0, *) {
photoCollectionView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
photoCollectionView.reloadData()
}
contentView.addSubview(pageControl)
pageControl.numberOfPages = photos?.count ?? 0
pageControl.currentPage = currentIndex
}
/// 添加手势
func addGestureRecognizer() {
singleTap.numberOfTapsRequired = 1
view.addGestureRecognizer(singleTap)
/// 添加双击手势
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
/// 双击时,单击失效
singleTap.require(toFail: doubleTap)
view.addGestureRecognizer(longPress)
/// 添加拖拽手势
addPanGesture(true)
}
func removeGestureRecognizer() {
if view.gestureRecognizers?.contains(singleTap) == true {
view.removeGestureRecognizer(singleTap)
}
if view.gestureRecognizers?.contains(doubleTap) == true {
view.removeGestureRecognizer(doubleTap)
}
if view.gestureRecognizers?.contains(longPress) == true {
view.removeGestureRecognizer(longPress)
}
}
func addPanGesture(_ isFirst: Bool) {
if isFirst == true {
view.addGestureRecognizer(panGesture)
return
}
let orientation = UIDevice.current.orientation
if orientation.isPortrait == true || isPortraitToUp == true {
view.addGestureRecognizer(panGesture)
}
}
func removePanGesture() {
if view.gestureRecognizers?.contains(panGesture) == true {
view.removeGestureRecognizer(panGesture)
}
}
func recoverAnimation() {
let orientation = UIDevice.current.orientation
let screenBounds = UIScreen.main.bounds
if orientation.isLandscape {
UIView.animate(withDuration: 0.25, animations: {
//旋转contentView
self.contentView.transform = .identity
let height: CGFloat = CGFloat.maximum(screenBounds.width, screenBounds.height)
//设置frame
self.contentView.bounds = CGRect(x: 0, y: 0, width: CGFloat.minimum(screenBounds.size.width, screenBounds.size.height), height: height)
self.contentView.center = UIApplication.shared.keyWindow?.center ?? CGPoint(x: 0, y: 0)
self.layoutSubviews()
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}) { (finished) in
self.showDismissAnimation()
}
} else {
self.showDismissAnimation()
}
}
func showDismissAnimation() {
let photoView = currentPhotoView()
let photo = photos?[currentIndex]
//结束位置
var sourceRect = photo?.sourceFrame
if sourceRect?.equalTo(CGRect.zero) == true || sourceRect == nil {
if photo?.sourceImageView == nil {
UIView.animate(withDuration: 0.25, animations: {
self.view.alpha = 0
}) { (finished) in
self.dismissAnimated(false)
}
return
}
if isHideSourceView {
photo?.sourceImageView?.alpha = 0
}
sourceRect = photo?.sourceImageView?.superview?.convert(photo?.sourceImageView?.frame ?? CGRect.zero, to: contentView)
} else {
if isHideSourceView && (photo?.sourceImageView != nil) {
photo?.sourceImageView?.alpha = 0
}
}
//起始位置
let originRect = photoView.imageView.frame
//动画image
let animationImage = UIImageView(image: photoView.imageView.image)
animationImage.frame = originRect
view.addSubview(animationImage)
//先隐藏
contentView.isHidden = true
photoCollectionView?.isHidden = true
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
animationImage.frame = sourceRect ?? CGRect.zero
self.view.backgroundColor = UIColor.clear
}) { (finished) in
animationImage.removeFromSuperview()
self.dismissAnimated(false)
self.panEndedWillDisappear(false)
}
}
func panEndedWillDisappear(_ disappear: Bool) {
//代理
}
func dismissAnimated(_ animated:Bool) {
let photo = currentPhoto()
if animated {
UIView.animate(withDuration: 0.25) {
photo?.sourceImageView?.alpha = 1
}
} else {
photo?.sourceImageView?.alpha = 1
}
//代理回调
deleagte?.photoBrowser(controller: self, willDismiss: currentIndex)
dismiss(animated: false, completion: nil)
}
func layoutSubviews() {
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
contentView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flowLayout.itemSize = CGSize(width: screenWidth + 10, height: screenHeight)
photoCollectionView?.frame = CGRect(x: 0, y: 0, width: screenWidth + 10, height: screenHeight)
//滚动cell
if isDrag == false {
photoCollectionView?.setContentOffset(CGPoint(x: Int(screenWidth + 10) * currentIndex, y: 0), animated: false)
}
//pageControl
pageControl.center = CGPoint(x: UIScreen.main.bounds.width * 0.5, y: UIScreen.main.bounds.height - 20)
}
func frameWithWidth(_ width: CGFloat, height: CGFloat, center: CGPoint) -> CGRect {
let x = center.x - width * 0.5
let y = center.y - height * 0.5
return CGRect(x: x, y: y, width: width, height: height)
}
func showCancelAnimation() {
let photoView = currentPhotoView()
let photo = photos?[currentIndex]
photo?.sourceImageView?.alpha = 1
UIView.animate(withDuration: 0.25, animations: {
photoView.imageView.transform = .identity
self.view.backgroundColor = UIColor.black
}) { (finished) in
if self.isStatusBarShowing == false {
self.isStatusBarShow = false
}
self.panEndedWillDisappear(false)
}
}
func handlePanBegin() {
let photo = currentPhoto()
if isHideSourceView == true {
photo?.sourceImageView?.alpha = 0
}
isStatusBarShowing = isStatusBarShow
//显示状态栏
isStatusBarShow = true
}
func handlePanZoomScale(_ panGesture: UIPanGestureRecognizer) {
let point = panGesture.translation(in: view)
// let location = panGesture.location(in: view)
let velocity = panGesture.velocity(in: view)
let photoView = currentPhotoView()
isDrag = true
switch panGesture.state {
case .began:
handlePanBegin()
break
case .changed:
photoView.imageView.transform = CGAffineTransform(translationX: 0, y: point.y)
var percent: CGFloat = CGFloat(1.0 - abs(point.y) / view.frame.height)
percent = CGFloat.maximum(percent, 0)
let s: CGFloat = CGFloat.maximum(percent, 0.5)
let translation = CGAffineTransform(translationX: point.x / s, y: point.y / s);
let scale = CGAffineTransform(scaleX: s, y: s)
photoView.imageView.transform = translation.concatenating(scale)
view.backgroundColor = UIColor.black.withAlphaComponent(percent)
break
case .ended, .cancelled:
if (abs(point.y) > 200) || (abs(velocity.y) > 500) {
showDismissAnimation()
} else {
showCancelAnimation()
}
isDrag = false
break
default:
break
}
}
func libraryAuthorization() {
let authorStatus = PHPhotoLibrary.authorizationStatus()
switch authorStatus {
case .notDetermined: //未确定 申请
PHPhotoLibrary.requestAuthorization { (status) in
//没有授权直接退出
if status != .authorized {
return;
}
}
break
case .restricted: break
case .denied:
showAlertNoAuthority(photoPermission)
return
case .authorized:
showAlertSaveImage()
break
default:
break
}
}
func showAlertSaveImage() {
//弹窗提示
let alertVC = UIAlertController(title: "保存图片到手机", message: "", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .default) { (action) in
}
let actionCommit = UIAlertAction(title: "确定", style: .default) {[weak self] (action) in
self?.saveImageToAlbum()
}
alertVC.addAction(cancelAction)
alertVC.addAction(actionCommit)
present(alertVC, animated: true, completion: nil)
}
func saveImageToAlbum() {
let photo = photos?[currentIndex]
guard let image = photo?.image else {
return
}
UIImageWriteToSavedPhotosAlbum(image, self, #selector(saved(image:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func saved(image: UIImage, didFinishSavingWithError erro: NSError?, contextInfo: AnyObject) {
if erro != nil {
print("错误")
return
}
print("ok")
}
/// 显示无授权信息
///
/// - Parameter text: 标题
func showAlertNoAuthority(_ text: String?) {
//弹窗提示
let alertVC = UIAlertController(title: "温馨提示", message: text, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .default) { (action) in
}
let actionCommit = UIAlertAction(title: "去设置", style: .default) { (action) in
//去设置
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
alertVC.addAction(cancelAction)
alertVC.addAction(actionCommit)
present(alertVC, animated: true, completion: nil)
}
}
// MARK: - 手势事件响应
extension DDPhotoBrowerController {
@objc func handleDoubleTap(_ tap: UITapGestureRecognizer) {
let photoView = currentPhotoView()
let photo = photos?[currentIndex]
if photo?.isFinished == false {
return
}
if (photoView.scrollView.zoomScale) > CGFloat(1.0) {
photoView.scrollView.setZoomScale(1.0, animated: true)
photo?.isZooming = false
addPanGesture(true)
} else {
let location = tap.location(in: contentView)
let wh: CGFloat = 1.0
let zoomRect = frameWithWidth(wh, height: wh, center: location)
photoView.zoomToRect(zoomRect, animated: true)
photo?.isZooming = true
photo?.zoomRect = zoomRect
// 放大情况下移除滑动手势
removePanGesture()
}
}
@objc func handlePanGesture(_ tap: UIPanGestureRecognizer) {
// 放大时候禁止滑动返回
let photoView = currentPhotoView()
if (photoView.scrollView.zoomScale) > CGFloat(1.0) {
return
}
handlePanZoomScale(tap)
}
@objc func handleLongPress(_ tap: UILongPressGestureRecognizer) {
switch tap.state {
case .began:
if isLongPressAutoSaveImageToAlbum == true {
libraryAuthorization()
} else {
//代理回调
deleagte?.photoBrowser(controller: self, longPress: currentIndex)
}
break
case .ended:
break
default:
break
}
}
@objc func handleSingleTap(_ tap: UITapGestureRecognizer) {
isDismissing = true
//显示状态栏
isStatusBarShow = true
self.showDismissAnimation()
}
}
// MARK: - 禁止屏幕旋转
extension DDPhotoBrowerController {
override public var shouldAutorotate: Bool {
return false
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .portrait
}
/// 隐藏状态栏
override public var prefersStatusBarHidden: Bool {
return !isStatusBarShow
}
override public var preferredStatusBarStyle: UIStatusBarStyle {
return previousStatusBarStyle
}
}
<file_sep>source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/aliyun/aliyun-specs.git'
source 'https://github.com/hk01-digital/hk01-ios-uikit-spec.git'
platform :ios, '9.0'
target 'DDPhotoBrowserDemo' do
use_frameworks!
pod 'Kingfisher', '4.9.0'
#pod 'DDKit/Hud'
#pod 'DDKit/PhotoBrowser'
end
<file_sep>//
// UIKit+Chain.swift
// UIKit
//
// Created by 胡峰 on 2017/7/19.
// Copyright © 2017年 . All rights reserved.
//
import UIKit
// 使用 extension UIKitChainable where Self: UIView 而非直接使用 extension UIView 的方式扩展
// 是因为 Xcode(目前到 9 仍有问题)代码无法自动提示问题:父类方法 -> Self 后,无法自动提示子类的成员,但编译无问题
//自定义的两个类型
public typealias Section = Int
public typealias ElementKind = String
public protocol Chainable {}
public protocol UIKitChainable: Chainable {}
extension UIView: UIKitChainable {}
// MARK: - UIView便利构造器
public extension UILabel {
/// 初始化 UILabel 对象,并设置好常用的属性
///
/// - Parameters:
/// - text: 需要显示的文字
/// - size: 字体大小,支持数字(默认为system字体),UIFont类型
/// - color: 文字颜色,默认 .black
/// - background: view 的背景色,默认 .clear
convenience init(text: String?, font: UIFontType, color: UIColor = .black, background: UIColor = .clear) {
self.init()
self.text = text
self.font = font.font
textColor = color
backgroundColor = background
}
}
public extension UIButton {
/// 初始化 .system 类型的按钮,文字默认使用 tintColor 的颜色
///
/// - Parameters:
/// - text: .normal 状态的字体大小
/// - font: 字体大小,支持数字(默认为system字体),UIFont类型
/// - color: .normal 状态的字体颜色,默认值 nil,显示 tintColor 的颜色
/// - image: 按钮图片,默认值 nil
convenience init(text: String?, font: UIFontType, color: UIColor? = nil, image: UIImage? = nil) {
self.init(type: .system)
setTitle(text, for: .normal)
setTitleColor(color, for: .normal)
titleLabel?.font = font.font
setImage(image, for: .normal)
}
}
extension UIImageView {
/// 初始化 UIImageView,并设置 image 和显示模式
///
/// - Parameters:
/// - image: 显示的图片
/// - mode: 显示模式 `contentMode`
convenience init(image: UIImage, mode: UIView.ContentMode) {
self.init(image: image)
self.contentMode = mode
}
}
// MARK: - UIFont
/// UIFont字体,已实现 Int,Double,UIFont 返回 UIFont 对象
public protocol UIFontType {
var font: UIFont { get }
}
extension Int: UIFontType {
public var font: UIFont { return UIFont.systemFont(ofSize: CGFloat(self)) }
}
extension Double: UIFontType {
public var font: UIFont { return UIFont.systemFont(ofSize: CGFloat(self)) }
}
extension CGFloat: UIFontType {
public var font: UIFont { return UIFont.systemFont(ofSize: self) }
}
extension UIFont: UIFontType {
public var font: UIFont { return self }
}
<file_sep>//
// BrowserController.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/12/13.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import Kingfisher
class BrowserController: UIViewController {
@IBOutlet weak var imageViewA: UIImageView!
@IBOutlet weak var imageViewB: UIImageView!
@IBOutlet weak var imageViewC: UIImageView!
@IBOutlet weak var imageViewD: UIImageView!
@IBOutlet weak var imageViewE: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
addTap()
}
deinit {
print(self)
}
func addTap() {
imageViewA.isUserInteractionEnabled = true
imageViewB.isUserInteractionEnabled = true
imageViewC.isUserInteractionEnabled = true
imageViewD.isUserInteractionEnabled = true
imageViewE.isUserInteractionEnabled = true
imageViewA.contentMode = .scaleAspectFill
imageViewB.contentMode = .scaleAspectFill
imageViewC.contentMode = .scaleAspectFill
imageViewD.contentMode = .scaleAspectFill
imageViewE.contentMode = .scaleAspectFill
imageViewA.clipsToBounds = true
imageViewB.clipsToBounds = true
imageViewC.clipsToBounds = true
imageViewD.clipsToBounds = true
imageViewE.clipsToBounds = true
let tap1 = UITapGestureRecognizer(target: self, action: #selector(tagAGesture))
imageViewA.addGestureRecognizer(tap1)
let tap2 = UITapGestureRecognizer(target: self, action: #selector(tagBGesture))
imageViewB.addGestureRecognizer(tap2)
let tap3 = UITapGestureRecognizer(target: self, action: #selector(tagCGesture))
imageViewC.addGestureRecognizer(tap3)
let tap4 = UITapGestureRecognizer(target: self, action: #selector(tagDGesture))
imageViewD.addGestureRecognizer(tap4)
let tap5 = UITapGestureRecognizer(target: self, action: #selector(tagEGesture))
imageViewE.addGestureRecognizer(tap5)
let url1 = URL(string: "http://dd01-test-d0.oss-cn-shenzhen.aliyuncs.com/20181207/0ed36a0dea9c7feaf2e4886c393adfb7.jpeg")
imageViewA.kf.setImage(with: url1)
let url2 = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056728983&di=0377ea3d0ef5acdefe8863c1657a67f4&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e90159a5094ba801211d25bec351.jpg")
imageViewB.kf.setImage(with: url2)
let url3 = URL(string: "http://img1.mydrivers.com/img/20171008/s_da7893ed38074cbc994e0ff3d85adeb5.jpg")
imageViewC.kf.setImage(with: url3)
// let url4 = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056728983&di=0377ea3d0ef5acdefe8863c1657a67f4&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e90159a5094ba801211d25bec351.jpg")
let url4 = URL(string: "https://i10.hoopchina.com.cn/hupuapp/bbs/154271663700897/thread_154271663700897_20181211163908_s_6365730_w_360_h_209_99511.gif")
imageViewD.kf.setImage(with: url4)
let url5 = URL(string: "http://dd01-test-d0.oss-cn-shenzhen.aliyuncs.com/20181207/0ed36a0dea9c7feaf2e4886c393adfb7.jpeg")
imageViewE.kf.setImage(with: url5)
}
@objc func tagAGesture() {
showImage(index: 0)
}
@objc func tagBGesture() {
showImage(index: 1)
}
@objc func tagCGesture() {
showImage(index: 2)
}
@objc func tagDGesture() {
showImage(index: 3)
}
@objc func tagEGesture() {
showImage(index: 4)
}
func showImage(index: Int) {
var photos = [DDPhoto]()
let photo1 = DDPhoto()
photo1.url = URL(string: "http://dd01-test-d0.oss-cn-shenzhen.aliyuncs.com/20181207/0ed36a0dea9c7feaf2e4886c393adfb7.jpeg")
photo1.sourceImageView = imageViewA
let photo2 = DDPhoto()
photo2.url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056728983&di=0377ea3d0ef5acdefe8863c1657a67f4&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e90159a5094ba801211d25bec351.jpg")
photo2.sourceImageView = imageViewB
let photo3 = DDPhoto()
photo3.url = URL(string: "http://img1.mydrivers.com/img/20171008/s_da7893ed38074cbc994e0ff3d85adeb5.jpg")
photo3.sourceImageView = imageViewC
let photo4 = DDPhoto()
// photo4.url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056728983&di=0377ea3d0ef5acdefe8863c1657a67f4&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e90159a5094ba801211d25bec351.jpg")
photo4.url = URL(string: "https://i10.hoopchina.com.cn/hupuapp/bbs/154271663700897/thread_154271663700897_20181211163908_s_6365730_w_360_h_209_99511.gif")
// https://i10.hoopchina.com.cn/hupuapp/bbs/154271663700897/thread_154271663700897_20181211163908_s_6365730_w_360_h_209_99511.gif
photo4.sourceImageView = imageViewD
let photo5 = DDPhoto()
photo5.url = URL(string: "http://tb-video.bdstatic.com/videocp/12045395_f9f87b84aaf4ff1fee62742f2d39687f.mp4")
photo5.sourceImageView = imageViewE
photos.append(photo1)
photos.append(photo2)
photos.append(photo3)
photos.append(photo4)
photos.append(photo5)
let browser = DDPhotoBrower.photoBrowser(Photos: photos, currentIndex: index)
browser.delegate = self
browser.photoPermission = "开启相册权限,方便将图片保存到相册"
browser.show()
}
}
extension BrowserController : DDPhotoBrowerDelegate {
/// 索引值改变
///
/// - Parameter index: 索引
func photoBrowser(controller: UIViewController?, didChanged index: Int?) {
// print(controller)
}
/// 单击事件,即将消失
///
/// - Parameter index: 索引
func photoBrowser(controller: UIViewController?, willDismiss index: Int?) {
// print(controller)
}
/// 长按事件事件
///
/// - Parameter index: 索引
func photoBrowser(controller: UIViewController?, longPress index: Int?) {
// print(controller)
}
}
<file_sep>//
// Timer+Block.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/23.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
extension Timer {
public class func scheduledTimerWithTimeInterval(_ timeInterval: TimeInterval, block: @escaping()->(), repeats: Bool) -> Timer {
return self.scheduledTimer(timeInterval: timeInterval, target:
self, selector: #selector(self.blcokInvoke(_:)), userInfo: block, repeats: repeats)
}
@objc class func blcokInvoke(_ timer: Timer) {
let block: ()->() = timer.userInfo as! ()->()
block()
}
}
<file_sep>//
// DDVideoPlayerUtils.swift
// mpdemo
//
// Created by leo on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import UIKit
public enum DDVideoPlayerMediaFormat : String{
case unknown
case mpeg4
case m3u8
case mov
case m4v
case error
}
class DDVideoPlayerUtils: NSObject {
// static public func playerBundle() -> Bundle {
// if let path = Bundle(for: DDVideoPlayer.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"), let bundle = Bundle(path: path) {
// return bundle
// }
// return Bundle(for: DDVideoPlayer.self)
// }
// static public func fileResource(_ fileName: String, fileType: String) -> String? {
// let bundle = playerBundle()
// let path = bundle.path(forResource: fileName, ofType: fileType)
// return path
// }
// static public func imageResource(_ name: String) -> UIImage? {
// let bundle = playerBundle()
//// return UIImage(named: "DDVideoPlayer.bundle/" + name)
// return UIImage(named: name, in: bundle, compatibleWith: nil)
// }
//
static func imageSize(image: UIImage?, scaledToSize newSize: CGSize) -> UIImage? {
guard let tmpImage = image else {
return nil
}
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
tmpImage.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage;
}
static func decoderVideoFormat(_ URL: URL?) -> DDVideoPlayerMediaFormat {
if URL == nil {
return .error
}
if let path = URL?.absoluteString{
if path.contains(".mp4") {
return .mpeg4
} else if path.contains(".m3u8") {
return .m3u8
} else if path.contains(".mov") {
return .mov
} else if path.contains(".m4v"){
return .m4v
} else {
return .unknown
}
} else {
return .error
}
}
}
<file_sep>//
// RouterURL.swift
// Route
//
// Created by 鞠鹏 on 2018/6/5.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
public class RouterURL: NSObject {
/// 使用的URL 格式 scheme://module/page?param1=xxx¶m2=xxx
public var route: String
///保存param
public var params: [String: Any]?
public init?(route: String, urlStr: String) {
guard URL(string: route) != nil else {
return nil
}
guard let routeOfUrlStr = RouterURL.route(urlStr: urlStr) else {
return nil
}
guard routeOfUrlStr == route else {
return nil
}
self.route = route
self.params = RouterURL.params(urlStr: urlStr)
}
public convenience init?(urlStr: String) {
guard let route = RouterURL.route(urlStr: urlStr) else {
return nil
}
self.init(route: route, urlStr: urlStr)
}
/// url 路由解析
///
/// param url: string
/// return: 路由模版
public static func route(urlStr: String) -> String? {
guard let url = URL(string: urlStr) else {
return nil
}
let query = url.query ?? ""
var route = urlStr.replacingOccurrences(of: query, with: "")
route = route.replacingOccurrences(of: "?", with: "")
if route.hasSuffix("/") {
var characterSet = CharacterSet()
characterSet.insert(charactersIn: "/")
route = route.trimmingCharacters(in: characterSet)
}
return route
}
/// url 解析
///
/// param url: string
/// return: params
public static func params(urlStr: String) -> [String: String]? {
let url = URL(string: urlStr)
guard let query = url?.query else {
return nil
}
var params = [String: String]()
let sections = query.components(separatedBy: "&")
sections.forEach {
guard let separatorIndex = $0.index(of: "=") else {
return
}
let keyRange = $0.startIndex..<separatorIndex
let valueRange = $0.index(after: separatorIndex)..<$0.endIndex
let key = String($0[keyRange])
let value = $0[valueRange].removingPercentEncoding ?? String($0[valueRange])
params[key] = value
}
return params
}
}
<file_sep>//
// PhotoTableVC.swift
// Example
//
// Created by senyuhao on 2018/7/4.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
class PhotoTableVC: UITableViewController {
var images = [UIImage]()
var items = ["SingleLocalPhoto",
"MutipleLocalPhotos",
"BrowserOnly",
"BrowserAndDelete",
"SingleOrginalPhoto",
"Camera",
"Camera origial",
"BrowserThenUpadte"]
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "图片相关"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") {
cell.textLabel?.text = items[indexPath.row]
return cell
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
// PhotoHelper.shared.chooseSingleLocalPhoto(basevc: self,
// handler: { [weak self] value in
// print(value)
// self?.images = value
// },
// permission: {
// print("无权限")
// })
} else if indexPath.row == 1 {
// PhotoHelper.shared.rightItemTintColor = #colorLiteral(red: 0.9487375617, green: 0.4749935865, blue: 0.434479177, alpha: 1)
// PhotoHelper.shared.chooseLocalPhotos(basevc: self,
// imagesCount: 3,
// handler: { [weak self] value in
// print(value)
// self?.images = value
// },
// permission: {
// print("无权限")
// })
} else if indexPath.row == 2 {
// if !images.isEmpty {
// let list: [PhotoAsset] = images.map { value -> PhotoAsset in
// PhotoAsset(image: value)
// }
// PhotoHelper.shared.browser(basevc: self, list: list, index: 0)
// }
} else if indexPath.row == 3 {
// if !images.isEmpty {
// let list: [PhotoAsset] = images.map { value -> PhotoAsset in
// PhotoAsset(image: value)
// }
// PhotoHelper.shared.browserThenDelete(basevc: self, list: list, index: 0) { value in
// print(value)
// }
// }
} else if indexPath.row == 4 {
// PhotoHelper.shared.chooseSingleOriginalPhoto(basevc: self,
// handler: { value in
// print(value)
// },
// permission: {
// print("无权限")
// })
} else if indexPath.row == 5 {
// PhotoHelper.shared.cameraOperation(basevc: self,
// handler: { value in
// print(value)
// },
// permission: {
// print("无权限")
// })
} else if indexPath.row == 6 {
// PhotoHelper.shared.cameraOriginalOperation(basevc: self,
// handler: { value in
//
// if let image = value.first {
// print(image)
//
// if let jpeg = UIImageJPEGRepresentation(image, 0.1),
// let jpegImage = UIImage(data: jpeg),
// let fix = jpegImage.fixOrientation() {
// if jpeg.count / 1_024 / 1_024 > 2 {
// print("123")
// }
// print(fix)
// print(jpeg)
// self.images = [fix]
// }
//
//// self.images = [temp]
// }
// },
// permission: {
//
// })
} else if indexPath.row == 7 {
// let item = UIBarButtonItem(title: "123", style: .plain, target: self, action: #selector(actionItem))
// let list: [PhotoAsset] = images.map { value -> PhotoAsset in
// PhotoAsset(image: value)
// }
// if !list.isEmpty {
// PhotoHelper.shared.browserThenUpdate(basevc: self, asset: list[0], item: item) { _ in
// print("234")
// }
// } else {
// print("控制")
// }
}
}
@objc private func actionItem() {
if let window = UIApplication.shared.keyWindow {
SheetTool.shared.show(value: (title: nil, message: "infomessage"), cancel: "取消", titles: ["2", "1"], target: window) { tag in
print(tag)
}
}
}
}
<file_sep>//
// DDPhotoPickerConfig.swift
// Photo
//
// Created by USER on 2018/10/24.
// Copyright © 2018年 leo. All rights reserved.
//
import Foundation
import UIKit
import Photos
/// 导航条高度(不包含状态栏高度)默认44
let DDPhotoNavigationHeight: CGFloat = 44
var DDPhotoScreenWidth: CGFloat = UIScreen.main.bounds.size.width
var DDPhotoScreenHeight: CGFloat = UIScreen.main.bounds.size.height
var DDPhotoStatusBarHeight: CGFloat = DDPhotoIsiPhoneX.isIphonex() ? 44 : 20
let DDPhotoNavigationTotalHeight: CGFloat = DDPhotoStatusBarHeight + DDPhotoNavigationHeight
let DDPhotoHomeBarHeight: CGFloat = DDPhotoIsiPhoneX.isIphonex() ? 34 : 0
//底部view
let DDPhotoPickerBottomViewHeight: CGFloat = 52
//图片相关 cell显示加载图片的size
let DDPhotoPickerBreviaryPhotoWidth = 140.0
let DDPhotoPickerBreviaryPhotoHeight = 140.0
let selectEnableColor = UIColor(red: 67/255.0, green: 116/255.0, blue: 255/255.0, alpha: 1)
let selectNotEnableColor = UIColor(red: 108/255.0, green: 108/255.0, blue: 108/255.0, alpha: 1)
public class DDPhotoIsiPhoneX {
static public func isIphonex() -> Bool {
var isIphonex = false
if UIDevice.current.userInterfaceIdiom != .phone {
return isIphonex
}
if #available(iOS 11.0, *) {
/// 利用safeAreaInsets.bottom > 0.0来判断是否是iPhone X。
let mainWindow = UIApplication.shared.keyWindow
if mainWindow?.safeAreaInsets.bottom ?? CGFloat(0.0) > CGFloat(0.0) {
isIphonex = true
}
}
return isIphonex
}
}
class TopViewController {
var getTopViewController: UIViewController? {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
return getTopViewController(viewController: rootViewController)
}
func getTopViewController(viewController: UIViewController?) -> UIViewController? {
if let presentedViewController = viewController?.presentedViewController {
return getTopViewController(viewController: presentedViewController)
}
if let tabBarController = viewController as? UITabBarController,
let selectViewController = tabBarController.selectedViewController {
return getTopViewController(viewController: selectViewController)
}
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return getTopViewController(viewController: visibleViewController)
}
if let pageViewController = viewController as? UIPageViewController,
pageViewController.viewControllers?.count == 1 {
return getTopViewController(viewController: pageViewController.viewControllers?.first)
}
for subView in viewController?.view.subviews ?? [] {
if let childViewController = subView.next as? UIViewController {
return getTopViewController(viewController: childViewController)
}
}
return viewController
}
}
extension Notification.Name {
static var DDPhotoFullScreenNotification = NSNotification.Name(rawValue: "DDPhotoFullScreenNotification")
}
<file_sep>//
// DDVideoPlayerError.swift
// mpdemo
//
// Created by leo on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import Foundation
import AVFoundation
public struct DDVideoPlayerError: CustomStringConvertible {
var error : Error?
var playerItemErrorLogEvent : [AVPlayerItemErrorLogEvent]?
var extendedLogData : Data?
var extendedLogDataStringEncoding : UInt?
public var description: String {
return "DDVideoPlayer Log -------------------------- \n error: \(String(describing: error))\n playerItemErrorLogEvent: \(String(describing: playerItemErrorLogEvent))\n extendedLogData: \(String(describing: extendedLogData))\n extendedLogDataStringEncoding \(String(describing: extendedLogDataStringEncoding))\n --------------------------"
}
}
<file_sep>//
// NotificationVC.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class NotificationVC: UIViewController {
@IBOutlet weak var btn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//接受通知 。无需再deinit中释放
addNotifiObserver(name: "a") { (notifi) in
print("NotificationVC接收到: \(notifi.userInfo.debugDescription)")
}
btn.addActionTouchUpInside {[weak self](sender) in
self?.postNotification(name: "a", object: nil, userInfo: ["name": "lisi"])
self?.postNotification(name: "b", object: nil, userInfo: ["name": "wangwu"])
}
}
deinit {
print(self)
}
}
<file_sep>//
// DDVideoPlayerViewDelegate.swift
// mpdemo
//
// Created by USER on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import UIKit
public protocol DDPlayerViewDelegate: class {
func ddPlayerView(_ playerView: DDVideoPlayerView, willFullscreen isFullscreen: Bool, orientation: UIInterfaceOrientation)
func ddPlayerView(didTappedClose playerView: DDVideoPlayerView)
func ddPlayerView(didDisplayControl playerView: DDVideoPlayerView)
}
// MARK: - delegate methods optional
public extension DDPlayerViewDelegate {
func ddPlayerView(_ playerView: DDVideoPlayerView, willFullscreen isFullscreen: Bool, orientation: UIInterfaceOrientation) {}
func ddPlayerView(didTappedClose playerView: DDVideoPlayerView) {}
func ddPlayerView(didDisplayControl playerView: DDVideoPlayerView) {}
func ddPlayerView(deviceOrientationDidChange playerView: DDVideoPlayerView, orientation: UIInterfaceOrientation) {}
}
public enum DDPlayerViewPanGestureDirection: Int {
case vertical
case horizontal
}
<file_sep>
//
// DDCustomCameraController.swift
// DDCustomCamera
//
// Created by USER on 2018/11/15.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
import CoreMotion
let kViewWidth: CGFloat = UIScreen.main.bounds.size.width
let kViewHeight: CGFloat = UIScreen.main.bounds.size.height
let DDSafeAreaBottom: CGFloat = DDCustomCameraIsiPhoneX.isIphonex() ? 34 : 0
class DDCustomCameraIsiPhoneX {
static public func isIphonex() -> Bool {
var isIphonex = false
if UIDevice.current.userInterfaceIdiom != .phone {
return isIphonex
}
if #available(iOS 11.0, *) {
/// 利用safeAreaInsets.bottom > 0.0来判断是否是iPhone X。
let mainWindow = UIApplication.shared.keyWindow
if mainWindow?.safeAreaInsets.bottom ?? CGFloat(0.0) > CGFloat(0.0) {
isIphonex = true
}
}
return isIphonex
}
}
class DDCustomCameraController: UIViewController {
//是否允许录制视频
public var isEnableRecordVideo: Bool? = true
//是否允许拍照
public var isEnableTakePhoto: Bool? = true
//最大录制时长
public var maxRecordDuration: Int = 15
//长按拍摄动画进度条颜色
public var circleProgressColor: UIColor = UIColor(red: 99.0/255.0, green: 181.0/255.0, blue: 244.0/255.0, alpha: 1)
//选择尺寸
public var sessionPreset:DDCaptureSessionPreset = .preset1280x720
//拍照回调
public var doneBlock: ((UIImage?, URL?)->())?
//从相册选择图片回调
public var selectedAlbumBlock: (([DDPhotoGridCellModel]?)->())?
//是否获取限制区域中的图片
public var isShowClipperView: Bool?
//限制区域的大小
public var clipperSize: CGSize?
//当前对象是否是从DDPhotoPicke present呈现,外界调用请勿修改此参数
public var isFromDDPhotoPickerPresent: Bool = false
//选择相册类型
public var photoAssetType: DDPhotoPickerAssetType = .all
//会话
private lazy var session: AVCaptureSession = {
let session = AVCaptureSession()
return session
}()
private lazy var motionManager: CMMotionManager? = {
let motionManager = CMMotionManager()
motionManager.deviceMotionUpdateInterval = 0.5
return motionManager
}()
/// 切换前后摄像头
private lazy var toggleCameraBtn: UIButton = {
let toggleCameraBtn = UIButton(type: .custom)
if let path = Bundle(for: DDCustomCameraController.classForCoder()).path(forResource: "DDCustomCamera", ofType: "bundle"),
let bundle = Bundle(path: path),
let toggleImage = UIImage(named: "photographyOverturn", in: bundle, compatibleWith: nil)
{
toggleCameraBtn.setImage(toggleImage, for: .normal)
}
toggleCameraBtn.addTarget(self, action: #selector(btnToggleCameraAction), for: .touchUpInside)
return toggleCameraBtn
}()
/// 切换前后摄像头
private lazy var flashlightBtn: UIButton = {
let flashlightBtn = UIButton(type: .custom)
if let path = Bundle(for: DDCustomCameraController.classForCoder()).path(forResource: "DDCustomCamera", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "photographyFlash", in: bundle, compatibleWith: nil)
{
flashlightBtn.setImage(image, for: .normal)
}
flashlightBtn.addTarget(self, action: #selector(flashlightBtnAction), for: .touchUpInside)
return flashlightBtn
}()
//关闭按钮
private lazy var closeBtn: UIButton = {
let closeBtn = UIButton(type: .custom)
if let path = Bundle(for: DDCustomCameraController.classForCoder()).path(forResource: "DDCustomCamera", ofType: "bundle"),
let bundle = Bundle(path: path),
let toggleImage = UIImage(named: "arrow", in: bundle, compatibleWith: nil)
{
closeBtn.setImage(toggleImage, for: .normal)
}
closeBtn.addTarget(self, action: #selector(colseBtnAction), for: .touchUpInside)
return closeBtn
}()
private lazy var toolView: DDCustomCameraToolView = DDCustomCameraToolView()
private var layoutOK: Bool = false
//预览图层,显示相机拍摄到的画面
private var previewLayer: AVCaptureVideoPreviewLayer?
//AVCaptureDeviceInput对象是输入流
private var videoInput: AVCaptureDeviceInput?
//照片输出流对象
private var imageOutPut: AVCaptureStillImageOutput?
//视频输出流
private var movieFileOutPut: AVCaptureMovieFileOutput?
//视屏方向
private var orientation: AVCaptureVideoOrientation?
//拍照照片显示
private lazy var takedImageView: UIImageView = {
let takedImageView = UIImageView()
takedImageView.backgroundColor = UIColor.black
takedImageView.isHidden = true
takedImageView.contentMode = .scaleAspectFit
return takedImageView
}()
//拍照的照片
private var takedImage: UIImage?
//录制视频保存的url
private var videoUrl: URL?
//视屏播放界面
private var playerView: DDCustomCameraPlayer?
//是否开启闪光灯
private var isFlashOn: Bool = false
//保存device
private var captureDevice: AVCaptureDevice?
//相册管理
private var pickermanager: DDPhotoPickerManager?
//拍照限制区域框
private lazy var clipperView: DDClipperView = {
let clipperView = DDClipperView(frame: view.bounds)
clipperView.clipperSize = clipperSize
return clipperView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupCamera()
observeDeviceMotion()
addNotification()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
motionManager?.stopDeviceMotionUpdates()
motionManager = nil
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
session.startRunning()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
session.stopRunning()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if layoutOK == true {
return
}
layoutOK = true
toolView.frame = CGRect(x: 0, y: kViewHeight-130-DDSafeAreaBottom, width: kViewWidth, height: 100)
previewLayer?.frame = view.layer.bounds
toggleCameraBtn.frame = CGRect(x: kViewWidth-18-30, y: 52, width: 30, height: 30)
flashlightBtn.frame = CGRect(x: kViewWidth-18-30-30-20, y: 52, width: 30, height: 30)
closeBtn.frame = CGRect(x: 18, y: 52, width: 30, height: 30)
takedImageView.frame = view.bounds
}
//只允许竖屏
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
deinit {
if session.isRunning == true {
session.stopRunning()
}
try? AVAudioSession.sharedInstance().setActive(false, with: .notifyOthersOnDeactivation)
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Action
extension DDCustomCameraController {
@objc func flashlightBtnAction() {
guard let device = captureDevice else {
return
}
try? device.lockForConfiguration()
if isFlashOn == true {
if device.isFlashModeSupported(.off) == true {
device.flashMode = .off
isFlashOn = false
}
} else {
if device.isFlashModeSupported(.on) == true {
device.flashMode = .on
isFlashOn = true
}
}
device.unlockForConfiguration()
}
@objc func btnToggleCameraAction() {
if takedImageView.isHidden == false {
return
}
let cameraCount = AVCaptureDevice.devices(for: .video).count
if cameraCount <= 1 {
return
}
var newVideoInput: AVCaptureDeviceInput?
let position = videoInput?.device.position
if position == .back {
if let device = frontCamera() {
newVideoInput = try? AVCaptureDeviceInput(device: device)
}
} else if position == .front {
if let device = backCamera() {
newVideoInput = try? AVCaptureDeviceInput(device: device)
}
} else {
return
}
if let newVideoInput = newVideoInput {
guard let videoInput = videoInput else {
return
}
session.beginConfiguration()
session.removeInput(videoInput)
if session.canAddInput(newVideoInput) == true {
session.addInput(newVideoInput)
self.videoInput = newVideoInput
} else {
session.addInput(videoInput)
}
session.commitConfiguration()
}
}
@objc func colseBtnAction() {
dismiss(animated: true, completion: nil)
}
}
// MARK: - DDCustomCameraToolViewDelegate
extension DDCustomCameraController: DDCustomCameraToolViewDelegate {
//点击相册
func onPhotoAlbum() {
if isFromDDPhotoPickerPresent == true {
doneBlock?(takedImage, videoUrl)
dismiss(animated: true, completion: nil)
return
}
pickermanager = DDPhotoPickerManager()
pickermanager?.isFromDDCustomCameraPresent = true
pickermanager?.presentImagePickerController {[weak self] (arr) in
self?.selectedAlbumBlock?(arr)
DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
self?.dismiss(animated: true, completion: nil)
})
}
}
func onTakePicture() {
let videoConnection = imageOutPut?.connection(with: .video)
videoConnection?.videoOrientation = orientation ?? .portrait
guard let connection = videoConnection else {
return
}
imageOutPut?.captureStillImageAsynchronously(from: connection, completionHandler: {[weak self] (imageDataSampleBuffer, err) in
guard let buffer = imageDataSampleBuffer,
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) else {
return
}
let image = UIImage(data: data)
if self?.isShowClipperView == true {
self?.takedImage = self?.clipImg(image: image)
} else {
self?.takedImage = image
}
self?.takedImageView.isHidden = false
self?.takedImageView.image = self?.takedImage
self?.session.stopRunning()
})
}
func onStartRecord() {
let movieConnection = movieFileOutPut?.connection(with: .video)
movieConnection?.videoOrientation = orientation ?? .portrait
movieConnection?.videoScaleAndCropFactor = 1.0
/// ios10后,设置输出视屏h格式
if let connection = movieConnection {
if #available(iOS 10.0, *) {
var dic = [String: String]()
dic[AVVideoCodecKey] = AVVideoCodecH264
movieFileOutPut?.setOutputSettings(dic, for: connection)
}
}
if movieFileOutPut?.isRecording == false {
let path = DDCustomCameraManager.getVideoExportFilePath(.mp4)
let url = URL(fileURLWithPath: path)
movieFileOutPut?.startRecording(to: url, recordingDelegate: self)
}
}
func onFinishRecord() {
movieFileOutPut?.stopRecording()
session.stopRunning()
setVideoZoomFactor(1.0)
}
func onRetake() {
session.startRunning()
takedImageView.isHidden = true
deleteVideo()
}
func onOkClick() {
playerView?.reset()
if let block = doneBlock {
block(takedImage, videoUrl)
}
if isFromDDPhotoPickerPresent == true {
var vc: UIViewController? = self
while(vc?.presentingViewController != nil) {
vc = vc?.presentingViewController
}
vc?.dismiss(animated: true, completion: nil)
return
}
dismiss(animated: true, completion: nil)
}
}
// MARK: - AVCaptureFileOutputRecordingDelegate
extension DDCustomCameraController: AVCaptureFileOutputRecordingDelegate {
func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
toolView.startAnimate()
}
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
if CMTimeGetSeconds(output.recordedDuration) < 1 {
if isEnableTakePhoto == true {
//视频长度小于1s 允许拍照则拍照,不允许拍照,则保存小于1s的视频x
lastFrame(videoUrl: outputFileURL, size: CGSize(width: 720, height: 1280), duration: output.recordedDuration) {[weak self] (image) in
self?.takedImage = image
self?.takedImageView.isHidden = false
self?.takedImageView.image = image
}
return
}
}
videoUrl = outputFileURL
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.playVideo()
}
}
}
private extension DDCustomCameraController {
//截图限制区域的图片
func clipImg(image: UIImage?) -> UIImage? {
guard let image = image else {
return nil
}
let scale: CGFloat = 3.0
let scaleImage = scaleToSize(image: image, size: view.frame.size, scale: scale)
let rect = view.convert(clipperView.clipperImgView?.frame ?? CGRect.zero, to: view)
let rect2 = CGRect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale)
let resultImage = imageFromImage(imageFromImage: scaleImage, inRext: rect2)
return resultImage
}
func scaleToSize(image: UIImage?, size: CGSize, scale: CGFloat) -> UIImage? {
guard let image = image else {
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, scale); //此处将画布放大两倍,这样在retina屏截取时不会影响像素
//
// // 得到图片上下文,指定绘制范围
// UIGraphicsBeginImageContext(size);
// 将图片按照指定大小绘制
image.draw(in: CGRect(x:0,y:0,width:size.width,height:size.height))
// 从当前图片上下文中导出图片
let img = UIGraphicsGetImageFromCurrentImageContext()
// 当前图片上下文出栈
UIGraphicsEndImageContext();
// 返回新的改变大小后的图片
return img
}
//2.实现这个方法,,就拿到了截取后的照片.
func imageFromImage(imageFromImage:UIImage?, inRext:CGRect) -> UIImage? {
guard let imageFromImage = imageFromImage else {
return nil
}
//将UIImage转换成CGImageRef
//按照给定的矩形区域进行剪裁
guard let sourceImageRef:CGImage = imageFromImage.cgImage,
let newImageRef:CGImage = sourceImageRef.cropping(to: inRext) else {
return nil
}
//将CGImageRef转换成UIImage
let img:UIImage = UIImage.init(cgImage: newImageRef)
//返回剪裁后的图片
return img
}
/// 获取视屏的最后一帧
///
/// - Parameters:
/// - url: url
/// - size: 图片的size
/// - duration: 视屏时长
/// - completion: 完成回调
func lastFrame(videoUrl url: URL?, size: CGSize, duration: CMTime, completion:@escaping (UIImage?)->()) {
guard let url = url else {
completion(nil)
return
}
DispatchQueue.global().async {
let opts = [AVURLAssetPreferPreciseDurationAndTimingKey: false]
let urlAsset = AVURLAsset(url: url, options: opts)
let genarator = AVAssetImageGenerator(asset: urlAsset)
genarator.appliesPreferredTrackTransform = true
genarator.requestedTimeToleranceAfter = kCMTimeZero
genarator.requestedTimeToleranceBefore = kCMTimeZero
let secondes = duration.seconds
//1 代码最后一帧
let time = CMTimeMakeWithSeconds(secondes, 1)
genarator.maximumSize = CGSize(width: size.width, height: size.height)
let img = try? genarator.copyCGImage(at: time, actualTime: nil)
DispatchQueue.main.async(execute: {
if let image = img {
completion(UIImage(cgImage: image))
} else {
completion(nil)
}
})
}
}
func playVideo() {
if playerView == nil {
let playV = DDCustomCameraPlayer(frame: view.bounds)
view.insertSubview(playV, belowSubview: toolView)
playerView = playV
}
playerView?.videoUrl = videoUrl
playerView?.play()
}
func setVideoZoomFactor(_ zoomFactor: CGFloat) {
let captureDevice = videoInput?.device
try? captureDevice?.lockForConfiguration()
captureDevice?.videoZoomFactor = zoomFactor
captureDevice?.unlockForConfiguration()
}
func deleteVideo() {
if videoUrl != nil {
playerView?.reset()
playerView?.alpha = 0
if let url = videoUrl {
try? FileManager.default.removeItem(at: url)
}
//清空videoUrl
videoUrl = nil
}
}
func setupUI() {
view.backgroundColor = UIColor.black
if isShowClipperView == true {
view.addSubview(clipperView)
}
toolView.isEnableTakePhoto = isEnableTakePhoto
toolView.isEnableRecordVideo = isEnableRecordVideo
toolView.circleProgressColor = circleProgressColor
toolView.maxRecordDuration = maxRecordDuration
toolView.delegate = self
toolView.isShowClipperView = isShowClipperView
view.addSubview(toolView)
view.addSubview(toggleCameraBtn)
view.addSubview(closeBtn)
view.addSubview(flashlightBtn)
if isEnableRecordVideo == true {
let pan = UIPanGestureRecognizer(target: self, action: #selector(adjustCameraFocus(_:)))
view.addGestureRecognizer(pan)
}
//添加拍照成功后图片背景,默认为隐藏
takedImageView.frame = view.bounds
view.insertSubview(takedImageView, belowSubview: toolView)
}
func setupCamera() {
guard let device = backCamera() else {
return
}
captureDevice = device
//相机画面输入流
videoInput = try? AVCaptureDeviceInput(device: device)
//照片输出流
imageOutPut = AVCaptureStillImageOutput()
//这是输出流的设置参数AVVideoCodecJPEG参数表示以JPEG的图片格式输出图片
let dicOutputSetting = [AVVideoCodecKey: AVVideoCodecJPEG]
imageOutPut?.outputSettings = dicOutputSetting
//音频输入流
let audioCaptureDevice = AVCaptureDevice.devices(for: .audio).first
var audioInput: AVCaptureDeviceInput? = nil
if isEnableRecordVideo == true {
guard let audioDevice = audioCaptureDevice else {
return
}
audioInput = try? AVCaptureDeviceInput(device: audioDevice)
}
//视频输出流
//设置视频格式
let preset = transformSessionPreset()
if session.canSetSessionPreset(AVCaptureSession.Preset(rawValue: preset)) {
session.sessionPreset = AVCaptureSession.Preset(rawValue: preset)
} else {
session.sessionPreset = AVCaptureSession.Preset.hd1280x720
}
movieFileOutPut = AVCaptureMovieFileOutput()
//必须设置,否则默认超过10s就没声音
movieFileOutPut?.movieFragmentInterval = kCMTimeInvalid
//将视频及音频输入流添加到session
if let videoInput = videoInput {
if session.canAddInput(videoInput) == true {
session.addInput(videoInput)
}
}
//添加音频输入
if let audioInput = audioInput {
if session.canAddInput(audioInput) == true {
session.addInput(audioInput)
}
}
//添加输出流
if let imageOutPut = imageOutPut {
if session.canAddOutput(imageOutPut) == true {
session.addOutput(imageOutPut)
}
}
if let movieFileOutPut = movieFileOutPut {
if session.canAddOutput(movieFileOutPut) == true {
session.addOutput(movieFileOutPut)
}
}
//预览层
previewLayer = AVCaptureVideoPreviewLayer(session: session)
view.layer.masksToBounds = true
//添加预览层到当前view.layer上
previewLayer?.videoGravity = .resizeAspectFill
if let previewLayer = previewLayer {
view.layer.insertSublayer(previewLayer, at: 0)
}
//设置闪光灯属性
//先加锁
try? device.lockForConfiguration()
// //闪光灯自动
// if device.isFlashModeSupported(.auto) == true {
// device.flashMode = .auto
// }
//自动白平衡
if device.isWhiteBalanceModeSupported(.autoWhiteBalance) == true {
device.whiteBalanceMode = .autoWhiteBalance
}
//启动默认是关闭闪光灯
if device.isFlashModeSupported(.off) == true {
device.flashMode = .off
}
//解锁
device.unlockForConfiguration()
}
func observeDeviceMotion() {
// 确定是否使用任何可用的态度参考帧来决定设备的运动是否可用
if motionManager?.isDeviceMotionAvailable == true {
// 启动设备的运动更新,通过给定的队列向给定的处理程序提供数据。
motionManager?.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: {[weak self] (motion, err) in
DispatchQueue.main.async(execute: {
self?.handleDeviceMotion(motion)
})
})
} else {
motionManager = nil
}
}
@objc func handleDeviceMotion(_ deviceMotion: CMDeviceMotion?) {
if isShowClipperView == true {
orientation = .portrait
return
}
let x = deviceMotion?.gravity.x ?? 0.0
let y = deviceMotion?.gravity.y ?? 0.0
if fabs(y) >= fabs(x) {
if y >= 0 {
orientation = .portraitUpsideDown
} else {
orientation = .portrait
}
} else {
if x >= 0 {
orientation = .landscapeLeft
} else {
orientation = .landscapeRight
}
}
}
func transformSessionPreset() -> String {
switch sessionPreset {
case .preset325x288:
return AVCaptureSession.Preset.cif352x288.rawValue
case .preset640x480:
return AVCaptureSession.Preset.vga640x480.rawValue
case .preset960x540:
return AVCaptureSession.Preset.iFrame960x540.rawValue
case .preset1280x720:
return AVCaptureSession.Preset.iFrame1280x720.rawValue
case .preset1920x1080:
return AVCaptureSession.Preset.hd1920x1080.rawValue
case .preset3840x2160:
return AVCaptureSession.Preset.hd4K3840x2160.rawValue
}
}
func backCamera() -> AVCaptureDevice? {
return cameraWithPosition(.back)
}
func frontCamera() -> AVCaptureDevice? {
return cameraWithPosition(.front)
}
func cameraWithPosition(_ position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let devices = AVCaptureDevice.devices(for: .video)
for device in devices {
if device.position == position {
return device
}
}
return nil
}
func addNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
}
func onDismiss() {
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
@objc func willResignActive() {
if session.isRunning == true {
dismiss(animated: true, completion: nil)
}
}
@objc func adjustCameraFocus(_ pan: UIPanGestureRecognizer) {
}
}
<file_sep>
//
// CHLogItem.swift
// CHLog
//
// Created by wanggw on 2018/6/30.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
import UIKit
public class CHLogItem: NSObject {
var logTime: String = "" //日志时间
var logInfo: String = "" //日志内容
var isError: Bool = false //是否是错误信息
var isRequest: Bool = true //是否是网络请求
var isRequestError: Bool = false //是否是请求失败
var requstType: String = "" //请求类型
var requstBaseUrl: String = "" //请求地址
var requstFullUrl: String = "" //请求完整地址
var requstHeader: [String: String] = [:] //请求头
var requstParams: [String: String] = [:] //请求参数
var response: [String: Any] = [:] //请求返回数据
var responses: [CHLogItem] = [] //请求返回数据列表
var rowHeight: CGFloat = 0 //缓存高度
}
extension CHLogItem {
public class func item(with item: DDRequstItemProtocol) -> CHLogItem {
let logItem: CHLogItem = CHLogItem()
logItem.isRequest = true
if let method = item.method,
let url = item.url,
let headers = item.headers,
let parameters = item.parameters {
logItem.requstType = method
logItem.requstFullUrl = url
logItem.requstHeader = headers
logItem.requstParams = parameters
}
if let response = item.response {
logItem.response = response
}
if let isRequestError = item.isError {
logItem.isRequestError = isRequestError
}
return logItem
}
}
extension CHLogItem {
public func cellRowHeigt() -> CGFloat {
if rowHeight != 0 {
return rowHeight
}
let nsInfo = describeString() as NSString
let size = nsInfo.boundingRect(with: CGSize(width: UIScreen.main.bounds.size.width - 30, height: 1000),
options: .usesLineFragmentOrigin,
attributes: [.font: UIFont.systemFont(ofSize: 12)],
context: nil)
rowHeight = size.height + 10
return rowHeight
}
}
extension CHLogItem {
public func describeString() -> String {
if !isRequest {
return logInfo
}
let info = " Type:\(requstType)\n FullUrl:\(requstFullUrl)\n Header:\(requstHeader)\n Params:\(requstParams)\nResponse:\(response)"
return info
}
public func attributedDescribeString() -> NSMutableAttributedString {
if !isRequest {
let color = isError ? UIColor.red : UIColor.white
let attributedString = NSMutableAttributedString(string: logInfo, attributes: [.font: UIFont.systemFont(ofSize: 12.0),
.foregroundColor: color])
return attributedString
}
//-----
let type = " type:"
let attributedString = NSMutableAttributedString(string: type, attributes: [.font: UIFont.boldSystemFont(ofSize: 12.0),
.foregroundColor: UIColor.black])
let typeValue = "\(requstType) \(requstBaseUrl)\n"
attributedString.append(NSMutableAttributedString(string: typeValue, attributes: [.font: UIFont.systemFont(ofSize: 12.0),
.foregroundColor: UIColor.black]))
//-----
let fullUrl = " fullUrl:"
attributedString.append(NSMutableAttributedString(string: fullUrl, attributes: [.font: UIFont.boldSystemFont(ofSize: 12.0),
.foregroundColor: UIColor.blue]))
let fullUrlValue = "\(requstFullUrl)\n"
attributedString.append(NSMutableAttributedString(string: fullUrlValue, attributes: [.font: UIFont.systemFont(ofSize: 12.0),
.foregroundColor: UIColor.blue]))
//-----
let header = " header:"
attributedString.append(NSMutableAttributedString(string: header, attributes: [.font: UIFont.boldSystemFont(ofSize: 12.0),
.foregroundColor: UIColor.black]))
let headerValue = "\(requstHeader)\n"
attributedString.append(NSMutableAttributedString(string: headerValue, attributes: [.font: UIFont.systemFont(ofSize: 12.0),
.foregroundColor: UIColor.black]))
//-----
let params = "params:"
attributedString.append(NSMutableAttributedString(string: params, attributes: [.font: UIFont.boldSystemFont(ofSize: 12.0),
.foregroundColor: UIColor.black]))
let paramsValue = "\(requstParams)\n"
attributedString.append(NSMutableAttributedString(string: paramsValue, attributes: [.font: UIFont.systemFont(ofSize: 12.0),
.foregroundColor: UIColor.black]))
//-----
return attributedString
}
}
<file_sep>
//
// DDScrollView.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/11/22.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class DDScrollView: UIScrollView {
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.panGestureRecognizer {
if gestureRecognizer.state == .possible {
if isScrollViewOnTopOrBottom() == true {
return false
}
}
}
return true
}
func isScrollViewOnTopOrBottom() -> Bool {
let translation = panGestureRecognizer.translation(in: self)
if translation.y > 0 && contentOffset.y <= 0 {
return true
}
let distance = contentSize.height - bounds.size.height
let maxOffsetY = floor(distance)
if translation.y < 0 && contentOffset.y >= maxOffsetY {
return true
}
return false
}
}
<file_sep>//
// Refresh.swift
// Refresh
//
// Created by senyuhao on 2018/7/2.
// Copyright © 2018年 dd01. All rights reserved.
//
import Foundation
import MJRefresh
import MobileCoreServices
extension MJRefreshGifHeader {
/// gif动态header
///
/// - Parameters:
/// - name: gif的名字,eg : mj.gif, 则name表示为mj即可
/// - handler: 回调
public class func inits(gifName: String, handler: @escaping() -> Void) -> MJRefreshGifHeader? {
let header = MJRefreshGifHeader {
handler()
}
GifTool.loadingGif(name: gifName) { images, duration in
header?.setImages(images, duration: duration, for: .idle)
header?.setImages(images, duration: duration, for: .pulling)
header?.setImages(images, duration: duration, for: .refreshing)
header?.setImages(images, duration: duration, for: .willRefresh)
}
header?.lastUpdatedTimeLabel.isHidden = true
header?.stateLabel.isHidden = true
header?.ignoredScrollViewContentInsetTop = 0
return header
}
}
extension MJRefreshBackGifFooter {
/// gif动态footer
///
/// - Parameters:
/// - name: 表示gif的名称, eg : mj.gif, 则name表示为mj即可
/// - handler: 回调操作
public class func inits(gifName: String, handler: @escaping() -> Void) -> MJRefreshBackGifFooter? {
let footer = RefreshBackGifFooter {
handler()
}
GifTool.loadingGif(name: gifName) { images, duration in
footer?.setImages(images, duration: duration, for: .pulling)
footer?.setImages(images, duration: duration, for: .refreshing)
footer?.setImages(images, duration: duration, for: .willRefresh)
}
footer?.setTitle(NSLocalizedString("暫無更多數據", comment: ""), for: .noMoreData)
footer?.ignoredScrollViewContentInsetBottom = 0
return footer
}
}
class RefreshBackGifFooter: MJRefreshBackGifFooter {
override func layoutSubviews() {
super.layoutSubviews()
if state == .noMoreData {
stateLabel.isHidden = false
} else {
stateLabel.isHidden = true
}
}
}
class GifTool: NSObject {
public class func loadingGif(name: String, handler: @escaping(_ images: [UIImage]?, _ duration: Double) -> Void) {
if let path = Bundle.main.path(forResource: name, ofType: "gif") {
let data = NSData(contentsOfFile: path)
let imagesources = imageSourceFromData(data: data)
let images = imagesFromImageSource(sources: imagesources)
if let images = images, let imageinfo = images.images {
handler(imageinfo, images.duration)
} else {
handler(nil, 0.0)
}
}
}
private class func imageSourceFromData(data: NSData?) -> CGImageSource? {
if let data = data {
let options = [kCGImageSourceShouldCache: true, kCGImageSourceTypeIdentifierHint: kUTTypeGIF] as [CFString: Any]
return CGImageSourceCreateWithData(data, options as CFDictionary)
}
return nil
}
private class func imagesFromImageSource(sources: CGImageSource?) -> (images: [UIImage]?, duration: Double)? {
if let sources = sources {
let count = CGImageSourceGetCount(sources)
var images = [UIImage]()
var gifDuration = 0.0
let options = [kCGImageSourceShouldCache: true, kCGImageSourceTypeIdentifierHint: kUTTypeGIF] as [CFString: Any]
for i in 0 ..< count {
guard let imageRef = CGImageSourceCreateImageAtIndex(sources, i, options as CFDictionary) else {
return (images, gifDuration)
}
if count == 1 {
gifDuration = Double.infinity
} else {
guard let properties = CGImageSourceCopyPropertiesAtIndex(sources, i, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
let frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else {
return (images, gifDuration)
}
gifDuration += frameDuration.doubleValue
// 鉴于提供的MJ多为3x图片设计,故这里直接使用3.0,未使用UIScreen.main.scale
let image = UIImage(cgImage: imageRef, scale: 3.0, orientation: .up)
images.append(image)
}
}
return (images, gifDuration)
}
return nil
}
}
<file_sep># Toast && Hud使用指南
[更多使用demo地址](https://github.com/weiweilidd01/ToastAndHudDemo.git)
#### 1.集成:DDKit
#### 2.Toast基本使用
```
view.showToast(msg: "1231231231")
```
#### 3.Hud基本使用
```
view.showHud(title: "加载中...")
```
#### 4.Toast功能展示
<img src="https://upload-images.jianshu.io/upload_images/2026287-720858cd2537a075.gif?imageMogr2/auto-orient/strip" width=200 height=400 />
#### 5.Hud功能展示
<img src="https://upload-images.jianshu.io/upload_images/2026287-b85cff7591390f36.gif?imageMogr2/auto-orient/strip" width=200 height=400 />
<file_sep># MagicTextField
[demo下载地址](https://github.com/weiweilidd01/MagicTextField)
#### 1.效果图
<img src="https://upload-images.jianshu.io/upload_images/2026287-a251d2d86e85276e.gif?imageMogr2/auto-orient/strip" width=300 height=500 />
#### 2.代码使用
```
accountInput.placeholder = "請輸入手機號碼"
accountInput.animatedText = "手机号码"
accountInput.font = UIFont.systemFont(ofSize: 14)
accountInput.animatedFont = UIFont.systemFont(ofSize: 12)
accountInput.textAlignment = .left
accountInput.marginLeft = 10
accountInput.placeholderColor = UIColor.red
accountInput.animatedPlaceholderColor = UIColor.blue
accountInput.moveDistance = 30
accountInput.borderStyle = .line
accountInput.frame = CGRect(x: 100, y: 100, width: 200, height: 30)
view.addSubview(accountInput)
```
##### 4.能设置的参数
```
//placeholder移动后的字体大小
public var animatedFont: UIFont? = UIFont.systemFont(ofSize: 12)
//placeholder移动后的文字显示
public var animatedText: String?
//placeholder向上移动的距离,负数向下
public var moveDistance: CGFloat = 0.0
//UITextFieldDidChange事件回调
public var magicFieldDidChangeCallBack: (()->())?
//placeholder的颜色,默认为灰色
public var placeholderColor: UIColor?
//placeholder移动后的颜色,默认为placeholderColor,设置此属性一定要在设置 placeholderColor的后面
public var animatedPlaceholderColor: UIColor?
//离输入框左边的边距,默认为0
public var marginLeft: CGFloat = 0
//重写父类placeholder
override public var placeholder: String?
//重写父类textAlignment
override public var textAlignment: NSTextAlignment
//重写父类font
override public var font: UIFont?
```
<file_sep>//
// DDScanPermissions.swift
// DDScanDemo
//
// Created by USER on 2018/11/27.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import Photos
import AssetsLibrary
import AVFoundation
public class DDScanPermissions: NSObject {
// MARK: - ---获取相册权限
static func authorizePhoto(_ comletion:@escaping (Bool) -> Void) {
let granted = PHPhotoLibrary.authorizationStatus()
switch granted {
case PHAuthorizationStatus.authorized:
comletion(true)
case PHAuthorizationStatus.denied, PHAuthorizationStatus.restricted:
comletion(false)
self.showAlertNoAuthority(NSLocalizedString("请在iPhone的\"设置-隐私-照片\"选项中,允许访问您的照片", comment: ""))
case PHAuthorizationStatus.notDetermined:
PHPhotoLibrary.requestAuthorization({ (status) in
DispatchQueue.main.async {
comletion(status == .authorized ? true:false)
}
})
}
}
// MARK: - --相机权限
public static func authorizeCamera(_ comletion: @escaping (Bool) -> Void ) {
let granted = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch granted {
case AVAuthorizationStatus.authorized:
comletion(true)
case AVAuthorizationStatus.denied:
comletion(false)
self.showAlertNoAuthority(NSLocalizedString("请在iPhone的\"设置-隐私-相机\"选项中,允许访问您的相机", comment: ""))
case AVAuthorizationStatus.restricted:
comletion(false)
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) in
DispatchQueue.main.async {
if granted {
comletion(granted)
}
}
})
}
}
/// 显示无授权信息
///
/// - Parameter text: 标题
static func showAlertNoAuthority(_ text: String?) {
//弹窗提示
let alertVC = UIAlertController(title: "提示", message: text, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .default) { (action) in
}
let actionCommit = UIAlertAction(title: "去设置", style: .default) { (action) in
//去设置
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
alertVC.addAction(cancelAction)
alertVC.addAction(actionCommit)
if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
rootVC.present(alertVC, animated: true, completion: nil)
}
}
}
<file_sep>//
// UIColor+HEX.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/18.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
/// UIColor.colorWithHex(0x000000)
///
/// - Parameters:
/// - hex: 16进制
/// - alpha: 透明度
/// - Returns: color
static public func colorWithHex(_ hex: UInt32, alpha: CGFloat = 1) -> UIColor {
return UIColor(red: CGFloat(((hex >> 16) & 0xFF))/255.0, green: CGFloat(((hex >> 8) & 0xFF))/255.0, blue: CGFloat((hex & 0xFF))/255.0, alpha: alpha)
}
}
<file_sep>//
// DDMediator.swift
// MediatorDemo
//
// Created by weiwei.li on 2019/3/19.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
//定义类型
public typealias MediatorParamDic = [String: Any]
public class Mediator {
}
public extension Mediator {
public func dispath(_ action: Action) -> Any? {
if action.cls.isEmpty {
assert(false, "Action----class名不能为空")
}
if action.method.isEmpty {
assert(false, "Action----method名不能为空")
}
return className(action.cls, method: action.method, parameters: action.parameters?.chainDic)
}
}
private extension Mediator {
func className(_ clsName: String, method mtd: String, parameters pa: MediatorParamDic?) -> Any? {
/// 获取targetClass字符串
let swiftModuleName = pa?[kMediatorTargetModuleName] as? String
var targetClassString: String?
if swiftModuleName?.isEmpty == false {
targetClassString = (swiftModuleName ?? "") + "." + clsName
} else {
let namespace = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
targetClassString = (namespace ?? "") + "." + clsName
}
guard let classString = targetClassString else {
assert(false, "获取targetClassString失败")
return nil
}
//获取Target对象
let targetClass = NSClassFromString(classString) as! NSObject.Type
let target = targetClass.init()
//获取methodName
let methodName = mtd + ":"
//获取Selector
let sel = Selector(methodName)
//带参数判断
if target.responds(to: sel) == true {
let unmanaged = target.perform(sel, with: pa ?? MediatorParamDic())
let res = unmanaged?.takeRetainedValue()
unmanaged?.release()
return res
}
//不带参数判断
if target.responds(to: Selector(mtd)) == true {
let unmanaged = target.perform(Selector(mtd))
let res = unmanaged?.takeRetainedValue()
unmanaged?.release()
return res
}
return nil
}
}
<file_sep>//
// Sub2ViewController.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/19.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import MJRefresh
class Sub2ViewController: PageTabsContainerController {
override func viewDidLoad() {
super.viewDidLoad()
setConfig()
title = "水电费你就是你发的健康"
//此demo情景,请不要设置下面属性。否则高度会出错
// if #available(iOS 11.0, *) {
// pageContainerView.tableView.contentInsetAdjustmentBehavior = .never
// } else {
// automaticallyAdjustsScrollViewInsets = false
// }
}
/// 配置父类信息
func setConfig() {
/// 配置segmentViewItems
segmentViewItems = ["列表1", "列表2", "网页"]
/// 配置segmentView
segmentView.itemWidth = UIScreen.main.bounds.width / CGFloat((segmentViewItems?.count) ?? 1)
segmentView.bottomLineWidth = 20
segmentView.bottomLineHeight = 2
/// 配置viewControllerList
var list = [PageTabsBaseController]()
let v1 = TestAController()
list.append(v1)
let v2 = TestBController()
list.append(v2)
let v3 = TestCController()
list.append(v3)
viewControllerList = list
tabsType = .segmented
/// 初始化默认选择tab
segmentView.scrollToIndex(0)
}
}
<file_sep>
//
// UIScrollView+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UIScrollView {
@discardableResult
func contentOffset(_ offset: CGPoint) -> Self {
contentOffset = offset
return self
}
@discardableResult
func contentSize(_ size: CGSize) -> Self {
contentSize = size
return self
}
@discardableResult
func contentInset(_ inset: UIEdgeInsets) -> Self {
contentInset = inset
return self
}
@discardableResult
@available(iOS 11.0, *)
func contentInsetAdjustmentBehavior(_ behavior: UIScrollView.ContentInsetAdjustmentBehavior) -> Self {
contentInsetAdjustmentBehavior = behavior
return self
}
@discardableResult
func isDirectionalLockEnabled(_ enabled: Bool) -> Self {
isDirectionalLockEnabled = enabled
return self
}
@discardableResult
func bounces(_ bool: Bool) -> Self {
bounces = bool
return self
}
@discardableResult
func alwaysBounceVertical(_ bool: Bool) -> Self {
alwaysBounceVertical = bool
return self
}
@discardableResult
func alwaysBounceHorizontal(_ bool: Bool) -> Self {
alwaysBounceHorizontal = bool
return self
}
@discardableResult
func isPagingEnabled(_ enabled: Bool) -> Self {
isPagingEnabled = enabled
return self
}
@discardableResult
func isScrollEnabled(_ enabled: Bool) -> Self {
isScrollEnabled = enabled
return self
}
@discardableResult
func showsHorizontalScrollIndicator(_ bool: Bool) -> Self {
showsVerticalScrollIndicator = bool
return self
}
@discardableResult
func showsVerticalScrollIndicator(_ bool: Bool) -> Self {
showsVerticalScrollIndicator = bool
return self
}
@discardableResult
func scrollIndicatorInsets(_ insets: UIEdgeInsets) -> Self {
scrollIndicatorInsets = insets
return self
}
@discardableResult
func indicatorStyle(_ style: UIScrollView.IndicatorStyle) -> Self {
indicatorStyle = style
return self
}
// 此属性ci跑不过,暂时关闭。此属性基本不使用
// @discardableResult
// func decelerationRate(_ rate: UIScrollViewDecelerationRate) -> Self {
// decelerationRate = rate
// return self
// }
@discardableResult
func indexDisplayMode(_ mode: UIScrollView.IndexDisplayMode) -> Self {
indexDisplayMode = mode
return self
}
@discardableResult
func delaysContentTouches(_ bool: Bool) -> Self {
delaysContentTouches = bool
return self
}
@discardableResult
func canCancelContentTouches(_ bool: Bool) -> Self {
canCancelContentTouches = bool
return self
}
@discardableResult
func minimumZoomScale(_ scale: CGFloat) -> Self {
minimumZoomScale = scale
return self
}
@discardableResult
func maximumZoomScale(_ scale: CGFloat) -> Self {
maximumZoomScale = scale
return self
}
@discardableResult
func zoomScale(_ scale: CGFloat) -> Self {
zoomScale = scale
return self
}
@discardableResult
func bouncesZoom(_ bool: Bool) -> Self {
bouncesZoom = bool
return self
}
@discardableResult
func scrollsToTop(_ bool: Bool) -> Self {
scrollsToTop = bool
return self
}
@discardableResult
func keyboardDismissMode(_ mode: UIScrollView.KeyboardDismissMode) -> Self {
keyboardDismissMode = mode
return self
}
@discardableResult
@available(iOS 10.0, *)
func refreshControl(_ control: UIRefreshControl?) -> Self {
refreshControl = control
return self
}
}
// MARK: - UIScrollViewDelegate
public extension UIKitChainable where Self: UIScrollView {
@discardableResult
public func addScrollViewDidScrollBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewDidScrollBlock(handler)
return self
}
@discardableResult
public func addScrollViewDidZoomBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewDidZoomBlock(handler)
return self
}
@discardableResult
public func addScrollViewWillBeginDraggingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewWillBeginDraggingBlock(handler)
return self
}
@discardableResult
public func addScrollViewWillEndDraggingWithVelocityTargetContentOffsetBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ velocity: CGPoint, _ targetContentOffset: UnsafeMutablePointer<CGPoint>)->())) -> Self {
setScrollViewWillEndDraggingWithVelocityTargetContentOffsetBlock(handler)
return self
}
@discardableResult
public func addScrollViewDidEndDraggingWillDecelerateBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ decelerate: Bool)->())) -> UIScrollView {
setScrollViewDidEndDraggingWillDecelerateBlock(handler)
return self
}
@discardableResult
public func addScrollViewWillBeginDeceleratingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewWillBeginDeceleratingBlock(handler)
return self
}
@discardableResult
public func addScrollViewDidEndDeceleratingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewDidEndDeceleratingBlock(handler)
return self
}
@discardableResult
public func addScrollViewDidEndScrollingAnimationBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewDidEndScrollingAnimationBlock(handler)
return self
}
@discardableResult
public func addViewForZoomingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->(UIView?))) -> Self {
setViewForZoomingBlock(handler)
return self
}
@discardableResult
public func addScrollViewWillBeginZoomingBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ view: UIView?)->())) -> Self {
setScrollViewWillBeginZoomingBlock(handler)
return self
}
@discardableResult
public func addScrollViewDidEndZoomingBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ view: UIView?, _ scale: CGFloat)->())) -> Self {
setScrollViewDidEndZoomingBlock(handler)
return self
}
@discardableResult
public func addScrollViewShouldScrollToTopBlock(_ handler: @escaping((_ scrollView: UIScrollView)->(Bool))) -> Self {
setScrollViewShouldScrollToTopBlock(handler)
return self
}
@discardableResult
public func addScrollViewDidScrollToTopBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewDidScrollToTopBlock(handler)
return self
}
@discardableResult
@available(iOS 11.0, *)
public func addScrollViewDidChangeAdjustedContentInsetBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) -> Self {
setScrollViewDidChangeAdjustedContentInsetBlock(handler)
return self
}
}
<file_sep>//
// TestViewController.swift
// TestSDK
//
// Created by USER on 2018/12/5.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
public class TestViewController: UIViewController {
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
}
}
<file_sep>//
// UICell+Extension.swift
// SBase
//
// Created by weiwei.li on 2018/6/21.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
extension UITableViewCell {
public static func registerNib(mTable: UITableView) {
mTable.register(UINib(nibName: String(describing: self), bundle: nil), forCellReuseIdentifier: NSStringFromClass(self))
}
public static func register(mTable: UITableView) {
mTable.register(self, forCellReuseIdentifier: String(describing: self))
}
}
extension UICollectionViewCell {
public static func registerNib(mCollectin: UICollectionView) {
mCollectin.register(UINib(nibName: String(describing: self), bundle: nil), forCellWithReuseIdentifier: NSStringFromClass(self))
}
public static func register(mCollectin: UICollectionView) {
mCollectin.register(self, forCellWithReuseIdentifier: NSStringFromClass(self))
}
}
public protocol ViewNib {}
extension UIView: ViewNib {}
extension UIViewController: ViewNib{}
extension ViewNib where Self: UIView {
public static func loadNib() -> Self? {
return Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)?.first as? Self
}
}
extension ViewNib where Self: UIViewController {
public static func storyboard(name: String) -> UIViewController? {
return UIStoryboard(name: name, bundle: nil).instantiateViewController(withIdentifier: String(describing: self)) as? Self
}
}
<file_sep>//
// HudVC.swift
// Example
//
// Created by senyuhao on 2018/7/18.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import MBProgressHUD
import MJRefresh
import UIKit
class HudVC: UITableViewController {
var items = ["1、hud-show",
"2、hud-title-show",
"3、hud-title-mode",
"4、hud-annularDeterminate",
"5、hud-circle-determinate",
"6、hud-determinateHorizontalBar",
"7、hud-hidden",
"8、hud-bgcolor",
"9、hud-clear",
"10、ProgressHUD Usage:just loading",
"11、ProgressHUD Usage:loading with note",
"12、ProgressHUD Usage:just show alert note",]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
tableView.mj_header = MJRefreshGifHeader.inits(gifName: "mj", handler: {
self.load(add: false)
})
tableView.mj_footer = MJRefreshBackGifFooter.inits(gifName: "mj", handler: {
self.load(add: true)
})
}
public func load(add: Bool) {
MBProgressHUD.show(base: self.view, backgroundColor: .clear, style: .solidColor)
if add {
items.append(contentsOf: ["1", "2", "3", "4", "5", "6", "7", "8", "10"])
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) { [weak self] in
self?.tableView.reloadData()
MBProgressHUD.hidden(base: self?.view)
self?.tableView.mj_header.endRefreshing()
self?.tableView.mj_footer.endRefreshing()
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
MBProgressHUD.show(base: view)
} else if indexPath.row == 1 {
MBProgressHUD.show(base: view, title: "加载中...")
} else if indexPath.row == 2 {
MBProgressHUD.show(base: view, title: "加载中...", mode: MBProgressHUDMode.indeterminate)
} else if indexPath.row == 3 {
MBProgressHUD.show(base: view, mode: MBProgressHUDMode.annularDeterminate)
} else if indexPath.row == 4 {
MBProgressHUD.show(base: view, mode: MBProgressHUDMode.determinate)
} else if indexPath.row == 5 {
MBProgressHUD.show(base: view, mode: MBProgressHUDMode.determinateHorizontalBar)
} else if indexPath.row == 6 {
MBProgressHUD.hidden(base: view)
} else if indexPath.row == 7 {
MBProgressHUD.show(base: view, backgroundColor: UIColor.red)
} else if indexPath.row == 8 {
MBProgressHUD.show(base: view, backgroundColor: .clear, style: .solidColor)
} else if indexPath.row == 9 {
ProgressHUD.show(vc: self)
dismissProgressHUD()
} else if indexPath.row == 10 {
ProgressHUD.show(vc: self, status: "加载中...")
dismissProgressHUD()
} else if indexPath.row == 11 {
ProgressHUD.showInfo(vc: self, info: "这是一个提示信息")
}
}
func dismissProgressHUD() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(3)) {
ProgressHUD.dismiss()
}
}
}
<file_sep>//
// ScanController.swift
// Example
//
// Created by USER on 2018/11/29.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
import DDKit
class ScanController: UIViewController {
@IBOutlet weak var qrImageView: UIImageView!
@IBOutlet weak var qr128ImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
@IBAction func scanAction(_ sender: Any) {
//请求授权
DDScanPermissions.authorizeCamera {[weak self] (granted) in
if granted == true {
//方式 1 新建controller继承 DDScanViewController,建议使用第一种方式,在controller中方便做其他操作
let vc = ScanSecondController()
// DDScanStyleConfig中参数可任意修,选择默认,就不需要再创建 style
let style = DDScanStyleConfig()
vc.scanStyle = style
self?.navigationController?.pushViewController(vc, animated: true)
//方式 2 直接使用默认的扫描控制器,需要设置代理
// let vc2 = DDScanViewController()
// vc2.delegate = self
// self?.navigationController?.pushViewController(vc2, animated: true)
}
}
}
@IBAction func createQRAction(_ sender: Any) {
//生成二维码
qrImageView.image = DDScanWrapper.createQrCode(codeString: "WERWRwwer", size: qrImageView.bounds.size, qrColor: UIColor.black, backgroudColor: UIColor.white)
}
@IBAction func create128QRAction(_ sender: Any) {
//生成条形码
qr128ImageView.image = DDScanWrapper.createCode128(codeString: "sdfsdf", size: qr128ImageView.bounds.size, qrColor: UIColor.black, backgroudColor: UIColor.white)
}
}
extension ScanController: DDScanViewControllerDelegate {
func scanFinished(scanResult: DDScanResult?) {
// print(scanResult?.strScanned )
}
}
<file_sep>//
// ToastVC.swift
// Example
//
// Created by senyuhao on 2018/7/26.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
class ToastVC: UITableViewController {
private var items = ["toast-top", "top-center", "top-bottom", "title - message", "toast-circle"]
override init(style: UITableView.Style) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") {
cell.textLabel?.text = items[indexPath.row]
return cell
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
SToast.show(msg: "244343", container: view, position: .top, duration: 3)
} else if indexPath.row == 1 {
SToast.show(msg: "1231231231", container: view, position: .center)
} else if indexPath.row == 2 {
SToast.show(msg: "12312313", container: view, position: .bottom, duration: 1.2)
} else if indexPath.row == 3 {
SToast.show(msg: "今日的领取次数已经用完", title: "领取成功", container: view, duration: 1.2)
} else if indexPath.row == 4 {
SToast.show(msg: "123123123", circle: true)
}
}
}
<file_sep>#!/bin/bash
x=1
while [ $x -le 12 ]
do
echo "Welcome $x times"
x=$(( $x + 1 ))
sleep 300
done
<file_sep>//
// BViewController.swift
// DDRouterDemo
//
// Created by USER on 2018/12/4.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class BViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(params)
let model = params?["model"] as? Model
print(model)
complete?("111111")
}
@IBAction func pushCAction(_ sender: Any) {
pushViewController("CViewController", params: params, animated: true) { (res) in
print(res)
}
}
@IBAction func presentCAction(_ sender: Any) {
presentViewController("CViewController", params: params, animated: true, complete: nil)
}
@IBAction func dismissAction(_ sender: Any) {
dismiss(true)
}
}
<file_sep>
//
// DDPhotoPickerNavigationController.swift
// Photo
//
// Created by USER on 2018/11/13.
// Copyright © 2018 leo. All rights reserved.
//
import UIKit
class DDPhotoPickerNavigationController: UINavigationController {
public var previousStatusBarStyle: UIStatusBarStyle = .default
public var barTintColor: UIColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1) {
didSet {
navigationBar.tintColor = barTintColor
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: barTintColor]
}
}
public var barColor: UIColor = UIColor(red: 25.0/255.0, green: 25.0/255.0, blue: 25.0/255.0, alpha: 1) {
didSet {
navigationBar.setBackgroundImage(imageWithColor(barColor), for: .default)
}
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
navigationBar.barStyle = DDPhotoStyleConfig.shared.navigationBarStyle
navigationBar.isTranslucent = true
if let color = DDPhotoStyleConfig.shared.navigationBackgroudColor {
navigationBar.setBackgroundImage(imageWithColor(color), for: .default)
} else {
navigationBar.setBackgroundImage(imageWithColor(barColor), for: .default)
}
if let color = DDPhotoStyleConfig.shared.navigationTintColor {
navigationBar.tintColor = color
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: color]
} else {
navigationBar.tintColor = barTintColor
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: barTintColor]
}
if let image = DDPhotoStyleConfig.shared.navigationBackImage {
navigationBar.backIndicatorImage = image
navigationBar.backIndicatorTransitionMaskImage = image
} else {
if let path = Bundle(for: DDPhotoPickerNavigationController.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "photo_nav_icon_back_black", in: bundle, compatibleWith: nil)
{
navigationBar.backIndicatorImage = image
navigationBar.backIndicatorTransitionMaskImage = image
}
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = previousStatusBarStyle
}
private func imageWithColor(_ color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
context.setFillColor(color.cgColor)
context.fill(rect)
let theImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return theImage
}
/// 禁止所有的屏幕旋转
// override var shouldAutorotate: Bool {
// return false
// }
//
// override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// return .portrait
// }
//
// override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
// return .portrait
// }
}
<file_sep>//
// SToast.swift
// EatojoyBiz
//
// Created by senyuhao on 2/24/2018.
// Copyright © 2018 dd01. All rights reserved.
//
import SnapKit
import UIKit
public enum ToastPosition: Int {
case top = 0
case bottom = 1
case center = 2
}
public class SToast: NSObject {
public static let shared = SToast()
public var backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.8) // 背景颜色
public var backgroundCorner: CGFloat = 5 // 统一圆角设置;若设置circle为true时,该属性无效
public var titleFont = UIFont.systemFont(ofSize: 16) // 标题字体
public var messageFont = UIFont.systemFont(ofSize: 14) // 内容字体
public var padding: CGFloat = 30.0 // position = top 时 距上距离; position = bottom 时, 距下距离
// position = center时。提示框距离中心点的距离 往上移为正,向下为负
public var centerPadding: CGFloat = 80.0
public class func show(msg: String, title: String? = nil, container: UIView? = nil, position: ToastPosition? = nil, duration: CGFloat? = nil, circle: Bool? = nil) {
if let target = container ?? UIApplication.shared.keyWindow {
if !msg.isEmpty {
let place = position ?? .center
let time = duration ?? 2
DispatchQueue.main.async {
SToast.showToast(msg: msg, title: title, container: target, duration: time, position: place, circle: circle)
}
}
}
}
private class func showToast(msg: String, title: String? = nil, container: UIView, duration: CGFloat, position: ToastPosition, circle: Bool? = nil) {
let baseview = baseView()
baseview.tag = 3001
//防止重复添加
for subView in container.subviews {
if subView.tag == baseview.tag {
subView.removeFromSuperview()
}
}
container.addSubview(baseview)
var height: CGFloat = 10
if let title = title, !title.isEmpty {
let titleLabel = self.titleLabel(title: title)
baseview.addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.top.equalTo(baseview).offset(8)
make.centerX.equalTo(baseview)
make.height.equalTo(20)
}
height = 36
}
let toast = toastLabel(msg: msg)
baseview.addSubview(toast)
let value = SToast.locationInfo(width: container.frame.width * 3 / 4 - 20, toast: toast)
toast.snp.makeConstraints { make in
make.top.equalTo(baseview).offset(height)
make.left.equalTo(baseview).offset(10)
make.right.equalTo(baseview).offset(-10)
make.height.equalTo(value.height)
}
baseview.snp.makeConstraints { make in
make.height.equalTo(value.height + height + 12)
make.width.equalTo(value.width + 20)
make.centerX.equalTo(container)
switch position {
case .top:
make.top.equalTo(container).offset(SToast.shared.padding)
case .center:
make.centerY.equalTo(container).offset(-SToast.shared.centerPadding)
case .bottom:
if let container = container as? UIScrollView {
make.top.equalTo(container).offset(scrollViewHeight(container: container) - (value.height + height + 12) - SToast.shared.padding)
} else {
make.bottom.equalTo(container.snp.bottom).offset(-SToast.shared.padding)
}
}
}
if let circle = circle, circle {
let baseHeight = value.height + height + 12
baseview.layer.cornerRadius = baseHeight / 2.0
} else {
baseview.layer.cornerRadius = SToast.shared.backgroundCorner
}
toastAnimate(view: baseview, duration: duration)
}
// animate动画
static func toastAnimate(view: UIView, duration: CGFloat) {
UIView.animate(withDuration: 0.5,
delay: TimeInterval(duration),
options: [.curveEaseIn, .beginFromCurrentState],
animations: {
view.alpha = 0.0
},
completion: { _ in
view.removeFromSuperview()
})
}
// toast消失
static public func dismissToast(container: UIView? = nil) {
if let toast = container?.subviews.last {
if toast.tag == 999 {
toast.removeFromSuperview()
}
} else {
if let toast = UIApplication.shared.keyWindow?.subviews.last {
if toast.tag == 999 {
toast.removeFromSuperview()
}
}
}
}
// label自适应高度
static func locationInfo(width: CGFloat, toast: UILabel) -> CGSize {
var frame = toast.frame
frame.size.width = width
toast.frame = frame
toast.sizeToFit()
return toast.frame.size
}
// container为scrollview时高度计算
static func scrollViewHeight(container: UIScrollView) -> CGFloat {
return container.frame.size.height + container.contentOffset.y
}
}
extension SToast {
private class func toastLabel(msg: String) -> UILabel {
let toast = UILabel(frame: .zero)
toast.text = msg
toast.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
toast.numberOfLines = 100
toast.textAlignment = .center
toast.lineBreakMode = .byWordWrapping
toast.font = SToast.shared.messageFont
return toast
}
private class func titleLabel(title: String) -> UILabel {
let titleLabel = UILabel(frame: .zero)
titleLabel.text = title
titleLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
titleLabel.font = SToast.shared.titleFont
return titleLabel
}
private class func baseView() -> UIView {
let baseview = UIView(frame: .zero)
baseview.backgroundColor = SToast.shared.backgroundColor
baseview.layer.masksToBounds = true
baseview.tag = 999
return baseview
}
}
extension UIView {
/// Toast show
///
/// - Parameters:
/// - msg: 提示文字
/// - title: 标题
/// - position: 位置
/// - duration: 时长
/// - circle: 是否需要圆角
public func showToast(msg: String, title: String? = nil, position: ToastPosition? = .center, duration: CGFloat? = 2.0, circle: Bool? = false) {
SToast.show(msg: msg, title: title, container: self, position: position, duration: duration, circle: circle)
}
}
<file_sep>//
// AccountModule.swift
// Route
//
// Created by 鞠鹏 on 2018/6/11.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
public protocol AccountServiceAPI {
func login(userName: String, passWord: String, complete: ((NSError?) -> Void))
func logout()
func register(userName: String, passWord: String, verifyCode: String, complete: ((NSError?) -> Void))
}
class AccountService: NSObject, AccountServiceAPI {
func login(userName: String, passWord: String, complete: ((NSError?) -> Void)) {
print(".........login")
}
func logout() {
print("=========logout")
}
func register(userName: String, passWord: String, verifyCode: String, complete: ((NSError?) -> Void)) {
print("-----------register")
}
}
<file_sep>//
// MagicTextField.swift
// MagicTextFieldDemo
//
// Created by leo on 2018/12/7.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
public class MagicTextField: UITextField {
// public property
//placeholder移动后的字体大小
public var animatedFont: UIFont? = UIFont.systemFont(ofSize: 12)
//placeholder移动后的文字显示
public var animatedText: String?
//placeholder向上移动的距离,负数向下
public var moveDistance: CGFloat = 0.0
//UITextFieldDidChange事件回调
public var magicFieldDidChangeCallBack: (()->())?
//placeholder的颜色,默认为灰色
public var placeholderColor: UIColor? {
didSet {
placeholderAnimationLab.textColor = placeholderColor
animatedPlaceholderColor = placeholderColor
}
}
//placeholder移动后的颜色,默认为placeholderColor,设置此属性一定要在设置placeholderColor的后面
public var animatedPlaceholderColor: UIColor?
//离输入框左边的边距,默认为0
public var marginLeft: CGFloat = 0
//重写父类placeholder
override public var placeholder: String? {
didSet {
placeholderAnimationLab.text = placeholder
self.tmpPlaceholder = placeholder
super.placeholder = ""
}
}
//重写父类textAlignment
override public var textAlignment: NSTextAlignment {
didSet {
placeholderAnimationLab.textAlignment = textAlignment
}
}
//重写父类font
override public var font: UIFont? {
didSet {
placeholderFont = font
placeholderAnimationLab.font = font
animatedFont = font
super.font = font
}
}
private var isFirstLoad: Bool = true
private lazy var placeholderAnimationLab: UILabel = {
let animationLab = UILabel()
animationLab.isUserInteractionEnabled = false
animationLab.textColor = UIColor(red: 136.0/255.0, green: 136.0/255.0, blue: 136.0/255.0, alpha: 0.6)
return animationLab
}()
private var placeholderFont: UIFont?
private var tmpPlaceholder:String?
public init() {
super.init(frame: CGRect.zero)
moveDistance = frame.size.height / 2
setupUI()
}
override public init(frame: CGRect) {
super.init(frame: frame)
moveDistance = frame.size.height / 2
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
if isFirstLoad == true {
isFirstLoad = false
var rect = bounds
rect.origin.x = rect.origin.x + marginLeft
rect.size.width = rect.width - marginLeft
placeholderAnimationLab.frame = rect
leftView = UIView(frame: CGRect(x: 0, y: 0, width: marginLeft, height: 0))
leftViewMode = .always
}
}
override public func becomeFirstResponder() -> Bool {
startAnimation()
return super.becomeFirstResponder()
}
override public func resignFirstResponder() -> Bool {
restoreAnimation()
return super.resignFirstResponder()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension MagicTextField {
func startAnimation() {
var targetFrame = self.placeholderAnimationLab.frame
targetFrame.origin.y = -moveDistance
UIView.animate(withDuration: 0.25) {
self.placeholderAnimationLab.frame = targetFrame
self.placeholderAnimationLab.textColor = self.animatedPlaceholderColor
self.placeholderAnimationLab.font = self.animatedFont
self.placeholderAnimationLab.text = self.animatedText?.count == 0 ? self.placeholderAnimationLab.text : self.animatedText
}
}
func restoreAnimation() {
if text?.count ?? 0 > 0 || placeholderAnimationLab.frame.origin.y == 0 {
return
}
var targetFrame = self.placeholderAnimationLab.frame
targetFrame.origin.y = 0
UIView.animate(withDuration: 0.25) {
self.placeholderAnimationLab.frame = targetFrame
self.placeholderAnimationLab.textColor = self.placeholderColor
self.placeholderAnimationLab.font = self.placeholderFont
self.placeholderAnimationLab.text = self.tmpPlaceholder
}
}
}
private extension MagicTextField {
func setupUI() {
placeholderColor = placeholderAnimationLab.textColor
animatedPlaceholderColor = placeholderColor
addSubview(placeholderAnimationLab)
NotificationCenter.default.addObserver(self, selector: #selector(changeEditing), name: UITextField.textDidChangeNotification, object: nil)
}
@objc func changeEditing() {
if let callBack = magicFieldDidChangeCallBack {
callBack()
}
self.placeholderAnimationLab.isHidden = false
}
}
<file_sep>//
// CHWindow.swift
// CHLog
//
// Created by wanggw on 2018/5/28.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
import UIKit
class CHWindow: UIWindow {
///重写 hitTest,传递触摸事件到下面的视图
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView: UIView? = super.hitTest(point, with: event)
if hitView == self {
return nil
}
return hitView
}
}
<file_sep>
//
// DDPhoto.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/11/22.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
public class DDPhoto: NSObject {
/** 图片地址 */
public var url: URL? {
didSet {
if url?.absoluteString.hasSuffix(".gif") == true || url?.absoluteString.hasSuffix(".GIF") == true {
isGif = true
}
if url?.absoluteString.hasSuffix(".mp4") == true || url?.absoluteString.hasSuffix(".mov") == true {
isVideo = true
}
}
}
/** video */
public var isVideo: Bool = false
/** 来源imageView */
public var sourceImageView: UIImageView?
/** 来源frame */
public var sourceFrame: CGRect?
/** 图片(静态) */
public var image: UIImage?
/** 占位图 */
public var placeholderImage: UIImage?
public override init() {
}
//MARK -- 下述参数无需配置
/** gif */
var isGif: Bool = false
/** 图片是否加载完成 */
var isFinished: Bool = false
/** 图片是否加载失败 */
var isFailed: Bool = false
/** 记录photoView是否缩放 */
var isZooming: Bool = false
var zoomRect: CGRect = CGRect.zero
var isFirstPhoto: Bool = false
}
<file_sep>
//
// PlayeCell.swift
// mpdemo
//
// Created by USER on 2018/11/14.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class PlayeCell: UITableViewCell {
lazy var containerView: UIImageView = {
let containerView = UIImageView()
containerView.isUserInteractionEnabled = true
return containerView
}()
lazy var playBtn: UIButton = {
let playBtn = UIButton(type: .custom)
playBtn.setTitle("播放", for: .normal)
playBtn.setTitleColor(UIColor.black, for: .normal)
playBtn.addTarget(self, action: #selector(playBtnAction(_:)), for: .touchUpInside)
return playBtn
}()
var playBtnCallBack: ((PlayeCell?, IndexPath?)->())?
var indexPath : IndexPath?
@objc func playBtnAction(_ sender: UIButton) {
if let callBack = playBtnCallBack {
callBack(self, indexPath)
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(containerView)
containerView.addSubview(playBtn)
containerView.snp.makeConstraints { (make) in
make.left.top.right.bottom.equalTo(contentView)
}
playBtn.snp.makeConstraints { (make) in
make.center.equalTo(containerView)
make.width.height.equalTo(50)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// CityListNormalCell.swift
// PlacePickerDemo
//
// Created by weiwei.li on 2019/1/3.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class CityListNormalCell: UITableViewCell {
private lazy var line: UIView = {
let line = UIView()
line.backgroundColor = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1)
return line
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(line)
textLabel?.font = UIFont.systemFont(ofSize: 17)
textLabel?.textColor = UIColor(red: 51.0/255.0, green: 51.0/255.0, blue:
51.0/255.0, alpha: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
var lineFrame = bounds
lineFrame.origin.x = 18
lineFrame.origin.y = bounds.height - 1
lineFrame.size.height = 1
lineFrame.size.width = bounds.width - 18
line.frame = lineFrame
}
}
<file_sep>//
// UIImage+ScaleToSize.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/12/12.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
extension UIImage {
func browserScaleToSize(size: CGSize) -> UIImage? {
// UIGraphicsBeginImageContextWithOptions(size, false, scale); //此处将画布放大两倍,这样在retina屏截取时不会影响像素
//
// // 得到图片上下文,指定绘制范围
UIGraphicsBeginImageContext(size);
// 将图片按照指定大小绘制
self.draw(in: CGRect(x:0,y:0,width:size.width,height:size.height))
// 从当前图片上下文中导出图片
let img = UIGraphicsGetImageFromCurrentImageContext()
// 当前图片上下文出栈
UIGraphicsEndImageContext();
// 返回新的改变大小后的图片
return img
}
func browserImageFrame() -> CGSize {
let frame = UIScreen.main.bounds
let imageSize = self.size
var imageF = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
// 图片的宽度 = 屏幕的宽度
let ratio = frame.width / imageF.size.width
imageF.size.width = frame.width
imageF.size.height = ratio * imageF.size.height
return imageF.size
}
}
<file_sep>
//
// UISegmentedControl+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UISegmentedControl {
@discardableResult
func isMomentary(_ bool: Bool) -> Self {
isMomentary = bool
return self
}
@discardableResult
func apportionsSegmentWidthsByContent(_ bool: Bool) -> Self {
apportionsSegmentWidthsByContent = bool
return self
}
@discardableResult
func insertSegment(title t: String?, segment: Int, animated: Bool) -> Self {
insertSegment(withTitle: t, at: segment, animated: animated)
return self
}
@discardableResult
func insertSegment(image i: UIImage?, segment: Int, animated: Bool) -> Self {
insertSegment(with: i, at: segment, animated: animated)
return self
}
@discardableResult
func removeSegment(_ segment: Int, animated: Bool) -> Self {
removeSegment(at: segment, animated: animated)
return self
}
@discardableResult
func removeAll() -> Self {
removeAllSegments()
return self
}
@discardableResult
func selectedSegmentIndex(_ index: Int) -> Self {
selectedSegmentIndex = index
return self
}
@discardableResult
func tintColor(_ color: UIColor) -> Self {
tintColor = color
return self
}
}
<file_sep>//
// UITextView+Placeholder.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UITextView {
fileprivate struct TextViewPlaceholderKey {
static var kTextViewPlaceholderKey = "kTextViewPlaceholderKey"
}
public var placeholder: String? {
get {
return objc_getAssociatedObject(self, &TextViewPlaceholderKey.kTextViewPlaceholderKey) as? String
}
set(value) {
objc_setAssociatedObject(self, &TextViewPlaceholderKey.kTextViewPlaceholderKey, value, .OBJC_ASSOCIATION_COPY_NONATOMIC)
let label = UILabel()
.text(value)
.numberOfLines(0)
.textColor(UIColor.lightGray)
.font(self.font ?? 13)
.sizeFit()
.add(to: self)
self .setValue(label, forKey: "_placeholderLabel")
}
}
}
<file_sep>//
// UIButton+BackgroudColor.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/3/27.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UIButton {
public func setBackground(color: UIColor, forState state: UIControl.State) {
setBackgroundImage(imageFromColor(color: color), for: state)
}
fileprivate func imageFromColor(color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
<file_sep>
//
// DDPhotoViewLoading.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/11/26.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
private let kDDPhotoViewLoadingKey = "kDDPhotoViewLoadingKey.rotation"
class DDPhotoViewLoading: UIView {
private let indicatorLayer = CAShapeLayer()
private let imageView: UIImageView = {
let imageView = UIImageView()
if let path = Bundle(for: DDPhotoViewLoading.classForCoder()).path(forResource: "DDPhotoBrowser", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "video_ratation", in: bundle, compatibleWith: nil) {
imageView.image = image
}
imageView.contentMode = .scaleAspectFill
return imageView
}()
public override init(frame : CGRect) {
super.init(frame : frame)
commonInit()
}
public convenience init() {
self.init(frame:CGRect.zero)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
commonInit()
}
override open func layoutSubviews() {
imageView.frame = bounds
}
}
//MARK --- public method
extension DDPhotoViewLoading {
func startAnimating() {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.duration = 1
animation.fromValue = 0
animation.toValue = (2 * Double.pi)
animation.repeatCount = Float.infinity
animation.isRemovedOnCompletion = false
imageView.layer.add(animation, forKey: kDDPhotoViewLoadingKey)
}
}
//MARK --- private method
private extension DDPhotoViewLoading {
private func commonInit(){
addSubview(imageView)
startAnimating()
}
}
<file_sep>//
// Action+Home.swift
// MediatorDemo
//
// Created by weiwei.li on 2019/3/19.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
extension Mediator {
func getModuleBData() {
let pa = Parameter.create().key("back").value({(res: String) in
print(res)
}).key("name").value("lisi")
let action = Action.action(cls: "ModuleB", method: "test", parameters: pa)
print(dispath(action))
}
}
<file_sep>//
// UIView+Extension.swift
// SBase
//
// Created by senyuhao on 2018/6/21.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
extension UIView {
// MARK: - Xib
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue > 0 ? newValue : 0
}
}
@IBInspectable var borderColor: UIColor {
get {
if let cgcolor = layer.borderColor {
return UIColor(cgColor: cgcolor)
} else {
return .clear
}
}
set {
layer.borderColor = newValue.cgColor
}
}
// MARK: - 常用frame属性
public var originX: CGFloat {
get {
return self.frame.origin.x
}
set {
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
public var originY: CGFloat {
get {
return self.frame.origin.y
}
set {
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
public var width: CGFloat {
get {
return self.frame.size.width
}
set(newWidth) {
var frame = self.frame
frame.size.width = newWidth
self.frame = frame
}
}
public var height: CGFloat {
get {
return self.frame.size.height
}
set(newHeight) {
var frame = self.frame
frame.size.height = newHeight
self.frame = frame
}
}
public var centerX: CGFloat {
get {
return self.center.x
}
set(newCenterX) {
var center = self.center
center.x = newCenterX
self.center = center
}
}
public var centerY: CGFloat {
get {
return self.center.y
}
set(newCenterY) {
var center = self.center
center.y = newCenterY
self.center = center
}
}
}
<file_sep>//
// UICollectionView+Blocks.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UICollectionView {
fileprivate struct CollectionViewKey {
// MARK: - UICollectionViewDataSource
static var UICollectionViewNumberOfItemsInSectionKey = "UICollectionViewNumberOfItemsInSectionKey"
static var UICollectionViewCellForItemAtIndexPathKey = "UICollectionViewCellForItemAtIndexPathKey"
static var UICollectionViewNumberOfSectionsKey = "UICollectionViewNumberOfSectionsKey"
static var UICollectionViewViewForSupplementaryElementOfKindAtIndexPathKey = "UICollectionViewViewForSupplementaryElementOfKindAtIndexPathKey"
static var UICollectionViewCanMoveItemAtIndexPathKey = "UICollectionViewCanMoveItemAtIndexPathKey"
static var UICollectionViewMoveItemAtSourceIndexPathToDestinationIndexPathKey = "UICollectionViewMoveItemAtSourceIndexPathToDestinationIndexPathKey"
static var UICollectionViewIndexTitlesKey = "UICollectionViewIndexTitlesKey"
static var UICollectionViewIndexPathForIndexTitleAtIndexKey = "UICollectionViewIndexPathForIndexTitleAtIndexKey"
// MARK: - UICollectionViewDelegate
static var UICollectionViewShouldHighlightItemAtIndexPathKey = "UICollectionViewShouldHighlightItemAtIndexPathKey"
static var UICollectionViewDidHighlightItemAtIndexPathKey = "UICollectionViewDidHighlightItemAtIndexPathKey"
static var UICollectionViewDidUnhighlightItemAtIndexPathKey = "UICollectionViewDidUnhighlightItemAtIndexPathKey"
static var UICollectionViewShouldSelectItemAtIndexPathKey = "UICollectionViewShouldSelectItemAtIndexPathKey"
static var UICollectionViewShouldDeselectItemAtIndexPathKey = "UICollectionViewShouldDeselectItemAtIndexPathKey"
static var UICollectionViewDidSelectItemAtIndexPathKey = "UICollectionViewDidSelectItemAtIndexPathKey"
static var UICollectionViewDidDeselectItemAtIndexPathKey = "UICollectionViewDidDeselectItemAtIndexPathKey"
static var UICollectionViewWillDisplayCellforItemAtIndexPathKey = "UICollectionViewWillDisplayCellforItemAtIndexPathKey"
static var UICollectionViewWillDisplaySupplementaryViewForElementKindKey = "UICollectionViewWillDisplaySupplementaryViewForElementKindKey"
static var UICollectionViewDidEndDisplayingCellForItemAtIndexPathKey = "UICollectionViewDidEndDisplayingCellForItemAtIndexPathKey"
static var UICollectionViewDidEndDisplayingSupplementaryViewForElementOfKindKey = "UICollectionViewDidEndDisplayingSupplementaryViewForElementOfKindKey"
static var UICollectionViewShouldShowMenuForItemAtIndexPathKey = "UICollectionViewShouldShowMenuForItemAtIndexPathKey"
static var UICollectionViewCanPerformActionforItemAtIndexPathWithSenderKey = "UICollectionViewCanPerformActionforItemAtIndexPathWithSenderKey"
static var UICollectionViewPerformActionforItemAtIndexPathWithSenderKey = "UICollectionViewPerformActionforItemAtIndexPathWithSenderKey"
//下述两种代理暂不提供
//custom transition layout
//focus
// MARK: - UICollectionViewDelegateFlowLayout
static var UICollectionViewLayoutCollectionViewLayoutSizeForItemAtIndexPathKey = "UICollectionViewLayoutCollectionViewLayoutSizeForItemAtIndexPathKey"
static var UICollectionViewLayoutCollectionViewLayoutInsetForSectionAtSectionKey = "UICollectionViewLayoutCollectionViewLayoutInsetForSectionAtSectionKey"
static var UICollectionViewLayoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionKey = "UICollectionViewLayoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionKey"
static var UICollectionViewLayoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionKey = "UICollectionViewLayoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionKey"
static var UICollectionViewLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionKey = "UICollectionViewLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionKey"
static var UICollectionViewLayoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionKey = "UICollectionViewLayoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionKey"
}
// MARK: - UICollectionViewDataSource
fileprivate var numberOfItemsInSectionBlock: ((UICollectionView, Section)->(Int))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewNumberOfItemsInSectionKey) as? ((UICollectionView, Section) -> (Int))
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewNumberOfItemsInSectionKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var cellForItemAtIndexPathBlock: ((UICollectionView, IndexPath)->(UICollectionViewCell))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewCellForItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> (UICollectionViewCell))
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewCellForItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var numberOfSectionsBlock: ((UICollectionView)->(Int))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewNumberOfSectionsKey) as? ((UICollectionView) -> (Int))
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewNumberOfSectionsKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var viewForSupplementaryElementOfKindAtIndexPathBlock: ((UICollectionView, ElementKind, IndexPath)->(UICollectionReusableView))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewViewForSupplementaryElementOfKindAtIndexPathKey) as? ((UICollectionView, ElementKind, IndexPath) -> (UICollectionReusableView))
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewViewForSupplementaryElementOfKindAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var canMoveItemAtIndexPathBlock: ((UICollectionView, IndexPath)->(Bool))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewCanMoveItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> (Bool))
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewCanMoveItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var moveItemAtSourceIndexPathToDestinationIndexPathBlock: ((UICollectionView, IndexPath,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewMoveItemAtSourceIndexPathToDestinationIndexPathKey) as? ((UICollectionView, IndexPath,IndexPath) -> ())
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewMoveItemAtSourceIndexPathToDestinationIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var indexTitlesBlock: ((UICollectionView)->([String]?))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewIndexTitlesKey) as? ((UICollectionView) -> ([String]?))
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewIndexTitlesKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var indexPathForIndexTitleAtIndexBlock: ((UICollectionView, String, Int)->(IndexPath))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewIndexPathForIndexTitleAtIndexKey) as? ((UICollectionView, String, Int) -> (IndexPath))
}
set(value) {
setDataSource()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewIndexPathForIndexTitleAtIndexKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate func setDataSource() {
if dataSource == nil || dataSource?.isEqual(self) == false {
dataSource = self
}
}
// MARK: - UICollectionViewDelegate
fileprivate func setDelegate() {
if delegate == nil || delegate?.isEqual(self) == false {
delegate = self
}
}
fileprivate var shouldHighlightItemAtIndexPathBlock: ((UICollectionView,IndexPath)->(Bool))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldHighlightItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldHighlightItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didHighlightItemAtIndexPathBlock: ((UICollectionView,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewDidHighlightItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewDidHighlightItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didUnhighlightItemAtIndexPathBlock: ((UICollectionView,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewDidUnhighlightItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewDidUnhighlightItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldSelectItemAtIndexPathBlock: ((UICollectionView,IndexPath)->(Bool))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldSelectItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldSelectItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldDeselectItemAtIndexPathBlock: ((UICollectionView,IndexPath)->(Bool))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldDeselectItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldDeselectItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didSelectItemAtIndexPathBlock: ((UICollectionView,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewDidSelectItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewDidSelectItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didDeselectItemAtIndexPathBlock: ((UICollectionView,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewDidDeselectItemAtIndexPathKey) as? ((UICollectionView, IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewDidDeselectItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var willDisplayCellforItemAtIndexPathBlock: ((UICollectionView,UICollectionViewCell,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewWillDisplayCellforItemAtIndexPathKey) as? ((UICollectionView, UICollectionViewCell,IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewWillDisplayCellforItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var willDisplaySupplementaryViewForElementKindBlock: ((UICollectionView,UICollectionReusableView,String,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewWillDisplaySupplementaryViewForElementKindKey) as? ((UICollectionView,UICollectionReusableView,String,IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewWillDisplaySupplementaryViewForElementKindKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didEndDisplayingCellForItemAtIndexPathBlock: ((UICollectionView,UICollectionViewCell,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewDidEndDisplayingCellForItemAtIndexPathKey) as? ((UICollectionView,UICollectionViewCell,IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewDidEndDisplayingCellForItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didEndDisplayingSupplementaryViewForElementOfKindBlock: ((UICollectionView,UICollectionReusableView,String,IndexPath)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewDidEndDisplayingSupplementaryViewForElementOfKindKey) as? ((UICollectionView,UICollectionReusableView,String,IndexPath) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewDidEndDisplayingSupplementaryViewForElementOfKindKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldShowMenuForItemAtIndexPathBlock: ((UICollectionView,IndexPath)->(Bool))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldShowMenuForItemAtIndexPathKey) as? ((UICollectionView,IndexPath) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewShouldShowMenuForItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var canPerformActionforItemAtIndexPathWithSenderBlock: ((UICollectionView,Selector,IndexPath,Any?)->(Bool))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewCanPerformActionforItemAtIndexPathWithSenderKey) as? ((UICollectionView,Selector,IndexPath,Any?) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewCanPerformActionforItemAtIndexPathWithSenderKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var performActionforItemAtIndexPathWithSenderBlock: ((UICollectionView,Selector,IndexPath,Any?)->())? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewPerformActionforItemAtIndexPathWithSenderKey) as? ((UICollectionView,Selector,IndexPath,Any?) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewPerformActionforItemAtIndexPathWithSenderKey, value, .OBJC_ASSOCIATION_COPY);
}
}
// MARK: - UICollectionViewDelegateFlowLayout
fileprivate var layoutCollectionViewLayoutSizeForItemAtIndexPathBlock: ((UICollectionView,UICollectionViewLayout,IndexPath)->(CGSize))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutSizeForItemAtIndexPathKey) as? ((UICollectionView,UICollectionViewLayout,IndexPath) -> (CGSize))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutSizeForItemAtIndexPathKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var layoutCollectionViewLayoutInsetForSectionAtSectionBlock: ((UICollectionView,UICollectionViewLayout,Section)->(UIEdgeInsets))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutInsetForSectionAtSectionKey) as? ((UICollectionView,UICollectionViewLayout,Section) -> (UIEdgeInsets))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutInsetForSectionAtSectionKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var layoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionBlock: ((UICollectionView,UICollectionViewLayout,Section)->(CGFloat))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionKey) as? ((UICollectionView,UICollectionViewLayout,Section) -> (CGFloat))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var layoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionBlock: ((UICollectionView,UICollectionViewLayout,Section)->(CGFloat))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionKey) as? ((UICollectionView,UICollectionViewLayout,Section) -> (CGFloat))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var layoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock: ((UICollectionView,UICollectionViewLayout,Section)->(CGSize))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionKey) as? ((UICollectionView,UICollectionViewLayout,Section) -> (CGSize))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var layoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionBlock: ((UICollectionView,UICollectionViewLayout,Section)->(CGSize))? {
get {
return objc_getAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionKey) as? ((UICollectionView,UICollectionViewLayout,Section) -> (CGSize))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &CollectionViewKey.UICollectionViewLayoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionKey, value, .OBJC_ASSOCIATION_COPY);
}
}
}
// MARK: - UICollectionViewDataSource
extension UICollectionView {
public func setNumberOfItemsInSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ section: Section)->(Int))) {
numberOfItemsInSectionBlock = handler
}
public func setCellForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(UICollectionViewCell))) {
cellForItemAtIndexPathBlock = handler
}
public func setNumberOfSectionsBlock(_ handler: @escaping((_ collectionView: UICollectionView)->(Int))) {
numberOfSectionsBlock = handler
}
public func setViewForSupplementaryElementOfKindAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ kind: ElementKind, _ indexPath: IndexPath)->(UICollectionReusableView))) {
viewForSupplementaryElementOfKindAtIndexPathBlock = handler
}
public func setCanMoveItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) {
canMoveItemAtIndexPathBlock = handler
}
public func setMoveItemAtSourceIndexPathToDestinationIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ sourceIndexPath: IndexPath, _ destinationIndexPath: IndexPath)->())) {
moveItemAtSourceIndexPathToDestinationIndexPathBlock = handler
}
public func setIndexTitlesBlock(_ handler: @escaping((_ collectionView: UICollectionView)->([String]?))) {
indexTitlesBlock = handler
}
public func setIndexPathForIndexTitleAtIndexBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ title: String, _ index: Int)->(IndexPath))) {
indexPathForIndexTitleAtIndexBlock = handler
}
}
// MARK: - UICollectionViewDelegate
extension UICollectionView {
public func setShouldHighlightItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) {
shouldHighlightItemAtIndexPathBlock = handler
}
public func setDidHighlightItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) {
didHighlightItemAtIndexPathBlock = handler
}
public func setDidUnhighlightItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) {
didUnhighlightItemAtIndexPathBlock = handler
}
public func setShouldSelectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) {
shouldSelectItemAtIndexPathBlock = handler
}
public func setShouldDeselectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) {
shouldDeselectItemAtIndexPathBlock = handler
}
public func setDidSelectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) {
didSelectItemAtIndexPathBlock = handler
}
public func setDidDeselectItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->())) {
didDeselectItemAtIndexPathBlock = handler
}
public func setWillDisplayCellforItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ cell: UICollectionViewCell, _ indexPath: IndexPath)->())) {
willDisplayCellforItemAtIndexPathBlock = handler
}
public func setWillDisplaySupplementaryViewForElementKindBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ view: UICollectionReusableView, _ elementKind: String, _ indexPath: IndexPath)->())) {
willDisplaySupplementaryViewForElementKindBlock = handler
}
public func setDidEndDisplayingCellForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ cell: UICollectionViewCell,_ indexPath: IndexPath)->())) {
didEndDisplayingCellForItemAtIndexPathBlock = handler
}
public func setDidEndDisplayingSupplementaryViewForElementOfKindBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ view: UICollectionReusableView, _ elementKind: String, _ indexPath: IndexPath)->())) {
didEndDisplayingSupplementaryViewForElementOfKindBlock = handler
}
public func setShouldShowMenuForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ indexPath: IndexPath)->(Bool))) {
shouldShowMenuForItemAtIndexPathBlock = handler
}
public func setCanPerformActionforItemAtIndexPathWithSenderBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ action: Selector,_ indexPath: IndexPath, _ sender: Any?)->(Bool))) {
canPerformActionforItemAtIndexPathWithSenderBlock = handler
}
public func setPerformActionforItemAtIndexPathWithSenderBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ action: Selector,_ indexPath: IndexPath, _ sender: Any?)->())) {
performActionforItemAtIndexPathWithSenderBlock = handler
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension UICollectionView {
public func setLayoutCollectionViewLayoutSizeForItemAtIndexPathBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ indexPath: IndexPath)->(CGSize))) {
layoutCollectionViewLayoutSizeForItemAtIndexPathBlock = handler
}
public func setLayoutCollectionViewLayoutInsetForSectionAtSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(UIEdgeInsets))) {
layoutCollectionViewLayoutInsetForSectionAtSectionBlock = handler
}
public func setLayoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGFloat))) {
layoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionBlock = handler
}
public func setLayoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGFloat))) {
layoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionBlock = handler
}
public func setLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGSize))) {
layoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock = handler
}
public func setLayoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionBlock(_ handler: @escaping((_ collectionView: UICollectionView, _ layout: UICollectionViewLayout,_ section: Section)->(CGSize))) {
layoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionBlock = handler
}
}
extension UICollectionView: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
if let block = shouldHighlightItemAtIndexPathBlock {
return block(collectionView, indexPath)
}
return true
}
public func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
didHighlightItemAtIndexPathBlock?(collectionView, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
didUnhighlightItemAtIndexPathBlock?(collectionView, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if let block = shouldSelectItemAtIndexPathBlock {
return block(collectionView, indexPath)
}
return true
}
public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
if let block = shouldDeselectItemAtIndexPathBlock {
return block(collectionView, indexPath)
}
return true
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didSelectItemAtIndexPathBlock?(collectionView, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
didDeselectItemAtIndexPathBlock?(collectionView, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
willDisplayCellforItemAtIndexPathBlock?(collectionView, cell, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
willDisplaySupplementaryViewForElementKindBlock?(collectionView, view, elementKind, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
didEndDisplayingCellForItemAtIndexPathBlock?(collectionView, cell, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
didEndDisplayingSupplementaryViewForElementOfKindBlock?(collectionView, view, elementKind, indexPath)
}
public func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
if let block = shouldShowMenuForItemAtIndexPathBlock {
return block(collectionView, indexPath)
}
return false
}
public func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
if let block = canPerformActionforItemAtIndexPathWithSenderBlock {
return block(collectionView, action, indexPath, sender)
}
return false
}
public func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
performActionforItemAtIndexPathWithSenderBlock?(collectionView, action, indexPath, sender)
}
}
extension UICollectionView: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let block = numberOfItemsInSectionBlock {
return block(collectionView, section)
}
return 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let block = cellForItemAtIndexPathBlock {
return block(collectionView, indexPath)
}
return UICollectionViewCell()
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
if let block = numberOfSectionsBlock {
return block(collectionView)
}
return 1
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let block = viewForSupplementaryElementOfKindAtIndexPathBlock {
return block(collectionView, kind, indexPath)
}
return UICollectionReusableView()
}
public func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
if let block = canMoveItemAtIndexPathBlock {
return block(collectionView, indexPath)
}
return true
}
public func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
moveItemAtSourceIndexPathToDestinationIndexPathBlock?(collectionView, sourceIndexPath, destinationIndexPath)
}
public func indexTitles(for collectionView: UICollectionView) -> [String]? {
if let block = indexTitlesBlock {
return block(collectionView)
}
return nil
}
public func collectionView(_ collectionView: UICollectionView, indexPathForIndexTitle title: String, at index: Int) -> IndexPath {
if let block = indexPathForIndexTitleAtIndexBlock {
return block(collectionView, title, index)
}
return IndexPath(row: 0, section: 0)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension UICollectionView: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let block = layoutCollectionViewLayoutSizeForItemAtIndexPathBlock {
return block(collectionView, collectionViewLayout, indexPath)
}
return CGSize(width: 0, height: 0)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
if let block = layoutCollectionViewLayoutInsetForSectionAtSectionBlock {
return block(collectionView, collectionViewLayout, section)
}
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
if let block = layoutCollectionViewLayoutMinimumLineSpacingForSectionAtSectionBlock {
return block(collectionView, collectionViewLayout, section)
}
return 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
if let block = layoutCollectionViewLayoutMinimumInteritemSpacingForSectionAtSectionBlock {
return block(collectionView, collectionViewLayout, section)
}
return 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if let block = layoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock {
return block(collectionView, collectionViewLayout, section)
}
return CGSize(width: 0, height: 0)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if let block = layoutCollectionViewLayoutReferenceSizeForFooterInSectionSectionBlock {
return block(collectionView, collectionViewLayout, section)
}
return CGSize(width: 0, height: 0)
}
}
<file_sep>//
// DDPhotoToast.swift
// Photo
//
// Created by USER on 2018/11/13.
// Copyright © 2018 leo. All rights reserved.
//
import UIKit
import SnapKit
let toastDuration: CGFloat = 1.0
class DDPhotoToast: NSObject {
public class func showToast(msg: String) {
if let container = UIApplication.shared.keyWindow {
showToast(msg: msg, container: container)
}
}
public class func showToast(msg: String, container: UIView) {
DispatchQueue.main.async {
let toast = UILabel(frame: .zero)
toast.text = msg
toast.backgroundColor = UIColor.black
toast.textColor = UIColor.white
toast.numberOfLines = 100
toast.tag = 999
toast.textAlignment = .center
toast.lineBreakMode = .byWordWrapping
toast.font = UIFont.systemFont(ofSize: 14)
container.addSubview(toast)
toast.layer.cornerRadius = 5
toast.layer.masksToBounds = true
let size = msg.boundingRect(with: CGSize(width: 220, height: 999),
options: .usesLineFragmentOrigin,
attributes: [NSAttributedString.Key.font: toast.font],
context: nil).size
let height = size.height + 15.0
let width = size.width <= 220.0 ? size.width + 30 : 220
toast.snp.makeConstraints { make in
make.center.equalTo(container)
make.width.equalTo(width)
make.height.equalTo(height)
}
UIView.animate(withDuration: 0.5,
delay: TimeInterval(toastDuration),
options: [.curveEaseIn, .beginFromCurrentState],
animations: {
toast.alpha = 0.0
},
completion: { _ in
toast.removeFromSuperview()
})
}
}
}
<file_sep>//
// DDPhotoBrowerCell.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/12/12.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class DDPhotoBrowerCell: UICollectionViewCell {
public let photoView = DDPhotoView(frame: CGRect.zero)
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor.clear
contentView.addSubview(photoView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
var rect = contentView.bounds
rect.size.width = rect.width - 10
photoView.frame = rect
photoView.resetFrame()
}
deinit {
photoView.removeFromSuperview()
}
func browserZoomShow(_ photo: DDPhoto?) {
guard let photo = photo else {
return
}
if photo.image != nil {
photoView.setupPhoto(photo)
} else {
let imgSize = photo.sourceImageView?.image?.browserImageFrame() ?? CGSize.zero
photoView.imageView.image = (photo.placeholderImage != nil) ? photo.placeholderImage : photo.sourceImageView?.image?.browserScaleToSize(size: imgSize)
// photoView.adjustFrame()
// photoView.imageView.image = (photo.placeholderImage != nil) ? photo.placeholderImage : photo.sourceImageView?.image
photoView.adjustFrame(photo: photo)
}
let endRect = photoView.imageView.frame
var sourceRect = photo.sourceFrame
if sourceRect?.equalTo(CGRect.zero) == true || sourceRect == nil {
sourceRect = photo.sourceImageView?.superview?.convert(photo.sourceImageView?.frame ?? CGRect.zero, to: (browserViewController() as? DDPhotoBrowerController)?.contentView)
}
photoView.imageView.frame = sourceRect ?? CGRect.zero
UIView.animate(withDuration: 0.2, animations: {
self.photoView.imageView.frame = endRect
}) { (finished) in
self.photoView.setupPhoto(photo)
if photo.isVideo == true {
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
self.photoView.videoView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
self.photoView.videoView.playBtnAction(nil)
photo.isFirstPhoto = false
self.photoView.videoView.setNeedsLayout()
self.photoView.videoView.layoutIfNeeded()
}
}
}
}
extension UIView {
func browserViewController () -> UIViewController? {
var next: UIResponder?
next = self.next
repeat {
if (next as? UIViewController) != nil {
return next as? UIViewController
} else {
next = next?.next
}
} while next != nil
return UIViewController()
}
}
<file_sep>//
// PageTabsViewController.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/18.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
extension NSNotification.Name {
static let kPageTabsContainerCanScrollName = NSNotification.Name("kPageTabsContainerCanScrollName")
static let kPageTabsContainerAllCotentoffsetZero = NSNotification.Name("kPageTabsContainerAllCotentoffsetZero")
static let kPageTabsContainerEndHeaderRefresh = NSNotification.Name("kPageTabsContainerEndHeaderRefresh")
}
public enum PageTabsType {
case multiWork // 多级联动
case segmented //无header的tabs
}
/// PageTabsContainerController 此类为抽象类,只能继承,请勿直接创建
open class PageTabsContainerController: UIViewController {
public var segmentViewItems:[String]? {
didSet {
segmentView.itemList = segmentViewItems
}
}
public var viewControllerList:[PageTabsBaseController]? {
didSet {
for vc in viewControllerList ?? [] {
vc.tabsType = tabsType
}
pageContentView.viewControllerList = viewControllerList
}
}
public var tabsType: PageTabsType = .multiWork {
didSet {
if tabsType == .segmented {
pageContainerView.headerView = nil
}
for vc in viewControllerList ?? [] {
vc.tabsType = tabsType
}
}
}
public lazy var segmentView: PageSegmentView = {
let segmentView = PageSegmentView(frame: CGRect(x: 0, y: 100, width: view.frame.width, height: 44))
segmentView.delegate = self
segmentView.itemWidth = 0
segmentView.itemTitleNormalColor = UIColor(red: 139.0/255.0, green: 142.0/255.0, blue: 147.0/255.0, alpha: 1)
segmentView.itemTitleSelectedColor = UIColor(red: 41.0/255.0, green: 41.0/255.0, blue: 41.0/255.0, alpha: 1)
segmentView.segmentBackgroudColor = UIColor.white
segmentView.bottomLineWidth = 20
segmentView.bottomLineHeight = 2
segmentView.bottomLineColor = UIColor(red: 67.0/255.0, green: 116.0/255.0, blue: 1, alpha: 1)
return segmentView
}()
public lazy var pageContainerView: PageTabsContainerView = {
let containerView = PageTabsContainerView(frame: CGRect.zero)
containerView.delegate = self
containerView.dataSource = self
return containerView
}()
public lazy var pageContentView: PageTabsContentView = {
let content = PageTabsContentView(frame: CGRect.zero)
content.delegate = self
return content
}()
public var headerView: UIView? {
didSet {
pageContainerView.headerView = headerView
if headerView == nil || headerView?.frame.height == 0 {
tabsType = .segmented
} else {
tabsType = .multiWork
}
}
}
private var currentIndex = 0
override open func viewDidLoad() {
super.viewDidLoad()
setupUI()
NotificationCenter.default.addObserver(self, selector: #selector(notifactionCanscroll), name: NSNotification.Name.kPageTabsContainerCanScrollName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(endPullData), name: NSNotification.Name.kPageTabsContainerEndHeaderRefresh, object: nil)
}
@objc private func notifactionCanscroll() {
// 通知容器可以开始滚动
pageContainerView.canScroll = true
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pageContainerView.frame = view.bounds
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension PageTabsContainerController {
//子类调用此方法
public func requesetPullData() {
if currentIndex >= viewControllerList?.count ?? -1 {
return
}
//刷新对应的子控制器界面
let vc = viewControllerList?[currentIndex]
vc?.requesetPullData(currentIndex: currentIndex)
}
// 需要子类重写此方法
@objc open func endPullData() {}
}
extension PageTabsContainerController: PageSegmentViewDelegate {
@objc public func segmentView(segmentView: PageSegmentView, didScrollTo index: Int) {
currentIndex = index
pageContentView.scroll(To: index)
}
}
extension PageTabsContainerController: PageTabsContentViewDelegate {
public func contentView(view: PageTabsContentView, didScrollTo index: Int) {
currentIndex = index
segmentView.scrollToIndex(index)
}
}
extension PageTabsContainerController: PageTabsContainerViewDelegate, PageTabsContainerViewDataSource {
@objc public func pageTabsContentCanScroll(containerView: PageTabsContainerView) {
//将所有容器设置为可滚动
for vc in viewControllerList ?? [] {
vc.canContentScroll = true
}
}
@objc public func pageTabsContainerCanScroll(containerView: PageTabsContainerView) {
// 当容器开始可以滚动时,将所有内容设置回到顶部
NotificationCenter.default.post(name: NSNotification.Name.kPageTabsContainerAllCotentoffsetZero, object: nil, userInfo: nil)
}
@objc public func pageTabsContainerDidScroll(scrollView: UIScrollView) {
// 监听容器的滚动,来设置NavigationBar的透明度
}
@objc public func pageTabsContainerViewInsetTop(containerView: PageTabsContainerView) -> CGFloat {
return isIphonex() ? 88 : 64
}
@objc public func pageTabsContainerViewInsetBottom(containerView: PageTabsContainerView) -> CGFloat {
// return isIphonex() ? 34 : 0
return 0
}
}
extension PageTabsContainerController {
private func getSubViewController(_ index: Int) -> PageTabsBaseController {
guard let list = viewControllerList else {
return PageTabsBaseController()
}
if index >= list.count {
return PageTabsBaseController()
}
return list[index]
}
private func setupUI() {
view.backgroundColor = UIColor.white
view.addSubview(pageContainerView)
pageContainerView.segmentView = segmentView
pageContainerView.contentView = pageContentView
tabsType = .multiWork
/// 初始化默认选择tab
segmentView.scrollToIndex(0)
}
/// 判断是否是iphonex以上机型
///
/// - Returns: bool
public func isIphonex() -> Bool {
var isIphonex = false
if UIDevice.current.userInterfaceIdiom != .phone {
return isIphonex
}
if #available(iOS 11.0, *) {
/// 利用safeAreaInsets.bottom > 0.0来判断是否是iPhone X 以上机型。
let mainWindow = UIApplication.shared.keyWindow
if mainWindow?.safeAreaInsets.bottom ?? CGFloat(0.0) > CGFloat(0.0) {
isIphonex = true
}
}
return isIphonex
}
}
<file_sep>
//
// DDMediator.swift
// DDMediatorDemo
//
// Created by USER on 2018/12/5.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
/// 若调用sdk中的模块,或者pod管理的模块,需要传入模块名,swift中存在命名空间
public let kMediatorTargetModuleName = "kMediatorTargetModuleName"
//定义两个类型
public typealias MediatorParamDic = [String: Any]
public typealias MediatorCallBack = (Any?) -> ()
public class DDMediator: NSObject {
/// 单列
public static let shared = DDMediator()
/// 服务模块对象的开头字符串命名,默认 "Target"开头
public var moduleName: String = "Target"
//初始化缓存
private var cacheTarget = [String: NSObject]()
}
extension DDMediator {
/// perform
///
/// - Parameters:
/// - targetName: 对应的target名字
/// - actionName: target中的方法名
/// - params: 传入的参数
/// - isCacheTarget: 是否需要缓存Target对象,多次调用只需要初始化一个对象
/// - complete: 完成回调
public func perform(Target targetName: String, actionName: String, params: MediatorParamDic?, isCacheTarget: Bool = true, complete: MediatorCallBack?) {
/// 获取targetClass字符串
let swiftModuleName = params?[kMediatorTargetModuleName] as? String
var targetClassString: String?
if (swiftModuleName?.count ?? 0) > 0 {
targetClassString = (swiftModuleName ?? "") + "." + "Target_\(targetName)"
} else {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
targetClassString = namespace + "." + "\(moduleName)_\(targetName)"
}
guard let classString = targetClassString else {
return
}
var target = cacheTarget[classString]
var targetClass: NSObject.Type
if target == nil {
//获取Target对象
targetClass = NSClassFromString(classString) as! NSObject.Type
target = targetClass.init()
//缓存target
if isCacheTarget == true {
if let obj = target {
cacheTarget[classString] = obj
}
}
}
//获取Target对象中的方法Selector
let sel = Selector(actionName)
//定义回调block
let result: MediatorCallBack = { res in
complete?(res)
}
//创建参数model
let model = MediatorParams()
model.callBack = result
model.params = params
if target?.responds(to: sel) == true {
target?.perform(sel, with: model)
}
return
}
}
<file_sep>//
// CityListViewController.swift
// PlacePickerDemo
//
// Created by weiwei.li on 2019/1/2.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
public class CityListViewController: UITableViewController {
//MARK: - 私有属性
private let listViewModel = CityListViewModel()
//MARK: - public属性
/// 当前城市
public var currentCity: String? {
didSet {
listViewModel.currentCity = currentCity
}
}
/// 热门城市
public var hotCitys: [String]? {
didSet {
listViewModel.hotCitys = hotCitys
}
}
/// 所有城市哈希对象
public var cityDatas: [String: [String]]? {
didSet {
listViewModel.cityDatas = cityDatas
}
}
/// 是否加载本地的city.plist数据
public var isLoadingNativeCityPlist: Bool = true
/// 选中回调
public var selectedComplete: ((String?)->())?
public override init(style: UITableView.Style) {
super.init(style: style)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
setupUI()
//addNotification
NotificationCenter.default.addObserver(self, selector: #selector(selectedCityName(notification:)), name: NSNotification.Name.init("kSelectedCityNameKey"), object: nil)
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension CityListViewController: CityListViewModelDelegate {
func reloadData() {
tableView.reloadData()
}
}
// MARK: - Table view data source
extension CityListViewController {
override public func numberOfSections(in tableView: UITableView) -> Int {
return listViewModel.numberSections
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listViewModel.numberOfRowsInSection(section: section)
}
override public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return listViewModel.viewForHeaderInSection(tableView: tableView, section: section)
}
public override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
public override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return listViewModel.heightForRowAt(indexPath: indexPath)
}
public override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return listViewModel.heightForHeaderInSection(section: section)
}
public override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.1
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section < 2 {
return listViewModel.tableView(tableView, cellForRowAt: indexPath, identifier: "CityListHotCell")
}
return listViewModel.tableView(tableView, cellForRowAt: indexPath, identifier: "CityListNormalCell")
}
public override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return listViewModel.sectionIndexTitles()
}
public override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if index < 2 {
return 1
}
return index / 2
}
public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let key = listViewModel.cityDataKeys?[indexPath.section],
let citys = listViewModel.cityDatas?[key] else {
return
}
let city = citys[indexPath.row]
NotificationCenter.default.post(name: NSNotification.Name.init("kSelectedCityNameKey"), object: nil, userInfo: ["city": city])
}
}
// MARK: - private Method
extension CityListViewController {
private func setupUI() {
//注册Cell
tableView.register(CityListHotCell.self, forCellReuseIdentifier: "CityListHotCell")
tableView.register(CityListNormalCell.self, forCellReuseIdentifier: "CityListNormalCell")
tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "HeaderFooterView")
tableView.tableFooterView = UIView()
tableView.backgroundColor = UIColor(red: 245.0/255.0, green: 245.0/255.0, blue: 245.0/255.0, alpha: 1)
tableView.separatorStyle = .none
//设置delegate
listViewModel.delegate = self
//是否加载本地数据
if isLoadingNativeCityPlist == true {
listViewModel.requestNativeData()
}
}
@objc private func selectedCityName(notification: Notification) {
selectedComplete?(notification.userInfo?["city"] as? String)
navigationController?.popViewController(animated: true)
}
}
<file_sep>//
// CViewController.swift
// DDRouterDemo
//
// Created by USER on 2018/12/5.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class CViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(params)
}
//pop到下一层控制器
@IBAction func popAction(_ sender: Any) {
//回调
complete?("我要pop了")
pop(animated: true)
}
// pop到指定的控制器
@IBAction func popToController(_ sender: Any) {
pop(ToViewController: "BViewController")
}
// pop到根控制器
@IBAction func popToRootController(_ sender: Any) {
pop(ToRootViewController: true)
}
//dismiss
@IBAction func dismissAction(_ sender: Any) {
dismiss(true)
}
}
<file_sep># DDCustomCamera
[demo地址](https://github.com/weiweilidd01/DDCustomCameraDemo)
#### DDCustomCamera和DDPhotoPicker合成一个组件DDCustomCamera
#### 1.前期初始化
1.请在info.plist中添加相册,照片,麦克风授权权限
2.DDPhotoStyleConfig配置对象,为单列
基本使用样例
```
// DDPhotoStyleConfig UI配置针对于e肚仔项目,其他项目无特殊需求不必关心
// DDPhotoStyleConfig初始化实际项目中,可丢到AppDelegate中初始化
// if let path = Bundle(for: DDPhotoPickerViewController.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
// let bundle = Bundle(path: path),
// let image = UIImage(named: "photo_nav_icon_back_black", in: bundle, compatibleWith: nil)
// {
// DDPhotoStyleConfig.shared.navigationBackImage = image
// }
// DDPhotoStyleConfig.shared.navigationBackgroudColor = UIColor.white
// DDPhotoStyleConfig.shared.navigationTintColor = UIColor.black
// DDPhotoStyleConfig.shared.navigationBarStyle = .default
//
// DDPhotoStyleConfig.shared.seletedImageCircleColor = UIColor.red
// DDPhotoStyleConfig.shared.bottomBarBackgroudColor = UIColor.white
// DDPhotoStyleConfig.shared.bottomBarTintColor = UIColor.red
DDPhotoStyleConfig.shared.photoAssetType = .imageOnly
//若你的第一级入口为选择照片,那个在相册中的进入拍照时,是否允许摄像
DDPhotoStyleConfig.shared.isEnableRecordVideo = false
DDPhotoStyleConfig.shared.maxSelectedNumber = 9
```
#### 2.基本调用
1.相册调用
```
DDPhotoPickerManager.show {[weak self] (resultArr) in
}
```
2.拍照调用
```
DDCustomCameraManager.show { (resultArr) in
}
```
#### 2.相册返回数组模型 DDPhotoGridCellModel
```
//资源对象
public var asset: PHAsset
//缩略图 -- 若为视屏,则返回视屏首张图片
public var image: UIImage?
//视屏时长
public var duration: String = ""
//当前资源类型
public var type: DDAssetMediaType?
```
#### 3.拍照完成回调DDCustomCameraResult
```
//资源对象
public var asset: PHAsset?
public var isVideo: Bool? //fale: 为图片, true为视屏
//图片 -- 若为视屏,则返回视屏首张图片
public var image: UIImage?
//时长
public var duration: String?
```
#### 4.若要上传视屏,获取对应的filePath
```
/// 上传视屏时,导出的filePath,图片不需要调用
///
/// - Parameter asset: asset
func getPath(asset: PHAsset?) {
if asset?.mediaType != .video {
return
}
//presetName 参数主要使用一下三个
//AVAssetExportPresetLowQuality
//AVAssetExportPresetMediumQuality
//AVAssetExportPresetHighestQuality
DDCustomCameraManager.exportVideoFilePath(for: asset, type: .mp4, presetName: AVAssetExportPresetMediumQuality) { (path, err) in
//path默认存储在沙盒的tmp目录下
print(path)
}
//清除存储在tmp目录下的文件。需要就调用
DDCustomCameraManager.cleanMoviesFile()
}
```
#### 5.DDCustomCameraManager和DDPhotoImageManager提供操作asset方法,两者方法大体类似,都能调用
```
/// 获取图片
///
/// - Parameters:
/// - asset: asset
/// - targetSize: 获取图片的size(用于展示实际所需大小)
/// - resultHandler: 回调
/// - Returns: id
static public func requestImageForAsset(for asset: PHAsset?, targetSize: CGSize, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID
/// 获取原始图片的data(用于上传)
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestOriginalImageDataForAsset(for asset: PHAsset?, resultHandler: @escaping (Data?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID
/// 获取相册视屏播放的item
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestVideoForAsset(for asset: PHAsset?, resultHandler: @escaping (AVPlayerItem?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID
/// 获取视屏的avasset
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestAVAssetForAsset(for asset: PHAsset?, resultHandler: @escaping (AVAsset?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID
/// 导出视屏上传临时存储的filePath
///
/// - Parameters:
/// - asset: asset
/// - type: 导出格式
/// - presetName: 压缩格式 ,常见的为以下三种
//AVAssetExp
ortPresetLowQuality
//AVAssetExportPresetMediumQuality
//AVAssetExportPresetHighestQuality
/// - compelete: 完成回调
static public func exportVideoFilePath(for asset: PHAsset?, type: DDExportVideoType, presetName: String, compelete:((String?, NSError?)->())?)
```
#### 5.具体使用,请参照[demo地址](https://github.com/weiweilidd01/DDCustomCameraDemo)
<file_sep>//
// Request+User.swift
// Example
//
// Created by senyuhao on 2018/7/11.
// Copyright © 2018年 dd01. All rights reserved.
//
import Alamofire
import CryptoSwift
import Foundation
import PromiseKit
import DDKit
struct StoreStatus: Codable {
var status: Int
private enum CodingKeys: String, CodingKey {
case status = "operating_status"
}
}
struct ResponseVersion: Decodable {
let code: Int
let message: String?
let data: Version?
}
struct Version: Codable {
var version: String?
var desc: String?
var source: String?
var type: Int? // 1:普通升级,2:强制升级
private enum CodingKeys: String, CodingKey {
case version
case desc
case source
case type
}
}
struct EBDefaultInfo: Codable { }
struct ResponseInter<T>: Decodable where T: Codable {
let status: Bool
let code: Int
let message: String?
let data: T?
}
struct Session: Codable {
var id: Int
var time: Int
var token: String
var reset: Int
private enum CodingKeys: String, CodingKey {
case id = "vendor_id"
case token = "vendor_token"
case time
case reset
}
}
extension DDRequest {
static func login(mobile: String, password: String, previous: @escaping(ResponseInter<Session>) -> Void) -> Promise<ResponseInter<Session>> {
let params = [
"account": mobile,
"password": <PASSWORD>()
]
return DDRequest.post(path: "vendor/login", params: params, cache: true, previous: previous)
}
static func loginBlock(mobile: String, password: String, handler: @escaping(ResponseInter<Session>?, Error?) -> Void) {
let params = [
"account": mobile,
"password": <PASSWORD>()
]
DDRequest.post(path: "vendor/login", params: params, cache: true) { value, error in
handler(value, error)
}
}
}
class Tool: NSObject {
public static let shared = Tool()
public class func storeLatestCookie(token: String) {
UserDefaults.standard.set(token, forKey: "Cookie")
}
class func useLatestCookies() -> HTTPHeaders? {
var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders
if let cookinfo = UserDefaults.standard.value(forKey: "Cookie") as? String {
defaultHeaders["Cookie"] = cookinfo
}
print("headers = \(defaultHeaders)")
return defaultHeaders
}
@objc public func needLogin() {
print("123")
}
@objc public func upgradeValue(_ value: Data) {
let decoder = DDKit.JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let resp = try? decoder.decode(ResponseVersion.self, from: value)
if let data = resp?.data {
print(data)
}
}
}
<file_sep>//
// CHLogHeader.swift
// CHLog
//
// Created by wanggw on 2018/7/2.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
import UIKit
class CHLogHeader: UIView {
private var titleLabel = UILabel()
private var logInfo: CHLogItem?
private var target: UIViewController?
override var canBecomeFirstResponder: Bool {
return true //最最最关键的代码。。。。。。。。
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupCopyMenu()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
private func setupUI() {
backgroundColor = UIColor.white
titleLabel.font = UIFont.systemFont(ofSize: 12)
titleLabel.textColor = UIColor.black
titleLabel.numberOfLines = 0
titleLabel.isUserInteractionEnabled = true
addSubview(titleLabel)
}
private func setupCopyMenu() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showMenuAction)))
}
// MARK: - Action
@objc private func showMenuAction() {
if UIMenuController.shared.isMenuVisible {
UIMenuController.shared.setMenuVisible(false, animated: true)
return
}
becomeFirstResponder()
let saveMenuItem = UIMenuItem(title: "拷贝请求参数", action: #selector(copyAction))
UIMenuController.shared.menuItems = [saveMenuItem]
UIMenuController.shared.setTargetRect(titleLabel.frame, in: self)
UIMenuController.shared.setMenuVisible(true, animated: true)
}
@objc private func copyAction() {
UIPasteboard.general.string = logInfo?.describeString()
let alert = UIAlertController(title: "提示", message: "已经拷贝至剪切板", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
target?.present(alert, animated: true, completion: nil)
}
// MARK: - updateContent
public func updateContent(logInfo: CHLogItem, target: UIViewController) {
self.logInfo = logInfo
self.target = target
backgroundColor = logInfo.isRequest ? UIColor.white : UIColor.black
titleLabel.attributedText = logInfo.attributedDescribeString()
titleLabel.frame = CGRect(x: 15, y: 5, width: self.bounds.size.width - 30, height: self.bounds.size.height - 10)
}
}
<file_sep>//
// CHURLSession.swift
// DDDebug
//
// Created by shenzhen-dd01 on 2019/1/18.
// Copyright © 2019 shenzhen-dd01. All rights reserved.
//
import UIKit
class CHURLSession: NSObject {
static let shared = CHURLSession()
private override init() {
super.init()
}
}
// MARK: - Notification
extension CHURLSession {
func addNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(getRequestInfo), name: NSNotification.Name(rawValue: "NSURLSession_Hook_Request"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(getResponseInfo), name: NSNotification.Name(rawValue: "NSURLSession_Hook_Response"), object: nil)
}
@objc func getRequestInfo(noti: Notification) {
dealWithNotification(noti)
}
@objc func getResponseInfo(noti: Notification) {
dealWithNotification(noti)
}
func dealWithNotification(_ noti: Notification) {
guard let userInfo = noti.userInfo else {
return
}
var session = SessionItem()
if let method = userInfo["method"] as? String,
let url = userInfo["url"] as? String,
let headers = userInfo["headers"] as? [String: String],
let parameters = userInfo["parameters"] as? [String: String] {
session.method = method
session.url = url
session.headers = headers
session.parameters = parameters
}
if let response = userInfo["response"] as? [String: Any] {
session.response = response
//判断是否是error
var isError = false
//if let code = response["code"] as? Int {
// isError = code == 0 ? false : true
//}
if let status = response["status"] as? Bool {
isError = status ? false : true
}
session.isError = isError
}
DDDebug.log(with: session)
}
}
struct SessionItem: DDRequstItemProtocol {
var method: String?
var url: String?
var headers: [String : String]?
var parameters: [String : String]?
var response: [String : Any]?
var isError: Bool?
}
<file_sep>//
// PhotoBrowserVideoView.swift
// DDPhotoBrowserDemo
//
// Created by weiwei.li on 2019/1/23.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
enum PlayerState: Int {
case none // default
case playing
case paused
case playFinished
case error
}
enum PlayerBufferstate: Int {
case none // default
case readyToPlay
case buffering
case stop
case bufferFinished
}
class PhotoBrowserVideoView: UIView {
lazy private var playBtn: UIButton = {
let playBtn = UIButton(type: .custom)
if let path = Bundle(for: PhotoBrowserVideoView.classForCoder()).path(forResource: "DDPhotoBrowser", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "video_btn_play_two", in: bundle, compatibleWith: nil)
{
playBtn.setImage(image, for: .normal)
}
playBtn.addTarget(self, action: #selector(playBtnAction(_:)), for: .touchUpInside)
return playBtn
}()
private var playLayer: AVPlayerLayer = AVPlayerLayer()
private var player: AVPlayer?
private var playerAsset : AVURLAsset?
private var playerItem : AVPlayerItem? {
willSet {
removePlayerItemObservers()
removePlayerNotifations()
}
didSet {
addPlayerItemObservers()
addPlayerNotifications()
}
}
lazy private var bottomView = PhotoBrowserVideoBottom()
private lazy var activityView: UIActivityIndicatorView = {
let activityView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
activityView.center = CGPoint(x: UIScreen.main.bounds.width / 2.0, y: UIScreen.main.bounds.height / 2.0)
activityView.style = .whiteLarge
return activityView
}()
//监听player时间回调
private var timeObserver: Any?
private var playerItemStatus: AVPlayerItem.Status = .unknown
private lazy var photoImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = true
return imageView
}()
private lazy var tap: UITapGestureRecognizer = {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognizer(_:)))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
tap.delegate = self
return tap
}()
lazy private var closeBtn: UIButton = {
let closeBtn = UIButton(type: .custom)
if let path = Bundle(for: PhotoBrowserVideoBottom.classForCoder()).path(forResource: "DDPhotoBrowser", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "arrow", in: bundle, compatibleWith: nil) {
closeBtn.setImage(image, for: .normal)
}
closeBtn.addTarget(self, action: #selector(closeBtnAction), for: .touchUpInside)
return closeBtn
}()
//当前播放状态
var state: PlayerState = .none {
didSet {
if state != oldValue {
if state == .playFinished {
activityView.isHidden = true
activityView.stopAnimating()
}
}
}
}
//当前缓冲状态
var bufferState : PlayerBufferstate = .none {
didSet {
if bufferState != oldValue {
if bufferState == .buffering || bufferState == .stop {
activityView.isHidden = false
activityView.startAnimating()
} else {
activityView.isHidden = true
activityView.stopAnimating()
}
}
}
}
var photo: DDPhoto? {
didSet {
playBtn.isHidden = false
photoImageView.isHidden = false
photoImageView.image = photo?.sourceImageView?.image
bottomView.isHidden = false
closeBtn.isHidden = false
addGestureRecognizer(tap)
reset()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
playBtn.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
playBtn.center = center
photoImageView.frame = bounds
playLayer.frame = bounds
var inset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0);
if #available(iOS 11.0, *) {
inset = safeAreaInsets
}
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
bottomView.frame = CGRect(x: 0, y: screenHeight - inset.bottom - 50, width: screenWidth, height: 50)
closeBtn.frame = CGRect(x: 10, y: inset.top + 10, width: 20, height: 20)
}
deinit {
print(self)
reset()
}
}
extension PhotoBrowserVideoView {
public func play() {
playBtn.isHidden = true
bringSubviewToFront(bottomView)
photoImageView.isHidden = true
player?.play()
bottomView.isHidden = false
closeBtn.isHidden = false
bottomView.changePlayBtnImage(true)
}
public func pause() {
// playBtn.isHidden = false
// bringSubview(toFront: playBtn)
state = .paused
player?.pause()
bottomView.changePlayBtnImage(false)
}
public func reset() {
pause()
playLayer.removeFromSuperlayer()
player?.removeTimeObserver(timeObserver as Any)
playerAsset?.cancelLoading()
playerAsset = nil
playerItem?.cancelPendingSeeks()
playerItem = nil
NotificationCenter.default.removeObserver(self)
player = nil
bottomView.playerDurationDidChange(0, totalDuration: 0)
removePlayerNotifations()
removePlayerItemObservers()
playBtn.isHidden = false
photoImageView.isHidden = false
bottomView.isHidden = true
closeBtn.isHidden = false
}
/// 是否正在播放
func isPlay() -> Bool {
if (player?.rate ?? 0) > Float(0) {
return true
}
return false
}
public func seekTime(_ time: TimeInterval, completion: ((Bool) -> Void)?) {
if time.isNaN || playerItemStatus != .readyToPlay {
if completion != nil {
completion!(false)
}
return
}
DispatchQueue.main.async { [weak self] in
self?.pause()
self?.player?.currentItem?.seek(to: CMTimeMakeWithSeconds(time, preferredTimescale: Int32(NSEC_PER_SEC)), completionHandler: { (finished) in
DispatchQueue.main.async(execute: {
self?.play()
if let completion = completion {
completion(finished)
}
})
})
}
}
}
private extension PhotoBrowserVideoView {
func addPlayerItemObservers() {
let options = NSKeyValueObservingOptions([.new, .initial])
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: options, context: nil)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges), options: options, context: nil)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.playbackBufferEmpty), options: options, context: nil)
}
func addPlayerNotifications() {
NotificationCenter.default.addObserver(self, selector: .pbPlayerItemDidPlayToEndTime, name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: .pbApplicationWillEnterForeground, name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: .pbApplicationDidEnterBackground, name: UIApplication.didEnterBackgroundNotification, object: nil)
}
func removePlayerItemObservers() {
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status))
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges))
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.playbackBufferEmpty))
}
func removePlayerNotifations() {
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}
func setupUI() {
addSubview(photoImageView)
addSubview(playBtn)
addSubview(bottomView)
addSubview(activityView)
bottomView.videoView = self
activityView.isHidden = true
activityView.stopAnimating()
bringSubviewToFront(playBtn)
addSubview(closeBtn)
}
func addNotification() {
timeObserver = player?.addPeriodicTimeObserver(forInterval: .init(value: 1, timescale: 1), queue: DispatchQueue.main, using: { [weak self] time in
if let currentTime = self?.player?.currentTime().seconds,
let totalDuration = self?.player?.currentItem?.duration.seconds {
self?.bottomView.playerDurationDidChange(currentTime, totalDuration: totalDuration)
}
})
}
}
extension PhotoBrowserVideoView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view?.isDescendant(of: bottomView) == true {
return false
} else {
return true
}
}
@objc func closeBtnAction() {
NotificationCenter.default.post(name: NSNotification.Name("PhotoBrowserVideoViewCloseKey"), object: nil)
}
@objc func playBtnAction(_ sender: UIButton?) {
photoImageView.isHidden = true
if isPlay() {
pause()
return
}
if player != nil {
play()
return
}
guard let url = photo?.url else {
return
}
reset()
let playerAssetTmp = AVURLAsset(url: url, options: .none)
playerAsset = playerAssetTmp
let keys = ["tracks", "playable"];
playerItem = AVPlayerItem(asset: playerAssetTmp, automaticallyLoadedAssetKeys: keys)
player = AVPlayer(playerItem: playerItem)
layer.addSublayer(playLayer)
playLayer.player = player
playLayer.videoGravity = .resizeAspect
//添加通知,添加监听
addNotification()
play()
}
@objc func tapGestureRecognizer(_ tap: UITapGestureRecognizer) {
bottomView.isHidden = !bottomView.isHidden
closeBtn.isHidden = !closeBtn.isHidden
}
@objc func playFinished() {
playBtn.isHidden = false
bringSubviewToFront(playBtn)
activityView.isHidden = true
activityView.stopAnimating()
photoImageView.isHidden = false
bottomView.isHidden = true
bringSubviewToFront(playBtn)
player?.seek(to: CMTime.zero)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItem.Status
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .unknown:
pause()
bufferState = .buffering
case .readyToPlay:
bufferState = .readyToPlay
case .failed:
state = .error
bufferState = .stop
}
playerItemStatus = status
return
}
if keyPath == #keyPath(AVPlayerItem.playbackBufferEmpty){
if let playbackBufferEmpty = change?[.newKey] as? Bool {
if playbackBufferEmpty {
pause()
bufferState = .buffering
}
}
return
}
if keyPath == #keyPath(AVPlayerItem.loadedTimeRanges) {
// 计算缓冲
let loadedTimeRanges = player?.currentItem?.loadedTimeRanges
if let bufferTimeRange = loadedTimeRanges?.first?.timeRangeValue {
let star = bufferTimeRange.start.seconds // The start time of the time range.
let duration = bufferTimeRange.duration.seconds // The duration of the time range.
let bufferTime = star + duration
if let itemDuration = playerItem?.duration.seconds {
if itemDuration == bufferTime {
bufferState = .bufferFinished
}
}
if let currentTime = playerItem?.currentTime().seconds{
if (bufferTime - currentTime) >= 2.0 && state != .paused {
play()
}
if (bufferTime - currentTime) < 2.0 {
bufferState = .buffering
} else {
bufferState = .readyToPlay
}
}
return
}
//播放
play()
}
}
}
//MARK--- Notification callBack
extension PhotoBrowserVideoView {
@objc internal func playerItemDidPlayToEnd(_ notification: Notification) {
if state != .playFinished {
state = .playFinished
}
playFinished()
}
@objc internal func applicationWillEnterForeground(_ notification: Notification) {
pause()
}
@objc internal func applicationDidEnterBackground(_ notification: Notification) {
pause()
}
}
// MARK: - Selecter
extension Selector {
static let pbPlayerItemDidPlayToEndTime = #selector(PhotoBrowserVideoView.playerItemDidPlayToEnd(_:))
static let pbApplicationWillEnterForeground = #selector(PhotoBrowserVideoView.applicationWillEnterForeground(_:))
static let pbApplicationDidEnterBackground = #selector(PhotoBrowserVideoView.applicationDidEnterBackground(_:))
}
<file_sep>//
// ChainableTableView.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/3/27.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
open class ChainableTableView: UITableView {
public var numberOfRowsInSectionBlock:((UITableView,Int)->(Int))?
public var cellForRowAtIndexPathBlock:((UITableView,IndexPath)->(UITableViewCell))?
public var numberOfSectionsBlock:((UITableView)->(Int))?
public var titleForHeaderInSectionBlock:((UITableView, Int)->(String))?
public var titleForFooterInSectionBlock:((UITableView, Int)->(String))?
public var canEditRowAtIndexPathBlock:((UITableView, IndexPath)->(Bool))?
public var canMoveRowAtIndexPathBlock:((UITableView, IndexPath)->(Bool))?
public var sectionIndexTitlesBlock:((UITableView)->([String]?))?
public var sectionForSectionIndexTitleAtIndexBlock:((UITableView, String, Int)->(Int))?
public var commitEditingStyleForRowAtIndexPathBlock:((UITableView, UITableViewCell.EditingStyle, IndexPath)->())?
public var moveRowAtSourceIndexPathtoDestinationIndexPathBlock:((UITableView, IndexPath, IndexPath)->())?
public var willDisplayCellForRowAtIndexPathBlock:((UITableView, UITableViewCell, IndexPath)->())?
public var willDisplayHeaderViewForSectionBlock:((UITableView, UIView, Section)->())?
public var willDisplayFooterViewForSectionBlock:((UITableView, UIView, Section)->())?
public var didEndDisplayingforRowAtIndexPathBlock:((UITableView, UITableViewCell, IndexPath)->())?
public var didEndDisplayingHeaderViewForSectionBlock:((UITableView, UIView, Section)->())?
public var didEndDisplayingFooterViewforSectionBlock:((UITableView, UIView, Section)->())?
public var heightForRowAtIndexPathBlock:((UITableView, IndexPath)->(CGFloat))?
public var heightForHeaderInSectionBlock:((UITableView, Section)->(CGFloat))?
public var heightForFooterInSectionBlock:((UITableView, Section)->(CGFloat))?
public var estimatedHeightForRowAtIndexPathBlock:((UITableView, IndexPath)->(CGFloat))?
public var estimatedHeightForHeaderInSectionBlock:((UITableView, Section)->(CGFloat))?
public var estimatedHeightForFooterInSectionBlock:((UITableView, Section)->(CGFloat))?
public var viewForHeaderInSectionBlock:((UITableView, Section)->(UIView?))?
public var viewForFooterInSectionBlock:((UITableView, Section)->(UIView?))?
public var accessoryButtonTappedForRowWithBlock:((UITableView, IndexPath)->())?
public var shouldHighlightRowAtIndexPathBlock:((UITableView, IndexPath)->(Bool))?
public var didHighlightRowAtIndexPathBlock:((UITableView, IndexPath)->())?
public var didUnhighlightRowAtIndexPathBlock:((UITableView, IndexPath)->())?
public var willSelectRowAtIndexPathBlock:((UITableView, IndexPath)->(IndexPath?))?
public var willDeselectRowAtIndexPathBlock:((UITableView, IndexPath)->(IndexPath?))?
public var didSelectRowAtIndexPathBlock:((UITableView, IndexPath)->())?
public var didDeselectRowAtIndexPathBlock:((UITableView, IndexPath)->())?
public var editingStyleForRowAtIndexPathBlock:((UITableView, IndexPath)->(UITableViewCell.EditingStyle))?
public var titleForDeleteConfirmationButtonForRowAtIndexPathBlock:((UITableView, IndexPath)->(String?))?
public var editActionsForRowAtIndexPathBlock:((UITableView, IndexPath)->([UITableViewRowAction]?))?
// @available(iOS 11.0, *)
// fileprivate var leadingSwipeActionsConfigurationForRowAtIndexPathBlock:((UITableView, IndexPath)->(UISwipeActionsConfiguration?))?
// @available(iOS 11.0, *)
// fileprivate var trailingSwipeActionsConfigurationForRowAtIndexPathBlock:((UITableView, IndexPath)->(UISwipeActionsConfiguration?))?
public var shouldIndentWhileEditingRowAtIndexPathBlock:((UITableView, IndexPath)->(Bool))?
public var willBeginEditingRowAtIndexPathBlock:((UITableView, IndexPath)->())?
public var didEndEditingRowAtIndexPathBlock:((UITableView, IndexPath?)->())?
public override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
setDelegate()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setDelegate()
}
private func setDelegate() {
delegate = self
dataSource = self
}
}
extension ChainableTableView: UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let block = numberOfRowsInSectionBlock {
return block(tableView, section)
}
return 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let block = cellForRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return UITableViewCell()
}
public func numberOfSections(in tableView: UITableView) -> Int {
if let block = numberOfSectionsBlock {
return block(tableView)
}
return 1
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let block = titleForHeaderInSectionBlock {
return block(tableView, section)
}
return nil
}
public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if let block = titleForFooterInSectionBlock {
return block(tableView, section)
}
return nil
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if let block = canEditRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return false
}
public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if let block = canMoveRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return false
}
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if let block = sectionIndexTitlesBlock {
return block(tableView)
}
return nil
}
public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if let block = sectionForSectionIndexTitleAtIndexBlock {
return block(tableView, title, index)
}
return 0
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
commitEditingStyleForRowAtIndexPathBlock?(tableView, editingStyle, indexPath)
}
public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
moveRowAtSourceIndexPathtoDestinationIndexPathBlock?(tableView, sourceIndexPath, destinationIndexPath)
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
willDisplayCellForRowAtIndexPathBlock?(tableView, cell, indexPath)
}
public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
willDisplayHeaderViewForSectionBlock?(tableView, view, section)
}
public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
willDisplayFooterViewForSectionBlock?(tableView, view, section)
}
public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
didEndDisplayingforRowAtIndexPathBlock?(tableView, cell, indexPath)
}
public func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
didEndDisplayingHeaderViewForSectionBlock?(tableView, view, section)
}
public func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) {
didEndDisplayingFooterViewforSectionBlock?(tableView, view, section)
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let block = heightForRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return tableView.estimatedRowHeight
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let block = heightForHeaderInSectionBlock {
return block(tableView, section)
}
return tableView.estimatedSectionHeaderHeight
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if let block = heightForFooterInSectionBlock {
return block(tableView, section)
}
return tableView.estimatedSectionFooterHeight
}
// public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
// if let block = estimatedHeightForRowAtIndexPathBlock {
// return block(tableView, indexPath)
// }
// return tableView.estimatedRowHeight
// }
//
// public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
// if let block = estimatedHeightForHeaderInSectionBlock {
// return block(tableView, section)
// }
// return tableView.estimatedSectionHeaderHeight
// }
//
// public func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
// if let block = estimatedHeightForFooterInSectionBlock {
// return block(tableView, section)
// }
// return tableView.estimatedSectionFooterHeight
// }
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let block = viewForHeaderInSectionBlock {
return block(tableView, section)
}
return nil
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if let block = viewForFooterInSectionBlock {
return block(tableView, section)
}
return nil
}
public func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
accessoryButtonTappedForRowWithBlock?(tableView, indexPath)
}
public func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
if let block = shouldHighlightRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return true
}
public func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
didHighlightRowAtIndexPathBlock?(tableView, indexPath)
}
public func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
didUnhighlightRowAtIndexPathBlock?(tableView, indexPath)
}
public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let block = willSelectRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return indexPath
}
public func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
if let block = willDeselectRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return indexPath
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelectRowAtIndexPathBlock?(tableView, indexPath)
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
didDeselectRowAtIndexPathBlock?(tableView, indexPath)
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if let block = editingStyleForRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return .none
}
public func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
if let block = titleForDeleteConfirmationButtonForRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return nil
}
public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
if let block = editActionsForRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return nil
}
// @available(iOS 11.0, *)
// public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// if let block = leadingSwipeActionsConfigurationForRowAtIndexPathBlock {
// return block(tableView, indexPath)
// }
// return nil
// }
//
// @available(iOS 11.0, *)
// public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// if let block = trailingSwipeActionsConfigurationForRowAtIndexPathBlock {
// return block(tableView, indexPath)
// }
// return nil
// }
public func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
if let block = shouldIndentWhileEditingRowAtIndexPathBlock {
return block(tableView, indexPath)
}
return true
}
public func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
willBeginEditingRowAtIndexPathBlock?(tableView, indexPath)
}
public func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
didEndEditingRowAtIndexPathBlock?(tableView, indexPath)
}
}
<file_sep>//
// PopController.swift
// EatojoyBiz
//
// Created by 胡峰 on 2016/10/31.
// Copyright © 2018年 dd01. All rights reserved.
//
import CoreGraphics
import UIKit
class PopController: UIPresentationController {
var style = PopControllerStyle.alert
var tapToDimiss: (() -> Bool)?
private var keyboardFrame: CGRect?
override var frameOfPresentedViewInContainerView: CGRect {
let size = presentedViewController.preferredContentSize
let containerSize = containerView?.bounds.size ?? size
switch style {
case .alert:
return CGRect(x: (containerSize.width - size.width) / 2.0, y: (containerSize.height - size.height) / 2.0, width: size.width, height: size.height)
case .actionSheet, .actionSheetPad:
return CGRect(x: 0, y: containerSize.height - size.height, width: containerSize.width, height: size.height)
case .popover:
assertionFailure("popover 不应该使用 PopController")
return CGRect(x: 0, y: 0, width: size.width, height: size.height)
}
}
// MARK: -
private lazy var backgroundView = UIView()
override func presentationTransitionWillBegin() {
backgroundView.frame = containerView?.bounds ?? UIScreen.main.bounds
backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
backgroundView.backgroundColor = UIColor.black
backgroundView.alpha = 0
backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapGestureAction(_:))))
if let presentedView = presentedView {
containerView?.insertSubview(backgroundView, belowSubview: presentedView)
} else {
containerView?.addSubview(backgroundView)
}
presentingViewController.transitionCoordinator?.animate( alongsideTransition: { _ in
self.backgroundView.alpha = 0.4
}, completion: nil)
}
override func presentationTransitionDidEnd(_ completed: Bool) {
if !completed {
backgroundView.removeFromSuperview()
}
}
override func dismissalTransitionWillBegin() {
presentingViewController.transitionCoordinator?.animate( alongsideTransition: { _ in
self.backgroundView.alpha = 0.0
}, completion: { _ in
self.backgroundView.removeFromSuperview()
})
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
backgroundView.removeFromSuperview()
}
@objc private func tapGestureAction(_ sender: UITapGestureRecognizer) {
if tapToDimiss?() ?? true {
presentedView?.endEditing(false)
presentingViewController.dismiss(animated: true, completion: nil)
}
}
func updateKeyboard(_ frame: CGRect) {
keyboardFrame = frame
if style == .alert {
UIView.animate(withDuration: 0.25) {
self.presentedView?.transform = CGAffineTransform(translationX: 0, y: frame.origin.y < 500 ? -108: 0)
}
}
}
}
<file_sep>
//
// DDPhotoPreviewBottomView.swift
// Photo
//
// Created by USER on 2018/11/12.
// Copyright © 2018 leo. All rights reserved.
//
import UIKit
let selectedBackBtnColor = UIColor(red: 67.0 / 255.0, green: 116.0 / 255.0, blue: 255.0 / 255.0, alpha: 1)
let normalBackBtnColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
class DDPhotoPreviewBottomView: UIView {
public var rightBtnCallBack: (()->())?
public var leftBtnCallBack: (()->())?
private lazy var selectCircle: UILabel = {
let selectCircle = UILabel()
selectCircle.layer.borderWidth = 1
selectCircle.layer.borderColor = UIColor.white.cgColor
selectCircle.layer.backgroundColor = normalBackBtnColor.cgColor
selectCircle.layer.cornerRadius = 9
selectCircle.layer.masksToBounds = true
selectCircle.isUserInteractionEnabled = true
selectCircle.textColor = UIColor.white
selectCircle.font = UIFont.systemFont(ofSize: 13)
selectCircle.textAlignment = .center
return selectCircle
}()
private lazy var textLab: UILabel = {
let textLab = UILabel()
textLab.text = Bundle.localizedString("选择")
if let color = DDPhotoStyleConfig.shared.bottomBarTintColor {
textLab.textColor = color
} else {
textLab.textColor = UIColor.white
}
textLab.font = UIFont.systemFont(ofSize: 12)
textLab.isUserInteractionEnabled = true
return textLab
}()
lazy var rightBtn: UIButton = {
let rightBtn = UIButton(type: .custom)
rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
rightBtn.addTarget(self, action: #selector(rightBtnAction(button:)), for: .touchUpInside)
rightBtn.setTitle(Bundle.localizedString("完成"), for: .normal)
rightBtn.backgroundColor = selectNotEnableColor
rightBtn.layer.cornerRadius = 4.0
rightBtn.layer.masksToBounds = true
rightBtn.isEnabled = false
return rightBtn
}()
private lazy var leftContainer: UIView = {
let leftContainer = UIView()
leftContainer.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(leftContainerGesture(_:)))
leftContainer.addGestureRecognizer(tap)
return leftContainer
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DDPhotoPreviewBottomView {
func changeSelectedBtnStatus(_ res: Bool? = false, text: String? = "") {
if res == true {
if let color = DDPhotoStyleConfig.shared.bottomBarTintColor {
selectCircle.layer.borderColor = color.cgColor
selectCircle.layer.backgroundColor = color.cgColor
} else {
selectCircle.layer.borderColor = selectedBackBtnColor.cgColor
selectCircle.layer.backgroundColor = selectedBackBtnColor.cgColor
}
selectCircle.text = text
} else {
selectCircle.layer.borderColor = UIColor.white.cgColor
selectCircle.layer.backgroundColor = normalBackBtnColor.cgColor
selectCircle.text = ""
}
}
func changeCompleteBtnStatus(_ count: Int, total: Int = 0) {
if count > 0 {
rightBtn.isEnabled = true
if total > 0 {
rightBtn.setTitle(Bundle.localizedString("完成") + " (\(count)/\(total))", for: .normal)
} else {
rightBtn.setTitle(Bundle.localizedString("完成") + " (\(count))", for: .normal)
}
if let color = DDPhotoStyleConfig.shared.bottomBarTintColor {
rightBtn.backgroundColor = color
} else {
rightBtn.backgroundColor = selectEnableColor
}
} else {
rightBtn.isEnabled = false
if total > 0 {
rightBtn.setTitle(Bundle.localizedString("完成") + " (\(count)/\(total))", for: .normal)
} else {
rightBtn.setTitle(Bundle.localizedString("完成") + " (\(count))", for: .normal)
}
rightBtn.backgroundColor = selectNotEnableColor
}
}
}
private extension DDPhotoPreviewBottomView {
func setupUI() {
if let color = DDPhotoStyleConfig.shared.bottomBarBackgroudColor {
backgroundColor = color.withAlphaComponent(0.8)
} else {
backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
}
addSubview(leftContainer)
addSubview(rightBtn)
leftContainer.snp.makeConstraints { (make) in
make.centerY.equalTo(self)
make.left.equalTo(self).offset(16)
make.top.equalTo(self).offset(10)
make.bottom.equalTo(self).offset(-10)
make.width.equalTo(64)
}
rightBtn.snp.makeConstraints { (make) in
make.right.equalTo(self).offset(-16)
make.top.equalTo(self).offset(10)
make.bottom.equalTo(self).offset(-10)
make.width.equalTo(63)
}
leftContainer.addSubview(selectCircle)
selectCircle.snp.makeConstraints { (make) in
make.left.equalTo(leftContainer)
make.centerY.equalTo(leftContainer)
make.width.height.equalTo(18)
}
leftContainer.addSubview(textLab)
textLab.snp.makeConstraints { (make) in
make.centerY.equalTo(leftContainer)
make.left.equalTo(selectCircle.snp.right).offset(8)
}
}
}
//MARK: --- action
private extension DDPhotoPreviewBottomView {
@objc func rightBtnAction(button: UIButton) {
if let rightBtnCallBack = rightBtnCallBack {
rightBtnCallBack()
}
}
@objc func leftContainerGesture(_ tap: UITapGestureRecognizer) {
if let leftBtnCallBack = leftBtnCallBack {
leftBtnCallBack()
}
}
}
<file_sep>//
// NumberSelectVC.swift
// Example
//
// Created by weiwei.li on 2019/1/7.
// Copyright © 2019 dd01. All rights reserved.
//
import UIKit
import DDKit
class NumberSelectVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// size 120 * 30 为ui设置标准大小。
let number = NumberSelect(frame: CGRect(x: 100, y: 200, width: 120, height: 32))
number.minNumber = 1
number.maxNumber = 20
number.currentNum = 10
number.stepNumber = 2
number.selectedNumberComplete = {
print($0)
}
view.addSubview(number)
}
}
<file_sep>//
// PresentController.swift
// Example
//
// Created by 鞠鹏 on 2018/6/7.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
class PresentController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction private func dismissClick(_ sender: Any) {
dismiss(animated: true, completion: nil)
SToast.shared.padding = 30
SToast.shared.backgroundCorner = 17
SToast.show(msg: "234234234234234", position: .bottom)
}
}
<file_sep># PageTabsController使用指南
#### 1.多级嵌套ScrollView使用
<img src="https://upload-images.jianshu.io/upload_images/2026287-a1b246afc32d0e86.gif?imageMogr2/auto-orient/strip" width=200 height=400 />
* 1.大容器请直接继承PageTabsContainerController类。具体使用参考demo
* 2.若要实现header下拉刷新,请在大容器中实现对应的方法。具体使用参考demo
* 3.若要实现滚动隐藏导航栏,请在大容器中重写父类方法,具体使用参开demo
* 4.tabs子类请直接继承PageTabsBaseController
* 5.tabs子类中必须设置实现UIScrollView的代理,才能控制滚动。同理UITableView,UISCrolleView,UICollectionView同样使用。PageTabsBaseController已经默认创建UITableView。 demo中也提供了嵌套网页的使用说明。具体使用参考demo
#### 2.无header的多级嵌套使用
<img src="https://upload-images.jianshu.io/upload_images/2026287-4f0da15835d2903f.gif?imageMogr2/auto-orient/strip" width=200 height=400 />
* 1.基本使用同上。具体使用参考demo
* 2.下拉刷新的实现,则由tabs子控制器自己去实现。具体使用参考demo
#### 3.PageSegmentView单独使用说明
<img src="https://upload-images.jianshu.io/upload_images/2026287-00d8563513df9517.gif?imageMogr2/auto-orient/strip" width=200 height=400 />
```
let list = ["列表1", "列表2", "列表3", "列表4", "列表5", "列表6"]
segmentView.itemList = list
segmentView.delegate = self
segmentView.itemWidth = 100
segmentView.bottomLineWidth = 20
segmentView.bottomLineHeight = 2
view.addSubview(segmentView)
//初始化默认选择
segmentView.scrollToIndex(5)
```
代理设置
```
//当前点击的Index
func segmentView(segmentView: PageSegmentView, didScrollTo index: Int) {
print(index)
}
```
<file_sep>//
// CityListViewModel.swift
// PlacePickerDemo
//
// Created by weiwei.li on 2019/1/2.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
protocol CityListViewModelDelegate: NSObjectProtocol {
func reloadData()
}
protocol ViewModelProtocol {
associatedtype ViewModel
func bindViewModel(model: ViewModel ,indexPath: IndexPath)
}
class CityListViewModel {
/// 当前城市名
var currentCity:String? {
didSet {
reloadData()
}
}
/// 热门城市
var hotCitys: [String]? {
didSet {
reloadData()
}
}
/// tableView当前的sections
var numberSections: Int = 0
//所有城市哈希对象
var cityDatas: [String: [String]]? {
didSet {
loadKeys()
reloadData()
}
}
//代理
weak var delegate: CityListViewModelDelegate?
//所有城市的key
var cityDataKeys:[String]?
init() {
}
}
// MARK: - public Method
extension CityListViewModel {
/// 加载本地数据
func requestNativeData() {
guard let path = Bundle(for: CityListViewController.classForCoder()).path(forResource: "CityList", ofType: "bundle"),
let bundle = Bundle(path: path),
let plistPath = bundle.path(forResource: "city", ofType: "plist")
else {
return
}
let dic = NSDictionary(contentsOfFile: plistPath)
if let tmp = dic as? [String: [String]] {
cityDatas = tmp
}
}
func numberOfRowsInSection(section: Int) -> Int {
if section == 0 {
return 1
}
if section == 1 {
return 1
}
if let cityDataKeys = cityDataKeys {
let key = cityDataKeys[section]
let count = cityDatas?[key]?.count
return count ?? 0
}
return 0
}
func heightForRowAt(indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && currentCity == nil {
return 0.0
}
if indexPath.section == 1 && hotCitys == nil {
return 0.0
}
if indexPath.section == 0 {
return 40 + 10
}
if indexPath.section == 1 {
let count = ((hotCitys?.count ?? 0) - 1) / 3 + 1
return CGFloat(40 * count + (count - 1) * 10) + 10
}
return 44.0
}
func heightForHeaderInSection(section: Int) -> CGFloat {
if section == 0 && currentCity == nil {
return 0.0
}
if section == 1 && hotCitys == nil {
return 0.0
}
return 35.0
}
func viewForHeaderInSection(tableView: UITableView, section: Int) -> UIView? {
if section == 0 && currentCity == nil {
return UIView()
}
if section == 1 && hotCitys == nil {
return UIView()
}
guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderFooterView") else {
return UIView()
}
header.backgroundColor = UIColor.clear
header.textLabel?.font = UIFont.systemFont(ofSize: 13)
header.textLabel?.textColor = UIColor(red: 153.0/255.0, green: 153.0/255.0, blue: 153.0/255.0, alpha: 1)
if section == 0 {
header.textLabel?.text = "当前城市"
} else if section == 1 {
header.textLabel?.text = "热门城市"
} else {
let key = cityDataKeys?[section]
header.textLabel?.text = key
}
return header
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, identifier: String) -> UITableViewCell {
if indexPath.section < 2 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CityListHotCell", for: indexPath) as? CityListHotCell else {
return UITableViewCell()
}
cell.bindViewModel(model: self, indexPath: indexPath)
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
guard let key = cityDataKeys?[indexPath.section],
let citys = cityDatas?[key] else {
return cell
}
cell.textLabel?.text = citys[indexPath.row]
return cell
}
func sectionIndexTitles() -> [String]? {
//在每个字母的后面加上空格字符串
var newKeys = [String]()
for key in cityDataKeys ?? [] {
newKeys.append(key)
newKeys.append(" ")
}
return newKeys
}
}
// MARK: - private Method
extension CityListViewModel {
private func reloadData() {
//初始化sections
numberSections = 0
if let cityDataKeys = cityDataKeys {
numberSections = cityDataKeys.count
}
//代理回调
delegate?.reloadData()
}
private func loadKeys() {
if let tmp = cityDatas {
var keys = Array(tmp.keys).sorted()
//当前城市索引key设为空
keys.insert("", at: 0)
keys.insert("热", at: 1)
cityDataKeys = keys
}
}
}
<file_sep>//
// TableViewController.swift
// EmptyDataViewDemo
//
// Created by USER on 2018/12/11.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
// MARK: - 注册时:一定要从0依次升序,否则出问题
extension EmptyDataConfig.Name {
static let common = EmptyDataConfig.Name(rawValue: 0)
static let license = EmptyDataConfig.Name(rawValue: 1)
static let activity = EmptyDataConfig.Name(rawValue: 2)
static let integral = EmptyDataConfig.Name(rawValue: 3)
static let wifi = EmptyDataConfig.Name(rawValue: 4)
}
class TableViewController: UITableViewController {
public var dataType = 0
var rows:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
rows = 0
/// 注册EmptydataSources, 在实际使用中,在AppdDelegate中提前注册好
let config1 = EmptyDataConfig(name: EmptyDataConfig.Name.common, title: "暂无内容", image: UIImage(named: "blankpage_common"))
let config2 = EmptyDataConfig(name: EmptyDataConfig.Name.license, title: "您目前没有绑定任何车牌", image: UIImage(named: "blankpage_search"))
let config3 = EmptyDataConfig(name: EmptyDataConfig.Name.activity, title: "暂无活动", image: UIImage(named: "blankpage_activity"))
let config4 = EmptyDataConfig(name: EmptyDataConfig.Name.integral, title: "暂无卡券", image: UIImage(named: "blankpage_integral"))
let config5 = EmptyDataConfig(name: EmptyDataConfig.Name.wifi, title: "oops!沒有网络讯号", image: UIImage(named: "blankpage_wifi"))
let arr = [config1, config2, config3, config4, config5]
EmptyDataManager.shared.dataSources = arr
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
tableView.tableFooterView = UIView()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.asyncAfter()
}
}
deinit {
print(self)
}
func asyncAfter() {
switch dataType {
case 0:
tableView.emptyDataView(name: EmptyDataConfig.Name.common, hasData: false)
break
case 1:
tableView.emptyDataView(name: EmptyDataConfig.Name.license, hasData: false, showButton: true, btnTitle: "添加") { [weak self] in
self?.clickAction()
}
break
case 2:
tableView.emptyDataView(name: EmptyDataConfig.Name.activity, hasData: false)
break
case 3:
tableView.emptyDataView(name: EmptyDataConfig.Name.integral, hasData: false)
break
case 4:
tableView.emptyDataView(name: EmptyDataConfig.Name.wifi, hasData: false, showButton: true, btnTitle: "点击重试") {[weak self] in
self?.clickAction()
}
break
default:
break
}
rows = 0
tableView.reloadData()
}
func clickAction() {
self.rows = 10
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
}
<file_sep>//
// TableViewVC.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class TableViewVC: UIViewController {
@IBOutlet weak var tableView: ChainableTableView!
override func viewDidLoad() {
super.viewDidLoad()
// TODO: --
//若用此链式添加UITableViewDelegate代理方法,请注意:
//1、若需要实现自动估值计算。请实现链式中属性方法进行设置,UITableViewDelegate代理方法中的估值方法不再提供接口
//2. 若通过链式获取代理回调,请不要通过系统方法设置代理,tableVie.delegate = self, tableVie.dataSource = self,否则会无效。
//3. 若链式代理无法满足需求。请设置tableVie.delegate = self, tableVie.dataSource = self再自行实现代理
//扩展全部UITableViewDatasource协议
//扩展了90%协议,未扩展协议为冷门协议,对日常使用无影响
tableView
.register(for: UITableViewCell.self, cellReuseIdentifier: "cell")
.register(for: UITableViewHeaderFooterView.self, headerFooterViewReuseIdentifier: "UITableViewHeaderFooterView")
// .estimatedRowHeight(50)
// .estimatedSectionHeaderHeight(100)
// .estimatedSectionFooterHeight(0.1)
.addNumberOfSectionsBlock { (tab) -> (Int) in
return 5
}
.addNumberOfRowsInSectionBlock { (tab, sec) -> (Int) in
return 10
}
.addHeightForRowAtIndexPathBlock({ (tab, indexPath) -> (CGFloat) in
return 100
})
.addHeightForHeaderInSectionBlock({ (tab, section) -> (CGFloat) in
return 50
})
.addViewForHeaderInSectionBlock({ (tab, section) -> (UIView?) in
if let header = tab.dequeueReusableHeaderFooterView(withIdentifier: "UITableViewHeaderFooterView") {
header.textLabel?
.text("我是第\(section)组")
.font(18)
.textColor(UIColor.red)
return header
}
return UIView()
})
.addViewForFooterInSectionBlock({ (tab, section) -> (UIView?) in
return UIView()
})
.addCellForRowAtIndexPathBlock {[weak self] (tab, indexPath) -> (UITableViewCell) in
if let cell = self?.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) {
cell.textLabel?.text = "\(indexPath.section)组" + "-- \(indexPath.row)行"
return cell
}
return UITableViewCell()
}
.addDidSelectRowAtIndexPathBlock({ (tab, indexPath) in
tab.deselectRow(at: indexPath, animated: true)
print("点击了第\(indexPath.section)组,第\(indexPath.row)行")
})
.addScrollViewDidScrollBlock({ (scrollView) in
print(scrollView.contentOffset)
})
.reload()
}
deinit {
print(self)
}
}
<file_sep>
//
// CustomPhotoController.swift
// Example
//
// Created by USER on 2018/11/27.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
import DDKit
import Photos
class CustomPhotoController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
/*
具体使用请参照wiki: https://github.com/hk01-digital/dd01-ios-ui-kit/wiki/DDCustomCamera-%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97
demo更多演示: https://github.com/weiweilidd01/DDCustomCameraDemo
*/
}
}
<file_sep>//
// ActionPicker.swift
// ActionPickerDemo
//
// Created by USER on 2018/12/20.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import ActionSheetPicker_3_0
public class Picker: NSObject {
private var datePicker: ActionSheetDatePicker?
private var stringPicker: ActionSheetStringPicker?
private lazy var doneBtn: UIButton = {
let doneBtn = UIButton(type: .system)
doneBtn.setTitle("确定", for: .normal)
doneBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
doneBtn.setTitleColor(UIColor(red: 67.0/255.0, green: 116.0/255.0, blue: 255.0/255.0, alpha: 1), for: .normal)
doneBtn.sizeToFit()
return doneBtn
}()
private lazy var cancelBtn: UIButton = {
let cancelBtn = UIButton(type: .system)
cancelBtn.setTitle("取消", for: .normal)
cancelBtn.setTitleColor(UIColor(red: 153.0/255.0, green: 153.0/255.0, blue: 153.0/255.0, alpha: 1), for: .normal)
cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
cancelBtn.sizeToFit()
return cancelBtn
}()
private lazy var toolBarLine: UIView = {
let line = UIView()
line.backgroundColor = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1)
return line
}()
/// 时间选择器
///
/// - Parameters:
/// - datePickerOrigin: 当前需要展示的view
/// - datePickerMode: UIDatePickerMode
/// - originDate: 展示时的起始时间,默认是当前时间
/// - completed: 点击完成回调
/// - canceled: 点击取消回调
@discardableResult public init(datePickerOrigin: UIView, datePickerMode: UIDatePicker.Mode = .date, originDate: Date = Date(), completed: @escaping ((_ selectedDate: Date?)->())) {
super.init()
datePicker = ActionSheetDatePicker(title: "",
datePickerMode: datePickerMode,
selectedDate: originDate,
doneBlock: {(picker, selectedDate, originDate) in
completed(selectedDate as? Date)
}, cancel: { (picker) in
}, origin: datePickerOrigin)
datePicker?.setDoneButton(UIBarButtonItem(customView: doneBtn))
datePicker?.setCancelButton(UIBarButtonItem(customView: cancelBtn))
datePicker?.locale = Locale(identifier: "zh_CN")
showDatePicker()
}
/// 字符串选择器
///
/// - Parameters:
/// - stringPickerOrigin: 当前需要展示的view
/// - rows: 数据源
/// - initialSelection: 默认选择的位置
/// - completed: 完成回调
@discardableResult public init(stringPickerOrigin: UIView,rows: [String],initialSelection: Int, completed: @escaping ((Int, String?)->())) {
super.init()
stringPicker = ActionSheetStringPicker(title: "", rows: rows, initialSelection: initialSelection, doneBlock: { (picker, seletedIndex, value) in
completed(seletedIndex, value as? String)
}, cancel: { (picker) in
}, origin: stringPickerOrigin)
stringPicker?.setDoneButton(UIBarButtonItem(customView: doneBtn))
stringPicker?.setCancelButton(UIBarButtonItem(customView: cancelBtn))
showStringPicker()
}
private func showDatePicker() {
datePicker?.show()
if let toolBar = datePicker?.toolbar {
toolBarLine.frame = CGRect(x: 0, y: toolBar.frame.height - 1, width: UIScreen.main.bounds.width, height: 1)
toolBar.addSubview(toolBarLine)
}
}
private func showStringPicker() {
stringPicker?.show()
if let toolBar = stringPicker?.toolbar {
toolBarLine.frame = CGRect(x: 0, y: toolBar.frame.height - 1, width: UIScreen.main.bounds.width, height: 1)
toolBar.addSubview(toolBarLine)
}
}
}
<file_sep>
//
// MediatorParams.swift
// DDMediatorDemo
//
// Created by USER on 2018/12/5.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
//必须为class, 在selector中传递,不接受struct
public class MediatorParams: NSObject {
/// 接收的参数
public var params: MediatorParamDic?
/// 回调block
public var callBack: MediatorCallBack?
}
<file_sep>//
// UIButton+Chainable.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIButton
public extension UIKitChainable where Self: UIButton {
/// 设置图片位置
///
/// - Parameters:
/// - p: 位置
/// - space: 距离
/// - Returns: self
@discardableResult
func image(position p: ButtonImagePosition, space: CGFloat) -> Self {
imagePosition(p, space: space)
return self
}
/// font
///
/// - Parameter font: font
/// - Returns: self
@discardableResult
func font(_ font: UIFontType) -> Self {
titleLabel?.font = font.font
return self
}
/// contentEdgeInsets
///
/// - Parameter insets: insets
/// - Returns: self
@discardableResult
func contentEdgeInsets(_ insets: UIEdgeInsets) -> Self {
contentEdgeInsets = insets
return self
}
/// titleEdgeInsets
///
/// - Parameter insets: insets
/// - Returns: self
@discardableResult
func titleEdgeInsets(_ insets: UIEdgeInsets) -> Self {
titleEdgeInsets = insets
return self
}
/// reversesTitleShadowWhenHighlighted
///
/// - Parameter highlighted: highlighted
/// - Returns: self
@discardableResult
func reversesTitleShadow(highlighted bool: Bool) -> Self {
reversesTitleShadowWhenHighlighted = bool
return self
}
/// imageEdgeInsets
///
/// - Parameter insets: insets
/// - Returns: self
@discardableResult
func imageEdgeInsets(_ insets: UIEdgeInsets) -> Self {
imageEdgeInsets = insets
return self
}
/// adjustsImage
///
/// - Parameter highlighted: highlighted
/// - Returns: self
@discardableResult
func adjustsImage(highlighted bool: Bool) -> Self {
adjustsImageWhenHighlighted = bool
return self
}
/// adjustsImage
///
/// - Parameter bool: disabled
/// - Returns: self
@discardableResult
func adjustsImage(disabled bool: Bool) -> Self {
adjustsImageWhenDisabled = bool
return self
}
/// showsTouch
///
/// - Parameter bool: highlighted
/// - Returns: self
@discardableResult
func showsTouch(highlighted bool: Bool) -> Self {
showsTouchWhenHighlighted = bool
return self
}
/// tint
///
/// - Parameter color: color
/// - Returns: self
@discardableResult
func tintColor(_ color: UIColor) -> Self {
tintColor = color
return self
}
/// setTitle
///
/// - Parameters:
/// - title: title
/// - state: state
/// - Returns: self
@discardableResult
func setTitle(_ title: String?, state: UIControl.State) -> Self {
setTitle(title, for: state)
return self
}
/// setTitleColor
///
/// - Parameters:
/// - color: color
/// - state: state
/// - Returns: self
@discardableResult
func setTitleColor(_ color: UIColor?, state: UIControl.State) -> Self {
setTitleColor(color, for: state)
return self
}
/// 设置图片
///
/// - Parameters:
/// - image: image
/// - state: state
/// - Returns: self
@discardableResult
func setImage(_ image: UIImage?, state: UIControl.State) -> Self {
setImage(image, for: state)
return self
}
/// 设置背景图片
///
/// - Parameters:
/// - image: image
/// - state: state
/// - Returns: self
@discardableResult
func setBackgroundImage(_ image: UIImage?, state: UIControl.State) -> Self {
setBackgroundImage(image, for: state)
return self
}
/// 设置富文本
///
/// - Parameters:
/// - title: 富文本
/// - state: state
/// - Returns: self
@discardableResult
func setAttributedTitle(_ title: NSAttributedString?, state: UIControl.State) -> Self {
setAttributedTitle(title, for: state)
return self
}
/// addTargetAction
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addActionTouchUpInside(_ handler: @escaping (UIButton) -> Void) -> Self {
self.action(.touchUpInside) { (btn) in
handler(btn)
}
return self
}
}
<file_sep>//
// AlertVC.swift
// Example
//
// Created by senyuhao on 2018/7/12.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
class AlertVC: UITableViewController {
var items = ["alert-normal",
"alert- cancle color",
"alert - button color",
"title - color",
"content - color",
"subtitle"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
normalAlert()
normalAlert()
normalAlert()
normalAlert()
normalAlert()
normalAlert()
normalAlert()
normalAlert()
normalAlert()
normalAlert()
} else if indexPath.row == 1 {
alertButtonColor()
} else if indexPath.row == 2 {
hasHeader()
} else if indexPath.row == 3 {
titleColor()
} else if indexPath.row == 4 {
versionUpgrade()
} else if indexPath.row == 5 {
subTitle()
}
}
private func normalAlert() {
let alert = AlertInfo(title: "123", sure: "知道", content: "123", targetView: view)
Alert.shared.show(info: alert, handler: { tag in
print(tag)
})
}
private func alertButtonColor() {
Alert.shared.cancelColor = #colorLiteral(red: 0.2605174184, green: 0.2605243921, blue: 0.260520637, alpha: 1)
let alert = AlertInfo(title: "123", sure: "知道", content: "123", targetView: view)
Alert.shared.show(info: alert, handler: { tag in
print(tag)
})
}
private func hasHeader() {
Alert.shared.cancelColor = #colorLiteral(red: 0.2605174184, green: 0.2605243921, blue: 0.260520637, alpha: 1)
Alert.shared.sureColor = #colorLiteral(red: 0, green: 0.5254901961, blue: 1, alpha: 1)
let alert = AlertInfo(title: "123", cancel: "取消", sure: "知道", targetView: view)
Alert.shared.show(info: alert, handler: { tag in
print(tag)
})
}
private func titleColor() {
Alert.shared.titleColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
let alert = AlertInfo(title: "123", cancel: "取消", sure: "知道", targetView: view)
Alert.shared.show(info: alert, handler: { tag in
print(tag)
})
}
private func versionUpgrade() {
Alert.shared.contentColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)
let alert = AlertInfo(title: "123", cancel: "取消", sure: "知道", content: "wakakakakkakakak", targetView: view)
Alert.shared.show(info: alert, handler: { tag in
print(tag)
})
}
private func subTitle() {
let string = NSLocalizedString("請回到 香港01首頁>個人中心\n修改個人資料及綁定帳戶", comment: "")
let attributedString = NSMutableAttributedString(string: string, attributes: [.font: UIFont.systemFont(ofSize: 16), .foregroundColor: #colorLiteral(red: 0.1490196078, green: 0.1490196078, blue: 0.1490196078, alpha: 1)])
attributedString.addAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16)], range: NSRange(location: 4, length: 6))
attributedString.addAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16)], range: NSRange(location: 11, length: 4))
let info = AlertInfo(subTitle: attributedString,
sure: NSLocalizedString("確定", comment: ""),
targetView: view)
Alert.shared.show(info: info) { _ in
}
}
}
<file_sep>
//
// UISlider+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UISlider {
@discardableResult
func value(_ value: Float) -> Self {
self.value = value
return self
}
@discardableResult
func minimumValue(_ value: Float) -> Self {
minimumValue = value
return self
}
@discardableResult
func maximumValue(_ value: Float) -> Self {
maximumValue = value
return self
}
@discardableResult
func minimumValueImage(_ image: UIImage?) -> Self {
minimumValueImage = image
return self
}
@discardableResult
func maximumValueImage(_ image: UIImage?) -> Self {
maximumValueImage = image
return self
}
@discardableResult
func isContinuous(_ bool: Bool) -> Self {
isContinuous = bool
return self
}
@discardableResult
func minimumTrackTintColor(_ color: UIColor?) -> Self {
minimumTrackTintColor = color
return self
}
@discardableResult
func maximumTrackTintColor(_ color: UIColor?) -> Self {
maximumTrackTintColor = color
return self
}
@discardableResult
func thumbTintColor(_ color: UIColor?) -> Self {
thumbTintColor = color
return self
}
}
<file_sep>//
// UIView+Chainable.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
// MARK: - UIView
public extension UIKitChainable where Self: UIView {
/// 支持SnapKit- remakeConstraints布局,请在addSubView方法后再调用,否则崩溃
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func remakeConstraints(_ handler: (_ make: ConstraintMaker) -> Void) -> Self {
self.snp.remakeConstraints(handler)
return self
}
/// 支持SnapKit- makeConstraints布局,请在addSubView方法后再调用,否则崩溃
///
/// - Parameter closure: 回调
/// - Returns: self
@discardableResult
func makeConstraints(_ handler: (_ make: ConstraintMaker) -> Void) -> Self {
self.snp.makeConstraints(handler)
return self
}
/// 支持SnapKit- updateConstraints布局,请在addSubView方法后再调用,否则崩溃
///
/// - Parameter closure: 回调
/// - Returns: self
@discardableResult
func updateConstraints(_ handler: (_ make: ConstraintMaker) -> Void) -> Self {
self.snp.updateConstraints(handler)
return self
}
/// 支持SnapKit- removeConstraints布局,请在addSubView方法后再调用,否则崩溃
///
/// - Parameter closure: 回调
/// - Returns: self
@discardableResult
func removeConstraints() -> Self {
self.snp.removeConstraints()
return self
}
/// 显示到的 superview
///
/// - Parameter superview: `父view`
/// - Returns: 返回 self,支持链式调用
@discardableResult func add(to superview: UIView) -> Self {
superview.addSubview(self)
return self
}
/// 添加子View
///
/// - Parameter view: `subView`
/// - Returns: self
@discardableResult
func add(subView view: UIView) -> Self {
self.addSubview(view)
return self
}
/// 移除所有的子视图
///
/// - Returns: self
@discardableResult
func removeAllSubViews() -> Self {
for sub in self.subviews {
sub.remove()
}
return self
}
/// 移除自己
///
/// - Returns: self
@discardableResult
func remove() -> Self {
self.removeFromSuperview()
return self
}
/// 添加单点手势
///
/// - Parameter gestureRecognizer: gestureRecognizer
/// - Returns: self
@discardableResult
func addTapGesture(_ handler: @escaping (Self, UITapGestureRecognizer) -> Void) -> Self {
tap { (view, tap) in
handler(view, tap)
}
return self
}
/// addDoubleTap
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addDoubleGesture(_ handler: @escaping (Self, UITapGestureRecognizer) -> Void) -> Self {
doubleTap { (view, tap) in
handler(view, tap)
}
return self
}
/// 添加长按手势
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addLongGesture(_ handler: @escaping (Self, UILongPressGestureRecognizer) -> Void) -> Self {
longPress { (view, tap) in
handler(view, tap)
}
return self
}
/// 移除手势
///
/// - Parameter gestureRecognizer: gestureRecognizer
/// - Returns: self
@discardableResult
func removeGesture(_ gestureRecognizer: UIGestureRecognizer) -> Self {
removeGestureRecognizer(gestureRecognizer)
return self
}
/// 坐标绝对定位的方式布局,设置 frame 时必须设置好自适应
///
/// frame 应始终以 superview 的 bounds 为参考,不能跨级,更不能使用 UIScreen 的 size
/// - Parameters:
/// - frame: frame位置
/// - autoresizing: 自适应方式
/// - Returns: 返回 self,支持链式调用
@discardableResult
func layout(_ frame: CGRect, _ autoresizing: UIView.AutoresizingMask) -> Self {
self.frame = frame
autoresizingMask = autoresizing
return self
}
/// 设置frame
///
/// - Parameter frame: frame
/// - Returns: self
@discardableResult
func frame(_ frame: CGRect) -> Self {
self.frame = frame
return self
}
/// 显示边框:设置颜色和宽度
///
/// - Parameters:
/// - color: 边框颜色
/// - width: 边框宽度,默认为 1.0
/// - Returns: 返回 self,支持链式调用
@discardableResult
func border(_ color: UIColor, _ width: CGFloat = 1.0) -> Self {
layer.borderColor = color.cgColor
layer.borderWidth = width
return self
}
/// 设置圆角 `layer.cornerRadius`
///
/// - Parameter radius: 圆角半径
/// - Returns: 返回 self,支持链式调用
@discardableResult
func corner(_ radius: CGFloat) -> Self {
layer.cornerRadius = radius
layer.masksToBounds = true
clipsToBounds = true
return self
}
/// 设置背景色 `backgroundColor`
///
/// - Parameter color: 背景色
/// - Returns: 返回 self,支持链式调用
@discardableResult
func backgroundColor(_ color: UIColor) -> Self {
backgroundColor = color
return self
}
/// 设置透明度 `alpha`
///
/// - Parameter alpha: 透明度,0.0 为全透明,1.0为不透明
/// - Returns: 返回 self,支持链式调用
@discardableResult
func alpha(_ alpha: CGFloat) -> Self {
self.alpha = alpha
return self
}
/// 设置内容显示模式 `contentMode`
///
/// - Parameter mode: 显示模式
/// - Returns: 返回 self,支持链式调用
@discardableResult
func contentMode(_ mode: UIView.ContentMode) -> Self {
contentMode = mode
return self
}
/// 是否允许交互
///
/// - Parameter enabled: enabled
/// - Returns: self
@discardableResult
func isUserInteractionEnabled(_ enabled: Bool) -> Self {
isUserInteractionEnabled = enabled
return self
}
/// tag
///
/// - Parameter tag: tag
/// - Returns: self
@discardableResult
func tag(_ tag: Int) -> Self {
self.tag = tag
return self
}
/// semanticContentAttribute
///
/// - Parameter contentAttribute: contentAttribute
/// - Returns: self
@discardableResult
func semanticContentAttribute(_ contentAttribute: UISemanticContentAttribute) -> Self {
semanticContentAttribute = contentAttribute
return self
}
/// bounds
///
/// - Parameter bounds: bounds
/// - Returns: self
@discardableResult
func bounds(_ bounds: CGRect) -> Self {
self.bounds = bounds
return self
}
/// center
///
/// - Parameter center: center
/// - Returns: self
@discardableResult
func center(_ center: CGPoint) -> Self {
self.center = center
return self
}
/// transform
///
/// - Parameter form: transform
/// - Returns: self
@discardableResult
func transform(_ form: CGAffineTransform) -> Self {
transform = form
return self
}
/// contentScaleFactor
///
/// - Parameter factor: factor
/// - Returns: self
@discardableResult
func contentScaleFactor(_ factor: CGFloat) -> Self {
contentScaleFactor = factor
return self
}
/// isMultipleTouchEnabled
///
/// - Parameter enabled: enabled
/// - Returns: self
@discardableResult
func isMultipleTouchEnabled(_ enabled: Bool) -> Self {
isUserInteractionEnabled = enabled
return self
}
/// discardableResult
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func isExclusiveTouch(_ bool: Bool) -> Self {
isExclusiveTouch = bool
return self
}
/// autoresizesSubviews
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func autoresizesSubviews(_ bool: Bool) -> Self {
autoresizesSubviews = bool
return self
}
/// autoresizingMask
///
/// - Parameter mask: mask
/// - Returns: self
@discardableResult
func autoresizingMask(_ mask: UIView.AutoresizingMask) -> Self {
autoresizingMask = mask
return self
}
/// sizeToFit
///
/// - Parameter _:
/// - Returns: self
@discardableResult func sizeFit() -> Self {
self.sizeToFit()
return self
}
/// insert
///
/// - Parameters:
/// - view: subView
/// - index: index
/// - Returns: self
@discardableResult
func insert(subview view: UIView, at index: Int) -> Self {
insertSubview(view, at: index)
return self
}
/// 交换subView的位置
///
/// - Parameters:
/// - index1: 下标1
/// - index2: 下标2
/// - Returns: self
@discardableResult
func exchange(at index1: Int, to index2: Int) -> Self {
exchangeSubview(at: index1, withSubviewAt: index2)
return self
}
/// inset 将当前子view插在另外一个子view的下面
///
/// - Parameters:
/// - view: subView
/// - siblingSubview: siblingSubview
/// - Returns: self
@discardableResult
func insert(subview view: UIView, belowSubview siblingSubview: UIView) -> Self {
insertSubview(view, belowSubview: siblingSubview)
return self
}
/// inset 将当前子view插在另外一个子view的上面
///
/// - Parameters:
/// - view: subView
/// - siblingSubview: siblingSubview
/// - Returns: self
@discardableResult
func insert(subview view: UIView, aboveSubview siblingSubview: UIView) -> Self {
insertSubview(view, aboveSubview: siblingSubview)
return self
}
/// 将子view显示在最前面
///
/// - Parameter view: 子view
/// - Returns: self
@discardableResult
func bring(subviewToFront view: UIView) -> Self {
bringSubviewToFront(view)
return self
}
/// 将子view显示在最下面
///
/// - Parameter view: 子view
/// - Returns: self
@discardableResult
func send(subviewToBack view: UIView) -> Self {
sendSubviewToBack(view)
return self
}
/// layoutMargins
///
/// - Parameter margins: margins
/// - Returns: self
@discardableResult
func layoutMargins(_ margins: UIEdgeInsets) -> Self {
layoutMargins = margins
return self
}
/// directionalLayoutMargins
///
/// - Parameter edgeInsets: edgeInsets
/// - Returns: self
@available(iOS 11.0, *)
@discardableResult
func directionalLayoutMargins(_ edgeInsets: NSDirectionalEdgeInsets) -> Self {
directionalLayoutMargins = edgeInsets
return self
}
/// preservesSuperviewLayoutMargins
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func preservesSuperviewLayoutMargins(_ bool: Bool) -> Self {
preservesSuperviewLayoutMargins = bool
return self
}
/// insetsLayoutMarginsFromSafeArea
///
/// - Parameter bool: bool
/// - Returns: self
@available(iOS 11.0, *)
@discardableResult
func insetsLayoutMarginsFromSafeArea(_ bool: Bool) -> Self {
insetsLayoutMarginsFromSafeArea = bool
return self
}
}
<file_sep>//
// ScrollViewVC.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class ScrollViewVC: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let w = UIScreen.main.bounds.width
let lab1 = UILabel()
.frame(CGRect(x: 0, y: 0, width: w, height: 200))
.backgroundColor(UIColor.red)
.text("第一个")
.font(18)
.textAlignment(.center)
.textColor(UIColor.black)
let lab2 = UILabel()
.frame(CGRect(x: w, y: 0, width: w, height: 200))
.backgroundColor(UIColor.blue)
.text("第二个")
.font(18)
.textAlignment(.center)
.textColor(UIColor.black)
let lab3 = UILabel()
.frame(CGRect(x: w * 2, y: 0, width: w, height: 200))
.backgroundColor(UIColor.yellow)
.text("第三个")
.font(18)
.textAlignment(.center)
.textColor(UIColor.black)
//支持所有代理回调
scrollView.frame(CGRect(x: 0, y: 100, width: w, height: 200))
.backgroundColor(UIColor.green)
.isPagingEnabled(true)
.bounces(true)
.add(subView: lab1)
.add(subView: lab2)
.add(subView: lab3)
.contentSize(CGSize(width: w * 3, height: 200))
.add(to: view)
.addScrollViewDidScrollBlock { (scroll) in
print(scroll.contentOffset)
}
}
deinit {
print(self)
}
}
<file_sep>//
// UITextField+Blocks.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/8.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UITextField {
fileprivate struct TextFieldKey {
static var UITextFieldShouldBeginEditingShakeKey = "UITextFieldShouldBeginEditingShakeKey"
static var UITextFieldShouldBeginEditingKey = "UITextFieldShouldBeginEditingKey"
static var UITextFieldShouldEndEditingKey = "UITextFieldShouldEndEditingKey"
static var UITextFieldDidBeginEditingKey = "UITextFieldDidBeginEditingKey"
static var UITextFieldDidEndEditingKey = "UITextFieldDidEndEditingKey"
static var UITextFieldShouldChangeCharactersInRangeKey = "UITextFieldShouldChangeCharactersInRangeKey"
static var UITextFieldShouldClearKey = "UITextFieldShouldClearKey"
static var UITextFieldShouldReturnKey = "UITextFieldShouldReturnKey"
}
fileprivate var shouldBegindEditingBlock: ((UITextField)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldShouldBeginEditingKey) as? ((UITextField) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldShouldBeginEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldEndEditingBlock: ((UITextField)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldShouldEndEditingKey) as? ((UITextField) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldShouldEndEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didBeginEditingBlock: ((UITextField)->())? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldDidBeginEditingKey) as? ((UITextField) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldDidBeginEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didEndEditingBlock: ((UITextField)->())? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldDidEndEditingKey) as? ((UITextField) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldDidEndEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldChangeCharactersInRangeBlock: ((UITextField, NSRange, String)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldShouldChangeCharactersInRangeKey) as? ((UITextField, NSRange, String) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldShouldChangeCharactersInRangeKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldReturnBlock: ((UITextField)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldShouldReturnKey) as? ((UITextField) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldShouldReturnKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldClearBlock: ((UITextField)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldShouldClearKey) as? ((UITextField) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldShouldClearKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate func setDelegate() {
if delegate == nil || delegate?.isEqual(self) == false {
delegate = self
}
}
}
// MARK: - Public Method
extension UITextField {
/// 当输入框进入编辑的是否需要震动动画
public var shouldBegindEditingShake: Bool? {
get {
return objc_getAssociatedObject(self, &TextFieldKey.UITextFieldShouldBeginEditingShakeKey) as? Bool
}
set(value) {
objc_setAssociatedObject(self, &TextFieldKey.UITextFieldShouldBeginEditingShakeKey, value, .OBJC_ASSOCIATION_COPY);
}
}
public func setShouldBegindEditingBlock(_ handler: @escaping((UITextField)->(Bool))) {
shouldBegindEditingBlock = handler
}
public func setShouldEndEditingBlock(_ handler: @escaping((UITextField)->(Bool))) {
shouldEndEditingBlock = handler
}
public func setDidBeginEditingBlock(_ handler: @escaping((UITextField)->())) {
didBeginEditingBlock = handler
}
public func setDidEndEditingBlock(_ handler: @escaping((UITextField)->())) {
didEndEditingBlock = handler
}
public func setShouldChangeCharactersInRangeBlock(_ handler: @escaping((UITextField, NSRange, String)->(Bool))) {
shouldChangeCharactersInRangeBlock = handler
}
public func setShouldReturnBlock(_ handler: @escaping((UITextField)->(Bool))) {
shouldReturnBlock = handler
}
public func setShouldClearBlock(_ handler: @escaping((UITextField)->(Bool))) {
shouldClearBlock = handler
}
}
// MARK: - UITextFieldDelegate
extension UITextField: UITextFieldDelegate {
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
var res: Bool = true
if shouldBegindEditingShake != nil && shouldBegindEditingShake == true {
self.shake()
}
if let block = shouldBegindEditingBlock {
res = block(textField)
}
// if let delegate = chainalbeDelegate,
// let value = delegate.textFieldShouldBeginEditing?(textField) {
// res = value
// }
return res
}
public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
var res: Bool = true
if let block = shouldEndEditingBlock {
res = block(textField)
}
// if let delegate = chainalbeDelegate,
// let value = delegate.textFieldShouldEndEditing?(textField) {
// res = value
// }
return res
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
didBeginEditingBlock?(textField)
// if let delegate = chainalbeDelegate {
// delegate.textFieldDidBeginEditing?(textField)
// }
}
public func textFieldDidEndEditing(_ textField: UITextField) {
didEndEditingBlock?(textField)
// if let delegate = chainalbeDelegate {
// delegate.textFieldDidEndEditing?(textField)
// }
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var res: Bool = true
if let block = shouldChangeCharactersInRangeBlock {
res = block(textField, range, string)
}
// if let delegate = chainalbeDelegate,
// let value = delegate.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) {
// res = value
// }
return res
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
var res: Bool = true
if let block = shouldReturnBlock {
res = block(textField)
}
// if let delegate = chainalbeDelegate,
// let value = delegate.textFieldShouldReturn?(textField) {
// res = value
// }
return res
}
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
var res: Bool = true
if let block = shouldClearBlock {
res = block(textField)
}
// if let delegate = chainalbeDelegate,
// let value = delegate.textFieldShouldClear?(textField) {
// res = value
// }
return res
}
}
<file_sep>//
// NotificationCenter+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
fileprivate let NotificationCenterChainableDisposebag = DisposeBag()
public extension Chainable where Self: NSObject {
/// 给当前对象添加快捷通知方法
///
/// - Parameters:
/// - name: name
/// - object: object
/// - handler: handler
/// - Returns: self
@discardableResult
public func addNotifiObserver(name: String, object: Any? = nil, handler: @escaping (Notification) -> Void) -> Self {
NotificationCenter.default
.rx.notification(NSNotification.Name.init(name))
.takeUntil(self.rx.deallocated) //页面销毁自动移除通知监听
.subscribe(onNext: { (notification) in
handler(notification)
})
.disposed(by: NotificationCenterChainableDisposebag)
return self
}
/// 给当前对象添加快捷发送通知
///
/// - Parameters:
/// - name: name
/// - object: object
/// - userInfo: userInfo
/// - Returns: self
@discardableResult
public func postNotification(name: String, object: Any? = nil, userInfo: [AnyHashable : Any]? = nil) -> Self {
NotificationCenter.default.post(name: NSNotification.Name.init(name), object: object, userInfo: userInfo)
return self
}
}
<file_sep>//
// ViewController.swift
// MagicTextFieldDemo
//
// Created by USER on 2018/12/7.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let accountInput = MagicTextField()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func setupUI() {
accountInput.placeholder = "請輸入手機號碼"
accountInput.animatedText = "手机号码"
accountInput.font = UIFont.systemFont(ofSize: 14)
accountInput.animatedFont = UIFont.systemFont(ofSize: 12)
accountInput.textAlignment = .left
accountInput.marginLeft = 10
accountInput.placeholderColor = UIColor.red
accountInput.animatedPlaceholderColor = UIColor.blue
accountInput.moveDistance = 30
accountInput.borderStyle = .line
accountInput.frame = CGRect(x: 100, y: 100, width: 200, height: 30)
view.addSubview(accountInput)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
<file_sep>//
// ViewController.swift
// DDRouterDemo
//
// Created by USER on 2018/12/4.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import DDKit
import TestSDK
struct Model {
var name: String = "liming"
var old: Int = 18
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
//定义的路由 key
// MARK: --- "BViewController"等,必须为对应的控制器名字
@IBAction func pushBAction(_ sender: Any) {
let model = Model()
pushViewController("BViewController", params: ["model": model,"title": "hello"], animated: true) { (res) in
//上级界面回调
print(res)
}
}
@IBAction func presentBAction(_ sender: Any) {
presentViewController("BViewController", params: nil, animated: true) { (res) in
print(res)
}
}
// MARK: --- 模块之间通信,后续会出方法
//本路由只适合用项目间控制器中的跳转和传值
@IBAction func pushTestSDKAction(_ sender: Any) {
//若为SDK中的控制器,前面必须加命名空间
pushViewController("TestSDK.TestViewController", params: nil, animated: true, complete: nil)
}
@IBAction func pushPosAction(_ sender: Any) {
//若为Pods中的控制器,前面必须加命名空间
pushViewController("DDKit.DDScanViewController", params: nil, animated: true, complete: nil)
}
/// 跳转Storybord控制器
///
@IBAction func pushOrderAction(_ sender: Any) {
pushSBViewController("Main", identifier: "OrderViewController", params: ["name": "lisi"])
// presentSBViewController("Main", identifier: "OrderViewController")
}
}
<file_sep>//
// UITextField+LengthLimit.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/8.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
import RxCocoa
import RxSwift
fileprivate let UITextFieldDisposebag = DisposeBag()
extension UITextField {
fileprivate struct TextFieldMaxLengthKey {
static var kTextFieldMaxLengthKey = "kUITextFieldMaxLengthKey"
}
public var maxLength: Int {
get {
return (objc_getAssociatedObject(self, &TextFieldMaxLengthKey.kTextFieldMaxLengthKey) as? Int) ?? LONG_MAX
}
set(value) {
var newValue = value
if newValue < 1 {
newValue = LONG_MAX
}
objc_setAssociatedObject(self, &TextFieldMaxLengthKey.kTextFieldMaxLengthKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//
// self.rx.controlEvent(.editingChanged)
// .asObservable()
// .subscribe(onNext: { [weak self] in
// self?.textFieldTextChanged()
// })
// .disposed(by: UITextFieldDisposebag)
self.rx.text.orEmpty
.map {[weak self] (text) -> Bool in
return text.count > self?.maxLength ?? Int.max
}
.share(replay: 1)
.subscribe(onNext: {[weak self] (res) in
if res == true,
let strongSelf = self,
let text = self?.text {
let index = text.index(text.startIndex, offsetBy: strongSelf.maxLength)
self?.text = String(text[..<index])
}
})
.disposed(by: UITextFieldDisposebag)
}
}
// fileprivate func textFieldTextChanged() {
// let toBeString = self.text as NSString?
// guard let textStr = toBeString else {
// return
// }
// if textStr.length == 0 {
// return
// }
//
// //获取高亮方法
// let selectedRange = self.markedTextRange ?? UITextRange()
// let position = self.position(from: selectedRange.start, offset: 0)
//
// // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
// if position != nil {
// return
// }
// if (textStr.length ) > self.maxLength {
// let rangeIndex = textStr.rangeOfComposedCharacterSequence(at: self.maxLength)
// if rangeIndex.length == 1 {
// self.text = textStr.substring(to: self.maxLength)
// } else {
// let range = textStr.rangeOfComposedCharacterSequences(for: NSRange(location: 0, length: self.maxLength))
// self.text = textStr.substring(with: range)
// }
// }
// }
}
<file_sep>//
// CityListHotCell.swift
// PlacePickerDemo
//
// Created by weiwei.li on 2019/1/3.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class CityListHotCell: UITableViewCell {
private let containerView = UIView()
private let flowLayout = UICollectionViewFlowLayout()
private var indexPath: IndexPath?
private var viewModel: CityListViewModel?
private lazy var collectionView: UICollectionView = { [weak self] in
flowLayout.scrollDirection = .vertical
// collectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
collectionView.backgroundColor = UIColor.white
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.isScrollEnabled = false
collectionView.backgroundColor = UIColor(red: 245.0/255.0, green: 245.0/255.0, blue: 245.0/255.0, alpha: 1)
collectionView.delegate = self
collectionView.dataSource = self
// 设置 cell
collectionView.register(CityHotCollectionCell.self, forCellWithReuseIdentifier: "CityHotCollectionCell")
return collectionView
}()
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
containerView.frame = CGRect(x: 18, y: 0, width: bounds.width - 18*2, height: bounds.height)
let width: CGFloat = containerView.frame.width
let padding: CGFloat = 10
let cellW: CGFloat = (width - 2 * padding) / 3.0
let cellH: CGFloat = 40.0
flowLayout.itemSize = CGSize(width: cellW, height: cellH)
flowLayout.minimumLineSpacing = padding
flowLayout.minimumInteritemSpacing = padding
collectionView.frame = containerView.bounds
collectionView.reloadData()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(containerView)
containerView.addSubview(collectionView)
backgroundColor = UIColor(red: 245.0/255.0, green: 245.0/255.0, blue: 245.0/255.0, alpha: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CityListHotCell : UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let indexPath = indexPath {
if indexPath.section == 0 {
return 1
}
if indexPath.section == 1 {
return viewModel?.hotCitys?.count ?? 0
}
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CityHotCollectionCell", for: indexPath) as? CityHotCollectionCell else {
return UICollectionViewCell()
}
if self.indexPath?.section == 0 {
cell.textLab.text = viewModel?.currentCity
} else {
cell.textLab.text = viewModel?.hotCitys?[indexPath.row]
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//当前城市
if self.indexPath?.section == 0 {
NotificationCenter.default.post(name: NSNotification.Name.init("kSelectedCityNameKey"), object: nil, userInfo: ["city": viewModel?.currentCity ?? ""])
return
}
//热门城市
if self.indexPath?.section == 1 {
let city = viewModel?.hotCitys?[indexPath.row]
NotificationCenter.default.post(name: NSNotification.Name.init("kSelectedCityNameKey"), object: nil, userInfo: ["city": city ?? ""])
return
}
}
}
extension CityListHotCell: ViewModelProtocol {
func bindViewModel(model: CityListViewModel, indexPath: IndexPath) {
self.indexPath = indexPath
viewModel = model
collectionView.reloadData()
}
}
<file_sep>//
// DDCustomCameraManager.swift
// DDCustomCamera
//
// Created by USER on 2018/11/15.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
//选择拍摄尺寸
public enum DDCaptureSessionPreset: Int {
case preset325x288
case preset640x480
case preset960x540
case preset1280x720
case preset1920x1080
case preset3840x2160
}
/// 导出视屏类型
///
/// - mov: mov
/// - mp4: mp4
public enum DDExportVideoType: Int {
case mov
case mp4
}
/// 水印位置,目前还不支持
///
/// - topLeft: 上左
/// - topRight: 上右
/// - center: 中间
/// - bottomLeft: 下左
/// - bottomRight: 下右
public enum DDWatermarkLocation:Int {
case topLeft
case topRight
case center
case bottomLeft
case bottomRight
}
public class DDCustomCameraManager: NSObject {
///完成回调
var completionBack: (([DDCustomCameraResult]?)->())?
//当前对象是否是从DDPhotoPicke present呈现,外界调用请勿修改此参数
var isFromDDPhotoPickerPresent: Bool = false
}
// MARK: - 类方法入口
extension DDCustomCameraManager {
public static func show(finishedHandler:@escaping ([DDCustomCameraResult]?)->()) {
let manager = DDCustomCameraManager()
manager.completionBack = finishedHandler
manager.presentCameraController()
}
}
extension DDCustomCameraManager {
public func presentCameraController() {
//先授权相册
DDCustomCameraManager.authorizePhoto { (res) in
if res == false {
DDPhotoPickerManager.showAlert(DDPhotoStyleConfig.shared.photoPermission)
return
}
//再授权相机
DDCustomCameraManager.authorizeCamera {(res) in
if res == false {
DDPhotoPickerManager.showAlert(DDPhotoStyleConfig.shared.cameraPermission)
return
}
//最后授权麦克风
if DDPhotoStyleConfig.shared.isEnableRecordVideo == true {
DDCustomCameraManager.authorizeMicrophone { (res) in
if res == false {
DDPhotoPickerManager.showAlert(DDPhotoStyleConfig.shared.microphonePermission)
return
}
//类方法不会循环引用,不能设为weak,否则self为空
self.showCamera()
}
} else {
//类方法不会循环引用,不能设为weak,否则self为空
self.showCamera()
}
}
}
}
private func showCamera() {
let vc = getTopViewController
let controller = DDCustomCameraController()
controller.isEnableRecordVideo = DDPhotoStyleConfig.shared.isEnableRecordVideo
controller.isEnableTakePhoto = DDPhotoStyleConfig.shared.isEnableTakePhoto
controller.circleProgressColor = DDPhotoStyleConfig.shared.circleProgressColor
controller.sessionPreset = DDPhotoStyleConfig.shared.sessionPreset
controller.maxRecordDuration = DDPhotoStyleConfig.shared.maxRecordDuration
controller.isShowClipperView = DDPhotoStyleConfig.shared.isShowClipperView
controller.isFromDDPhotoPickerPresent = isFromDDPhotoPickerPresent
controller.photoAssetType = DDPhotoStyleConfig.shared.photoAssetType
if DDPhotoStyleConfig.shared.isShowClipperView == true {
controller.isEnableRecordVideo = false
}
controller.clipperSize = DDPhotoStyleConfig.shared.clipperSize
//为何不使用[weak self],防止当前对象运行完没释放,两者之间无循环引用,不互相持有
controller.doneBlock = {(image, url) in
self.save(image, url: url)
}
//[DDPhotoGridCellModel]?
controller.selectedAlbumBlock = {[weak self] arr in
let result = arr?.map({ (model) -> DDCustomCameraResult in
let res = model.asset.mediaType == .video ? true : false
return DDCustomCameraResult(asset: model.asset, isVideo: res, image: model.image, duration: model.duration, albumArrs: nil)
})
self?.completionBack?(result)
}
vc?.present(controller, animated: true, completion: nil)
}
}
extension DDCustomCameraManager {
static func getVideoExportFilePath(_ type: DDExportVideoType? = .mp4) -> String {
let format = (type == .mp4) ? "mp4" : "mov"
return NSTemporaryDirectory() + getUniqueStrByUUID() + "." + format
}
static func getUniqueStrByUUID() -> String {
let uuidObj = CFUUIDCreate(nil)
let uuidString = CFUUIDCreateString(nil, uuidObj)
return (uuidString as String?) ?? "\(Date.init(timeIntervalSinceNow: 100))"
}
// MARK: - ---获取相册权限
static func authorizePhoto(_ comletion:@escaping (Bool) -> Void) {
let granted = PHPhotoLibrary.authorizationStatus()
switch granted {
case PHAuthorizationStatus.authorized:
comletion(true)
case PHAuthorizationStatus.denied, PHAuthorizationStatus.restricted:
comletion(false)
case PHAuthorizationStatus.notDetermined:
PHPhotoLibrary.requestAuthorization({ (status) in
DispatchQueue.main.async {
comletion(status == .authorized ? true:false)
}
})
}
}
// MARK: - --相机权限
static func authorizeCamera(_ comletion: @escaping (Bool) -> Void ) {
let granted = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch granted {
case AVAuthorizationStatus.authorized:
comletion(true)
case AVAuthorizationStatus.denied:
comletion(false)
case AVAuthorizationStatus.restricted:
comletion(false)
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) in
DispatchQueue.main.async {
if granted {
comletion(granted)
}
}
})
}
}
// MARK: - --麦克风授权
static func authorizeMicrophone(_ comletion: @escaping (Bool) -> Void ) {
let granted = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
switch granted {
case AVAuthorizationStatus.authorized:
comletion(true)
case AVAuthorizationStatus.denied:
comletion(false)
case AVAuthorizationStatus.restricted:
comletion(false)
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.audio, completionHandler: { (granted: Bool) in
DispatchQueue.main.async {
if granted {
comletion(granted)
}
}
})
}
}
}
private extension DDCustomCameraManager {
/// 存储图片和视屏
///
/// - Parameters:
/// - image: 图片
/// - url: 视屏url
func save(_ image: UIImage?, url: URL?) {
if let image = image {
saveImageToAlbum(image) {[weak self] (success, asset) in
if success == true {
DispatchQueue.main.async(execute: {
if let back = self?.completionBack {
let model = DDCustomCameraResult.init(asset: asset, isVideo: false, image: image, duration: "",albumArrs: nil)
var arr: [DDCustomCameraResult] = [DDCustomCameraResult]()
arr.append(model)
back(arr)
}
})
}
}
return
}
if let url = url {
saveVideoToAlbum(url) {[weak self] (success, asset) in
if success == true {
//视屏就获取首张图片
_ = DDCustomCameraManager.requestImageForAsset(for: asset, targetSize: DDPhotoStyleConfig.shared.thumbnailSize, resultHandler: { (image, dic) in
DispatchQueue.main.async(execute: {
if let back = self?.completionBack {
let model = DDCustomCameraResult.init(asset: asset, isVideo: true, image: image, duration: self?.getDuration(asset))
var arr: [DDCustomCameraResult] = [DDCustomCameraResult]()
arr.append(model)
back(arr)
}
})
})
}
}
}
}
/// 获取视屏时长
///
/// - Parameter asset: asset
/// - Returns: 时长
func getDuration(_ asset: PHAsset?) -> String? {
var duration: Int = 0
if asset?.mediaType == .video {
duration = Int(asset?.duration ?? 0)
}
if duration < 60 {
return String(format: "00:%02ld", arguments: [duration])
} else if duration < 3600 {
let m = duration / 60
let s = duration % 60
return String(format: "%02ld:%02ld", arguments: [m, s])
} else {
let h = duration / 3600
let m = (duration % 3600) / 60
let s = duration % 60
return String(format: "%02ld:%02ld:%02ld", arguments: [h, m, s])
}
}
/// 保存视屏到相册
///
/// - Parameters:
/// - url: url
/// - completion: 回调
func saveVideoToAlbum(_ url: URL, completion:@escaping (Bool, PHAsset?)->()) {
let status = PHPhotoLibrary.authorizationStatus()
if status == .denied {
completion(false, nil)
return
}
if status == .restricted {
completion(false, nil)
return
}
var placeholderAsset: PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
let newAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
placeholderAsset = newAssetRequest?.placeholderForCreatedAsset
}) {[weak self] (success, err) in
if success == false {
completion(false, nil)
return
}
guard let asset = self?.getAssetFromlocalIdentifier(placeholderAsset?.localIdentifier),
let desCollection = self?.getDestinationCollection() else {
completion(false, nil)
return
}
PHPhotoLibrary.shared().performChanges({
_ = PHAssetCollectionChangeRequest(for: desCollection, assets: PHAsset.fetchAssets(withLocalIdentifiers: [asset.localIdentifier], options: nil))
}, completionHandler: { (success, err) in
completion(success,asset)
})
}
}
/// 保存图片到相册
///
/// - Parameters:
/// - image: image
/// - completion: 回调
func saveImageToAlbum(_ image: UIImage, completion:@escaping (Bool, PHAsset?)->()) {
let status = PHPhotoLibrary.authorizationStatus()
if status == .denied {
completion(false, nil)
return
}
if status == .restricted {
completion(false, nil)
return
}
var placeholderAsset: PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
let newAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
placeholderAsset = newAssetRequest.placeholderForCreatedAsset
}) {[weak self] (success, err) in
if success == false {
completion(false, nil)
return
}
guard let asset = self?.getAssetFromlocalIdentifier(placeholderAsset?.localIdentifier),
let desCollection = self?.getDestinationCollection() else {
completion(false, nil)
return
}
PHPhotoLibrary.shared().performChanges({
_ = PHAssetCollectionChangeRequest(for: desCollection, assets: PHAsset.fetchAssets(withLocalIdentifiers: [asset.localIdentifier], options: nil))
}, completionHandler: { (success, err) in
completion(success,asset)
})
}
}
/// 获取自定义相册
///
/// - Returns: 自定义相册
func getDestinationCollection() -> PHAssetCollection? {
//是否存在自定义相册
let collectionResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
for number in 0..<collectionResult.count {
let collection: PHAssetCollection = collectionResult[number]
if collection.localizedTitle == getAppName() {
return collection
}
}
//新建自定义相册
var collectionId: String?
try? PHPhotoLibrary.shared().performChangesAndWait {[weak self] in
collectionId = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: self?.getAppName() ?? "DD01").placeholderForCreatedAssetCollection.localIdentifier
}
if let id = collectionId {
return PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [id], options: nil).lastObject
}
return nil
}
/// 获取当前app的名字
///
/// - Returns: 名字
func getAppName() -> String {
var dic = (Bundle.main.localizedInfoDictionary != nil) ? Bundle.main.localizedInfoDictionary : Bundle.main.infoDictionary
let name = (dic?["CFBundleDisplayName"] != nil) ? dic?["CFBundleDisplayName"] : dic?["CFBundleName"]
return (name as? String) ?? "DD01"
}
/// 获取PHAsset
///
/// - Parameter localIdentifier: localIdentifier descriptio
/// - Returns: PHAsset
func getAssetFromlocalIdentifier(_ localIdentifier: String?) -> PHAsset? {
guard let localIdentifier = localIdentifier else {
return nil
}
let result = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: nil)
if result.count > 0 {
return result.firstObject
}
return nil
}
/// 显示无授权信息
///
/// - Parameter text: 标题
func showAlertNoAuthority(_ text: String?) {
//弹窗提示
let alertVC = UIAlertController(title: "提示", message: text, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .default) { (action) in
}
let actionCommit = UIAlertAction(title: "去设置", style: .default) { (action) in
//去设置
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
alertVC.addAction(cancelAction)
alertVC.addAction(actionCommit)
getTopViewController?.present(alertVC, animated: true, completion: nil)
}
/// 是否有相机授权权限
///
/// - Returns: bool
func isHaveCameraAuthority() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: .video)
if status == .restricted || status == .denied {
return false
}
return true
}
/// 是否有相册访问权限
///
/// - Returns: bool
func isHavePhotoLibraryAuthority() -> Bool {
let status = PHPhotoLibrary.authorizationStatus()
if status == .authorized {
return true
}
return false
}
func isHavaMicrophoneAuthority() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: .audio)
if status == .restricted || status == .denied {
return false
}
return true
}
/// 获取当前app最上层vc
///
/// - Returns: controller
var getTopViewController: UIViewController? {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
return getTopViewController(viewController: rootViewController)
}
func getTopViewController(viewController: UIViewController?) -> UIViewController? {
if let presentedViewController = viewController?.presentedViewController {
return getTopViewController(viewController: presentedViewController)
}
if let tabBarController = viewController as? UITabBarController,
let selectViewController = tabBarController.selectedViewController {
return getTopViewController(viewController: selectViewController)
}
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return getTopViewController(viewController: visibleViewController)
}
if let pageViewController = viewController as? UIPageViewController,
pageViewController.viewControllers?.count == 1 {
return getTopViewController(viewController: pageViewController.viewControllers?.first)
}
for subView in viewController?.view.subviews ?? [] {
if let childViewController = subView.next as? UIViewController {
return getTopViewController(viewController: childViewController)
}
}
return viewController
}
}
extension DDCustomCameraManager {
/// 获取图片
///
/// - Parameters:
/// - asset: asset
/// - targetSize: 获取图片的size(用于展示实际所需大小)
/// - resultHandler: 回调
/// - Returns: id
static public func requestImageForAsset(for asset: PHAsset?, targetSize: CGSize, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
let option = PHImageRequestOptions()
// PHImageRequestOptions是否有效
option.isSynchronous = true
// 缩略图的压缩模式设置为无
/**
resizeMode:对请求的图像怎样缩放。有三种选择:None,默认加载方式;Fast,尽快地提供接近或稍微大于要求的尺寸;Exact,精准提供要求的尺寸。
deliveryMode:图像质量。有三种值:Opportunistic,在速度与质量中均衡;HighQualityFormat,不管花费多长时间,提供高质量图像;FastFormat,以最快速度提供好的质量。
这个属性只有在 synchronous 为 true 时有效。
*/
option.resizeMode = .none
// 缩略图的质量为快速
option.deliveryMode = .fastFormat
//必要时从icould下载
option.isNetworkAccessAllowed = true;
return PHCachingImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: option, resultHandler: { (image, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let image = image {
resultHandler(image,dictionry)
}
})
}
/// 获取原始图片的data(用于上传)
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestOriginalImageDataForAsset(for asset: PHAsset?, resultHandler: @escaping (Data?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
let option = PHImageRequestOptions()
option.resizeMode = .exact
option.isNetworkAccessAllowed = true
option.isSynchronous = true
return PHCachingImageManager.default().requestImageData(for: asset, options: option, resultHandler: { (data, uti, orientation, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let photoData = data {
resultHandler(photoData,dictionry)
}
})
}
/// 获取相册视屏播放的item
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestVideoForAsset(for asset: PHAsset?, resultHandler: @escaping (AVPlayerItem?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
return PHCachingImageManager.default().requestPlayerItem(forVideo: asset, options: nil, resultHandler: { (item, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let item = item {
resultHandler(item,dictionry)
}
})
}
/// 获取视屏的avasset
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestAVAssetForAsset(for asset: PHAsset?, resultHandler: @escaping (AVAsset?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
return PHCachingImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (avAsset, mix, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let avAsset = avAsset {
resultHandler(avAsset,dictionry)
}
})
}
/// 导出视屏上传临时存储的filepath
///
/// - Parameters:
/// - asset: asset
/// - type: 导出格式
/// - presetName: 压缩格式 ,常见的为以下三种
//AVAssetExportPresetLowQuality
//AVAssetExportPresetMediumQuality
//AVAssetExportPresetHighestQuality
/// - compelete: 完成回调
static public func exportVideoFilePath(for asset: PHAsset?, type: DDExportVideoType, presetName: String, compelete:((String?, NSError?)->())?) {
self.export(for: asset, type: type, presetName: presetName, complete: compelete)
}
/// 清除沙盒路径下视屏文件
///
/// - Parameter path: 沙盒路径 , 默认是u存储在tmp目录下
static public func cleanMoviesFile(_ path: String? = NSTemporaryDirectory()) {
guard let path = path else {
return
}
let manager = FileManager.default
let subPathArr = try? manager.contentsOfDirectory(atPath: path)
guard let pahtArr = subPathArr else {
return
}
for subPath in pahtArr {
let filePath = path + subPath
print(filePath)
//删除子文件夹
try? manager.removeItem(atPath: filePath)
}
}
}
// MARK: - 私有方法
private extension DDCustomCameraManager {
static func export(for asset: PHAsset?, type: DDExportVideoType, presetName: String, complete:((String?, NSError?)->())?) {
guard let asset = asset else {
return
}
if asset.mediaType != .video {
if complete != nil {
complete?(nil, NSError(domain: "导出失败", code: -1, userInfo: ["message": "导出对象不是视频对象"]))
}
return
}
let options = PHVideoRequestOptions()
options.version = .original
options.deliveryMode = .automatic
options.isNetworkAccessAllowed = true
PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { (avAsset, audioMix, info) in
self.export(for: avAsset, range: CMTimeRange(start: CMTime.zero, duration: CMTime.positiveInfinity), type: type, presetName: presetName, complete: { (exportFilePath, error) in
DispatchQueue.main.async(execute: {
if complete != nil {
complete?(exportFilePath, error)
}
})
})
}
}
static func export(for asset: AVAsset?, range: CMTimeRange, type: DDExportVideoType, presetName: String, complete:((String?, NSError?)->())?) {
guard let asset = asset else {
if complete != nil {
complete?(nil, NSError(domain: "导出失败", code: -1, userInfo: ["message": "找不到导出对象"]))
}
return
}
let exportFilePath = self.getVideoExportFilePath(.mp4)
let exportSession = AVAssetExportSession(asset: asset, presetName: presetName)
let exportFileUrl = URL(fileURLWithPath: exportFilePath)
exportSession?.outputURL = exportFileUrl
exportSession?.outputFileType = (type == .mov) ? .mov : .mp4
exportSession?.timeRange = range
if let session = exportSession {
session.exportAsynchronously(completionHandler: {
if session.status == .completed {
if complete != nil {
complete?(exportFilePath, nil)
}
} else {
if complete != nil {
complete?(nil, NSError(domain: "导出失败", code: -1, userInfo: nil))
}
session.cancelExport()
}
})
}
}
}
<file_sep>//
// UIProgressView+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UIProgressView {
@discardableResult
func progressViewStyle(_ style: UIProgressView.Style) -> Self {
progressViewStyle = style
return self
}
@discardableResult
func progress(_ value: Float) -> Self {
progress = value
return self
}
@discardableResult
func progressTintColor(_ color: UIColor?) -> Self {
progressTintColor = color
return self
}
@discardableResult
func trackTintColor(_ color: UIColor?) -> Self {
trackTintColor = color
return self
}
@discardableResult
func progressImage(_ image: UIImage?) -> Self {
progressImage = image
return self
}
@discardableResult
func trackImage(_ image: UIImage?) -> Self {
trackImage = image
return self
}
@discardableResult
func observedProgress(_ progress: Progress?) -> Self {
observedProgress = progress
return self
}
}
<file_sep>source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/aliyun/aliyun-specs.git'
source 'https://github.com/hk01-digital/dd01-ios-uikit-spec.git'
platform :ios, '9.0'
target 'DDCustomCameraDemo' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
pod 'SnapKit'
pod 'DDKit/Hud'
end
<file_sep>
//
// ScanSecondController.swift
// Example
//
// Created by USER on 2018/11/29.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
import DDKit
class ScanSecondController: DDScanViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
/// 重写此回调方法即可
///
/// - Parameter results: results
override func handleCodeResult(results: [DDScanResult]?) {
guard let arr = results else {
return
}
//处理信息等待可以显示菊花
showActivity()
showMsg(title: "", message: arr.first?.strScanned)
}
func showMsg(title: String?, message: String?) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: UIAlertController.Style.alert)
let alertAction = UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: UIAlertAction.Style.default) {[weak self] (alertAction) in
self?.hiddenActivity()
self?.navigationController?.popViewController(animated: true)
}
let cancelAction = UIAlertAction(title: "重新扫描", style: .default) {[weak self] (action) in
self?.hiddenActivity()
self?.start()
}
alertController.addAction(cancelAction)
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
}
}
<file_sep>//
// DDDebug+UIViewController.swift
// DDDebug
//
// Created by shenzhen-dd01 on 2019/1/16.
// Copyright © 2019 shenzhen-dd01. All rights reserved.
//
import Foundation
public extension UIViewController {
/// 显示当前显示的控制器的名字
public static func ch_swizzle() {
UIViewController.swizzleViewWillAppear()
}
}
// MARK: - Method Swizzling
extension UIViewController {
private static func swizzleViewWillAppear() {
guard self == UIViewController.self else { return }
//巧妙的方法,使用匿名函数避免再次调用
let _: () = {
let originalSelector = #selector(UIViewController.viewWillAppear(_:))
let swizzledSelector = #selector(UIViewController.debug_ViewWillAppear(_:))
if let originalMethod = class_getInstanceMethod(self, originalSelector),
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}()
}
@objc private func debug_ViewWillAppear(_ animated: Bool) {
debug_ViewWillAppear(animated)
let currentvc = NSStringFromClass(type(of: self)).components(separatedBy: ".").last ?? "UIViewController"
guard currentvc != "UIViewController"
&& currentvc != "UIAlertController"
&& currentvc != "UIPageViewController"
&& currentvc != "SFSafariViewController"
&& currentvc != "UINavigationController"
&& currentvc != "UIInputWindowController"
&& currentvc != "SFBrowserRemoteViewController"
&& currentvc != "UISystemKeyboardDockController"
&& currentvc != "UICompatibilityInputViewController" else { return }
print("【DDDebug】+++++++++++++【current viewController: \(currentvc) 】")
}
}
<file_sep>//
// TablePlayerController.swift
// Example
//
// Created by USER on 2018/11/14.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
import DDKit
import SnapKit
class TablePlayerController: UIViewController {
var player = DDVideoPlayer()
var currentPlayIndexPath : IndexPath?
var isHidden:Bool = false
var tableView: UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .grouped)
tableView.register(PlayeCell.self, forCellReuseIdentifier: "PlayeCell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalTo(view)
}
let options = NSKeyValueObservingOptions([.new, .initial])
tableView.addObserver(self, forKeyPath: #keyPath(UITableView.contentOffset), options: options, context: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
player.pause()
}
deinit {
player.cleanPlayer()
tableView.removeObserver(self, forKeyPath: #keyPath(UITableView.contentOffset))
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .none
}
override var prefersStatusBarHidden: Bool {
return isHidden
}
}
extension TablePlayerController {
//kvo 目的是滚动table的时候。当前播放cell不可见,就自动移除播放,
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(UITableView.contentOffset) {
if let playIndexPath = currentPlayIndexPath {
if let cell = tableView.cellForRow(at: playIndexPath) {
if player.displayView.isFullScreen { return }
let visibleCells = tableView.visibleCells
if visibleCells.contains(cell) {
} else {
player.cleanPlayer()
player.displayView.removeFromSuperview()
}
} else {
player.cleanPlayer()
player.displayView.removeFromSuperview()
}
}
}
}
}
extension TablePlayerController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = (tableView.dequeueReusableCell(withIdentifier: "PlayeCell") as! PlayeCell)
cell.playBtn.setTitle("播放\(indexPath.row)", for: .normal)
cell.indexPath = indexPath
cell.playBtnCallBack = {[weak self] (cell, index) in
self?.setPlayer(cell, indexPath: index)
}
return cell
}
func setPlayer(_ cell: PlayeCell?, indexPath: IndexPath?) {
currentPlayIndexPath = indexPath
player.cleanPlayer()
let url = URL(string: "http://tb-video.bdstatic.com/videocp/12045395_f9f87b84aaf4ff1fee62742f2d39687f.mp4")!
self.player.replaceVideo(url)
self.player.backgroundMode = .proceed
//tableCell竖屏播放是否执行定时器自动隐藏播放界面的底部栏
self.player.isHiddenCellPlayBottomBar = false
//横屏设置要显示的标题
self.player.displayView.titleLabel.text = "DD01"
self.player.displayView.delegate = self
cell?.containerView.addSubview(self.player.displayView)
self.player.displayView.frame = cell?.contentView.bounds ?? CGRect.zero
self.player.play()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension TablePlayerController: DDPlayerViewDelegate {
func ddPlayerView(_ playerView: DDVideoPlayerView, willFullscreen isFullscreen: Bool, orientation: UIInterfaceOrientation) {
if orientation == .portrait {
isHidden = false
} else {
isHidden = true
}
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
}
<file_sep>//
// CityHotCollectionCell.swift
// PlacePickerDemo
//
// Created by weiwei.li on 2019/1/3.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class CityHotCollectionCell: UICollectionViewCell {
public lazy var textLab: UILabel = {
let lab = UILabel(frame: CGRect.zero)
lab.textAlignment = .center
lab.font = UIFont.systemFont(ofSize: 14)
lab.textColor = UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1)
return lab
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(textLab)
contentView.backgroundColor = UIColor.white
}
override func layoutSubviews() {
super.layoutSubviews()
var textLabFrame = bounds
textLabFrame.origin.x = 10
textLabFrame.size.width = bounds.width - 10 * 2
textLab.frame = textLabFrame
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>//
// UIImageView+Chainable.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIImageView
public extension UIKitChainable where Self: UIImageView {
/// 设置图片
///
/// - Parameter image: image
/// - Returns: self
@discardableResult
func image(_ image: UIImage?) -> Self {
self.image = image
return self
}
/// highlightedImage
///
/// - Parameter image: image
/// - Returns: self
@discardableResult
func highlightedImage(_ image: UIImage?) -> Self {
highlightedImage = image
return self
}
/// isUserInteractionEnabled
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func isUserInteractionEnabled(_ bool: Bool) -> Self {
isUserInteractionEnabled = bool
return self
}
/// isHighlighted
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func isHighlighted(_ bool: Bool) -> Self {
isHighlighted = bool
return self
}
/// animationImages
///
/// - Parameter images: images
/// - Returns: self
@discardableResult
func animationImages(_ images: [UIImage]?) -> Self {
animationImages = images
return self
}
/// highlightedAnimationImages
///
/// - Parameter images: images
/// - Returns: self
@discardableResult
func highlightedAnimationImages(_ images: [UIImage]?) -> Self {
highlightedAnimationImages = images
return self
}
/// 动画时间
///
/// - Parameter duration: 时间
/// - Returns: self
@discardableResult
func animationDuration(_ duration: TimeInterval) -> Self {
animationDuration = duration
return self
}
/// 动画循环次数
///
/// - Parameter count: count
/// - Returns: self
@discardableResult
func animationRepeatCount(_ count: Int) -> Self {
animationRepeatCount = count
return self
}
/// tintColor
///
/// - Parameter color: color
/// - Returns: self
@discardableResult
func tintColor(_ color: UIColor) -> Self {
tintColor = color
return self
}
/// 开始动画
///
/// - Returns: self
@discardableResult
func startAnimate() -> Self {
startAnimating()
return self
}
/// 停止动画
///
/// - Returns: self
@discardableResult
func stopAnimate() -> Self {
stopAnimating()
return self
}
}
<file_sep>//
// Date+Extension.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/21.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
public extension Date {
// 只初始化一次,多次初始化DateFormatter对性能会有损耗
fileprivate static var outputFormatter = DateFormatter()
/// 获取日
/// 2019-01-21 06:24:16 +0000
/// return 21
var day: Int {
return Date.day(date: self)
}
static func day(date d: Date) -> Int {
let calendar = Calendar.current
return calendar.component(.day, from: d)
}
/// 获取月
/// 2019-01-21 06:26:18 +0000
/// return 1
var month: Int {
return Date.month(date: self)
}
static func month(date d: Date) -> Int {
let calendar = Calendar.current
return calendar.component(.month, from: d)
}
/// 获取年
/// 2019-01-21 06:26:18 +0000
/// return 2019
var year: Int {
return Date.year(date: self)
}
static func year(date d: Date) -> Int {
let calendar = Calendar.current
return calendar.component(.year, from: d)
}
/// 获取时
/// 2019-01-21 06:26:18 +0000
/// return 14
var hour: Int {
return Date.hour(date: self)
}
static func hour(date d: Date) -> Int {
let calendar = Calendar.current
return calendar.component(.hour, from: d)
}
var minute: Int {
return Date.minute(date: self)
}
static func minute(date d: Date) -> Int {
let calendar = Calendar.current
return calendar.component(.minute, from: d)
}
/// 获取秒
/// 2019-01-21 06:26:18 +0000
/// return 2
var second: Int {
return Date.second(date: self)
}
static func second(date d: Date) -> Int {
let calendar = Calendar.current
return calendar.component(.second, from: d)
}
/// 获取星期几
/// 周日--周六分别为 1---7
var weekday: Int {
return Date.weekday(self)
}
static func weekday(_ fromDate: Date) -> Int {
let calendar = Calendar(identifier: .gregorian)
return calendar.component(.weekday, from: fromDate)
}
/// 是否为闰年
var isLeapYear: Bool {
return Date.isLeapYear(date: self)
}
static func isLeapYear(date d: Date) -> Bool {
let year = d.year
if (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0) {
return true
}
return false
}
/// 获取全年天数
var daysInYear: Int {
return Date.daysInYear(date: self)
}
static func daysInYear(date d: Date) -> Int {
return self.isLeapYear(date: d) ? 366: 365
}
/// 获取当前日期是当年的第几周
var weekOfYear: Int {
return Date.weekOfYear(date: self)
}
static func weekOfYear(date d: Date) -> Int {
var i = 1
let year = d.year
while d.dateAfterDay(-7 * i).year == year {
i += 1
}
return i
}
/// 返回当前月一共有几周(可能为4,5,6)
var weeksOfMonth: Int {
return Date.weeksOfMonth(date: self)
}
static func weeksOfMonth(date d: Date) -> Int {
return d.lastdayOfMonth.weekOfYear - d.begindayOfMonth.weekOfYear + 1
}
/// 获取该月的第一天的日期
var begindayOfMonth: Date {
return Date.begindayOfMonth(date: self)
}
static func begindayOfMonth(date d: Date) -> Date {
return dateAfterDay(d, day: -(d.day) + 1)
}
/// 获取该月的最后一天的日期
var lastdayOfMonth: Date {
return Date.lastdayOfMonth(date: self)
}
static func lastdayOfMonth(date d: Date) -> Date {
let lastDate = begindayOfMonth(date: d)
return lastDate.dateAfterMonth(1).dateAfterDay(-1)
}
/// 返回day天后的日期(若day为负数,则为|day|天前的日期)
///
/// - Parameter day: 天数
func dateAfterDay(_ day: Int) -> Date {
return Date.dateAfterDay(self, day: day)
}
static func dateAfterDay(_ fromDate: Date, day: Int) -> Date {
let calendar = Calendar.current
var componentsToAdd = DateComponents()
componentsToAdd.setValue(day, for: .day)
let dateAfterDay = calendar.date(byAdding: componentsToAdd, to: fromDate) ?? Date()
return dateAfterDay
}
/// 返回month月后的日期(若day为负数,则为|month|月前的日期)
///
/// - Parameters:
/// - date: date
/// - month: 月
/// - Returns: Date
func dateAfterMonth(_ month: Int) -> Date {
return Date.dateAfterMonth(self, month: month)
}
static func dateAfterMonth(_ fromDate: Date, month: Int) -> Date {
let calendar = Calendar.current
var componentsToAdd = DateComponents()
componentsToAdd.setValue(month, for: .month)
return calendar.date(byAdding: componentsToAdd, to: fromDate) ?? Date()
}
/// 返回Years年后的日期
///
/// - Parameter years: 年数
/// - Returns: Date
func dateAfterYears(_ years: Int) -> Date {
return Date.dateAfterYears(self, years: years)
}
static func dateAfterYears(_ fromDate: Date, years: Int) -> Date {
let calendar = Calendar(identifier: .gregorian)
var offsetComponents = DateComponents()
offsetComponents.setValue(years, for: .year)
return calendar.date(byAdding: offsetComponents, to: fromDate) ?? Date()
}
/// 返回hours小时后的日期
func dateAfterHours(_ hours: Int) -> Date {
return Date.dateAfterHours(self, hours: hours)
}
static func dateAfterHours(_ fromDate: Date, hours: Int) -> Date {
let calendar = Calendar(identifier: .gregorian)
var offsetComponents = DateComponents()
offsetComponents.setValue(hours, for: .hour)
return calendar.date(byAdding: offsetComponents, to: fromDate) ?? Date()
}
/// 判断是否为同一天
///
/// - Parameter date: anotherDate
/// - Returns: Bool
func isSameDay(anotherDate date: Date) -> Bool {
return Date.isSameDay(self, anotherDate: date)
}
static func isSameDay(_ fromDate: Date, anotherDate date: Date) -> Bool {
let calendar = Calendar.current
let components1 = calendar.dateComponents([.year, .month, .day], from: fromDate)
let components2 = calendar.dateComponents([.year, .month, .day], from: date)
return (components1.year == components2.year) && (components1.month == components2.month) && (components1.day == components2.day)
}
/// 是否是今天
var isToday: Bool {
return Date.isSameDay(self, anotherDate: Date())
}
/// 获取格式化为YYYY-MM-dd格式的日期字符串
/// 2019年01月21日
var formatYMD: String {
return Date.formatYMD(date: self)
}
static func formatYMD(date d: Date) -> String {
return String(format: "%d年%02lu月%02lu日",d.year,d.month,d.day)
}
/// 根据日期返回字符串
/// YYYY/MM/dd HH:mm:ss HH大写为24小时制,小写为12小时制
/// - Parameter format: 格式化
/// - Returns: String
func stringWithFormat(_ format: String) -> String {
return Date.stringWithDate(self, format: format)
}
static func stringWithDate(_ date: Date, format: String) -> String {
outputFormatter.dateFormat = format
return outputFormatter.string(from: date)
}
/// 根据时间字符串获取Date
///
/// - Parameters:
/// - string: 字符串
/// - format: 格式化
/// - Returns: Date
static func dateWithString(_ string: String, format: String) -> Date {
outputFormatter.dateFormat = format
return outputFormatter.date(from: string) ?? Date()
}
/// 获取指定月份的天数
func daysInMonth(_ month: Int) -> Int {
return Date.daysInMonth(self, month: month)
}
static func daysInMonth(_ fromDate: Date, month: Int) -> Int {
switch month {
case 1, 3, 5, 7, 8, 9, 10, 12:
return 31
case 2:
return fromDate.isLeapYear ? 29 : 28
default:
return 30
}
}
/// 分别获取yyyy-MM-dd/HH:mm:ss/yyyy-MM-dd HH:mm:ss格式的字符串
var ymdFormat: String {
return Date.ymdFormat()
}
static func ymdFormat() -> String {
return "yyyy-MM-dd"
}
var hmsFormat: String {
return Date.hmsFormat()
}
static func hmsFormat() -> String {
return "HH:mm:ss"
}
var ymdHmsFormat: String {
return Date.ymdHmsFormat()
}
static func ymdHmsFormat() -> String {
return "\(self.ymdFormat()) \(self.hmsFormat())"
}
}
<file_sep>
//
// DDPhotoView.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/11/22.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import Kingfisher
let kMaxZoomScale: CGFloat = 2.0
class DDPhotoView: UIView {
public lazy var scrollView: DDScrollView = {
let scrollView = DDScrollView()
let sWidth = UIScreen.main.bounds.width
let sHeight = UIScreen.main.bounds.height
scrollView.frame = CGRect(x: 0, y: 0, width: sWidth, height: sHeight)
scrollView.backgroundColor = UIColor.clear
scrollView.delegate = self
scrollView.clipsToBounds = true
scrollView.isMultipleTouchEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
return scrollView
}()
public lazy var imageView: AnimatedImageView = {
let imageView = AnimatedImageView()
let sWidth = UIScreen.main.bounds.width
let sHeight = UIScreen.main.bounds.height
imageView.frame = CGRect(x: 0, y: 0, width: sWidth, height: sHeight)
imageView.clipsToBounds = true
imageView.autoPlayAnimatedImage = false
imageView.isUserInteractionEnabled = true
return imageView
}()
private lazy var activityView: UIActivityIndicatorView = {
let activityView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
activityView.center = CGPoint(x: UIScreen.main.bounds.width / 2.0, y: UIScreen.main.bounds.height / 2.0)
activityView.style = .whiteLarge
return activityView
}()
//MARK -- 视屏播放相关
let videoView: PhotoBrowserVideoView = {
let videoView = PhotoBrowserVideoView()
videoView.backgroundColor = UIColor.black
return videoView
}()
public var photo: DDPhoto?
public var zoomEnded: ((CGFloat)->())?
/// 横屏时是否充满屏幕宽度,默认YES,为NO时图片自动填充屏幕
public var isFullWidthForLandSpace: Bool = true
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
addSubview(scrollView)
addSubview(activityView)
scrollView.addSubview(imageView)
activityView.isHidden = false
imageView.addSubview(videoView)
videoView.isHidden = true
}
override func layoutSubviews() {
super.layoutSubviews()
if photo?.isVideo == true {
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
videoView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
videoView.setNeedsLayout()
videoView.layoutIfNeeded()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
cleanImage()
imageView.stopAnimating()
}
}
extension DDPhotoView {
public func setupPhoto(_ photo: DDPhoto?) {
self.photo = photo
if photo?.isVideo == true {
activityView.isHidden = true
videoView.isHidden = false
videoView.photo = photo
imageView.image = nil
return
}
videoView.isHidden = true
loadImage(photo)
}
public func zoomToRect(_ rect : CGRect, animated: Bool) {
scrollView.zoom(to: rect, animated: true)
}
public func resetFrame() {
scrollView.frame = bounds
activityView.center = UIApplication.shared.keyWindow?.center ?? CGPoint.zero
if photo != nil {
adjustFrame(photo: photo)
}
}
func adjustFrame(photo: DDPhoto? = nil) {
if photo?.isVideo == true {
return
}
scrollView.setZoomScale(1, animated: false)
var frame = scrollView.frame
if imageView.image != nil {
let imageSize = imageView.image?.size ?? CGSize.zero
var imageF = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
// 图片的宽度 = 屏幕的宽度
let ratio = frame.width / imageF.size.width
imageF.size.width = frame.width
imageF.size.height = ratio * imageF.size.height
// 默认情况下,显示出的图片的宽度 = 屏幕的宽度
// 如果IsFullWidthForLandSpace = NO,需要把图片全部显示在屏幕上
// 此时由于图片的宽度已经等于屏幕的宽度,所以只需判断图片显示的高度>屏幕高度时,将图片的高度缩小到屏幕的高度即可
if isFullWidthForLandSpace == false {
// 图片的高度 > 屏幕的高度
if imageF.size.height > frame.size.height {
let scale = imageF.size.width / imageF.size.height
imageF.size.height = frame.size.height
imageF.size.width = imageF.size.height * scale
}
}
// 设置图片的frame
imageView.frame = imageF
scrollView.contentSize = imageView.frame.size
if imageF.size.height <= scrollView.bounds.height {
imageView.center = CGPoint(x: scrollView.bounds.width * 0.5, y: scrollView.bounds.height * 0.5)
} else {
imageView.center = CGPoint(x: scrollView.bounds.width * 0.5, y: imageF.size.height * 0.5)
}
// 根据图片大小找到最大缩放等级,保证最大缩放时候,不会有黑边
var maxScale = frame.size.height / imageF.height
maxScale = (frame.width / imageF.size.width) > maxScale ? (frame.size.width / imageF.size.width) : maxScale
// 超过了设置的最大的才算数
maxScale = maxScale > kMaxZoomScale ? maxScale : kMaxZoomScale
// 初始化
scrollView.minimumZoomScale = 1
scrollView.maximumZoomScale = maxScale
scrollView.zoomScale = 1
} else {
frame.origin = CGPoint.zero
let width = frame.width
let height = width
imageView.bounds = CGRect(x: 0, y: 0, width: width, height: height)
imageView.center = CGPoint(x: frame.width * 0.5, y: frame.size.height * 0.5)
// 重置内容大小
scrollView.contentSize = imageView.frame.size
}
scrollView.contentOffset = CGPoint.zero
// if let photo = photo {
// imageView.contentMode = photo.sourceImageView?.contentMode ?? .scaleToFill
// } else {
// imageView.contentMode = .scaleToFill
// }
imageView.contentMode = .scaleToFill
// frame调整完毕,重新设置缩放
if photo?.isZooming == true {
zoomToRect((photo?.zoomRect ?? CGRect.zero), animated: false)
}
}
func centerOfScrollViewContent(_ scrollView: UIScrollView) -> CGPoint {
let offsetX = (scrollView.bounds.width > scrollView.contentSize.width) ? (scrollView.bounds.width - scrollView.contentSize.width) * 0.5 : 0
let offsetY = (scrollView.bounds.height > scrollView.contentSize.height) ? (scrollView.bounds.height - scrollView.contentSize.height) * 0.5 : 0
let actualCenter = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
return actualCenter
}
}
extension DDPhotoView: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
imageView.center = centerOfScrollViewContent(scrollView)
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
if let callBack = zoomEnded {
callBack(scrollView.zoomScale)
}
}
}
private extension DDPhotoView {
func loadImage(_ photo: DDPhoto?) {
bringSubviewToFront(activityView)
if let photo = photo {
scrollView.setZoomScale(1, animated: false)
if let image = photo.image {
activityView.stopAnimating()
activityView.isHidden = true
scrollView.isScrollEnabled = true
photo.isFinished = true
imageView.image = image
adjustFrame(photo: photo)
return
}
// 显示原来的图片
if imageView.image == nil {
imageView.image = photo.placeholderImage != nil ? (photo.placeholderImage) : (photo.sourceImageView?.image)
adjustFrame(photo: photo)
}
scrollView.isScrollEnabled = false
activityView.isHidden = false
activityView.startAnimating()
//gif只加载第一帧,防止内存过大
var options: KingfisherOptionsInfo? = nil
if photo.isGif == true {
options = KingfisherOptionsInfo()
options?.append(.onlyLoadFirstFrame)
}
imageView.kf.setImage(with: photo.url, placeholder: photo.placeholderImage, options: nil, progressBlock: { (receivedSize, totalSize) in
}) {[weak self] (image, err, type, url) in
if err != nil {
photo.isFailed = true
return
}
photo.image = image
self?.imageView.image = image
if photo.isFirstPhoto == true && photo.isGif == true {
self?.imageView.startAnimating()
photo.isFirstPhoto = false
}
photo.isFinished = true
self?.scrollView.isScrollEnabled = true
self?.activityView.isHidden = true
self?.activityView.stopAnimating()
self?.adjustFrame(photo: photo)
}
} else {
cleanImage()
}
}
func cleanImage() {
imageView.image = nil
adjustFrame(photo: photo)
}
}
<file_sep>//
// DDDebug+URLSession.swift
// DDDebug
//
// Created by shenzhen-dd01 on 2019/1/17.
// Copyright © 2019 shenzhen-dd01. All rights reserved.
//
import Foundation
public extension URLSession {
/// 显示当前显示的控制器的名字
public static func ch_swizzle() {
URLSession.swizzleSession()
}
}
extension URLSession {
private static func swizzleSession() {
guard self == UIViewController.self else { return }
//巧妙的方法,使用匿名函数避免再次调用
let _: () = {
//Swift 方式 Hook URLSession 代理方法
// NSNotificationCenter @"NSURLSession_Hook_Request" get request info
// NSNotificationCenter @"NSURLSession_Hook_Response" get response info
}()
}
}
<file_sep>//
// Timer+DDVideoPlayer.swift
// mpdemo
//
// Created by leo on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import Foundation
extension Timer {
class func ddPlayer_scheduledTimerWithTimeInterval(_ timeInterval: TimeInterval, block: @escaping()->(), repeats: Bool) -> Timer {
return self.scheduledTimer(timeInterval: timeInterval, target:
self, selector: #selector(self.ddPlayer_blcokInvoke(_:)), userInfo: block, repeats: repeats)
}
@objc class func ddPlayer_blcokInvoke(_ timer: Timer) {
let block: ()->() = timer.userInfo as! ()->()
block()
}
}
<file_sep># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
target 'ToastDemo' do
use_frameworks!
pod 'PKHUD'
pod 'SnapKit'
pod 'MBProgressHUD'
end
<file_sep>//
// UITextField+Chainable.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
//extension UITextField {
// fileprivate struct ChainableTextFieldKey {
// static var kChainableTextFieldDelegateKey = "kChainableTextFieldDelegateKey"
// }
//
//
// /// Chainable内部使用
// weak var chainalbeDelegate: UITextFieldDelegate? {
// get {
// return objc_getAssociatedObject(self, &ChainableTextFieldKey.kChainableTextFieldDelegateKey) as? UITextFieldDelegate
// }
//
// set(value) {
// objc_setAssociatedObject(self, &ChainableTextFieldKey.kChainableTextFieldDelegateKey, value, .OBJC_ASSOCIATION_ASSIGN)
// }
// }
//}
public extension UIKitChainable where Self: UITextField {
/// 设置代理
///
/// - Parameter delegate: delegate
/// - Returns: self
// @discardableResult
// func delegate(_ delegate: UITextFieldDelegate?) -> UITextField {
// chainalbeDelegate = delegate
// return self
// }
/// 文字
///
/// - Parameter text: text
/// - Returns: self
@discardableResult
func text(_ text: String?) -> Self {
self.text = text
return self
}
/// attributedText
///
/// - Parameter text: text
/// - Returns: self
@discardableResult
func attributedText(_ text: NSAttributedString?) -> Self {
attributedText = text
return self
}
@discardableResult
func textColor(_ color: UIColor?) -> Self {
textColor = color
return self
}
@discardableResult
func font(_ font: UIFontType) -> Self {
self.font = font.font
return self
}
@discardableResult
func textAlignment(_ alignment: NSTextAlignment) -> Self {
textAlignment = alignment
return self
}
@discardableResult
func borderStyle(_ style: UITextField.BorderStyle) -> Self {
borderStyle = style
return self
}
@discardableResult
func defaultTextAttributes(_ attributes: [String : Any]) -> Self {
defaultTextAttributes = convertToNSAttributedStringKeyDictionary(attributes)
return self
}
@discardableResult
func placeholder(_ holder: String?) -> Self {
placeholder = holder
return self
}
@discardableResult
func attributedPlaceholder(_ holder: NSAttributedString?) -> Self {
attributedPlaceholder = holder
return self
}
@discardableResult
func clearsOnBeginEditing(_ bool: Bool) -> Self {
clearsOnBeginEditing = bool
return self
}
@discardableResult
func adjustsFontSizeToFitWidth(_ bool: Bool) -> Self {
adjustsFontSizeToFitWidth = bool
return self
}
@discardableResult
func minimumFontSize(_ size: CGFloat) -> Self {
minimumFontSize = size
return self
}
@discardableResult
func background(image: UIImage?) -> Self {
background = image
return self
}
@discardableResult
func disabledBackground(image: UIImage?) -> Self {
disabledBackground = image
return self
}
@discardableResult
func allowsEditingTextAttributes(_ bool: Bool) -> Self {
allowsEditingTextAttributes = bool
return self
}
@discardableResult
func typingAttributes(_ attributes: [String : Any]?) -> Self {
typingAttributes = convertToOptionalNSAttributedStringKeyDictionary(attributes)
return self
}
@discardableResult
func clearButtonMode(_ mode: UITextField.ViewMode) -> Self {
clearButtonMode = mode
return self
}
@discardableResult
func leftView(_ view: UIView?) -> Self {
leftView = view
return self
}
@discardableResult
func leftViewMode(_ mode: UITextField.ViewMode) -> Self {
leftViewMode = mode
return self
}
@discardableResult
func rightView(_ view: UIView?) -> Self {
rightView = view
return self
}
@discardableResult
func rightViewMode(_ mode: UITextField.ViewMode) -> Self {
rightViewMode = mode
return self
}
@discardableResult
func inputView(_ view: UIView?) -> Self {
inputView = view
return self
}
@discardableResult
func inputAccessoryView(_ view: UIView?) -> Self {
inputAccessoryView = view
return self
}
@discardableResult
func clearsOnInsertion(_ bool: Bool) -> Self {
clearsOnInsertion = bool
return self
}
/// 是否开始进入编辑状态
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addShouldBegindEditingBlock(_ handler: @escaping((UITextField)->(Bool))) -> Self {
setShouldBegindEditingBlock(handler)
return self
}
/// 是否结束编辑状态
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addShouldEndEditingBlock(_ handler: @escaping((UITextField)->(Bool))) -> Self {
setShouldEndEditingBlock(handler)
return self
}
/// 进入编辑状态
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addDidBeginEditingBlock(_ handler: @escaping((UITextField)->())) -> Self {
setDidBeginEditingBlock(handler)
return self
}
/// 是否改变输入的字符
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addShouldChangeCharactersInRangeBlock(_ handler: @escaping((UITextField, NSRange, String)->(Bool))) -> Self {
setShouldChangeCharactersInRangeBlock(handler)
return self
}
/// 点击clear按钮是否有效
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addShouldClearBlock(_ handler: @escaping((UITextField)->(Bool))) -> Self {
setShouldClearBlock(handler)
return self
}
/// 点击return按钮是否有效
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addShouldReturnBlock(_ handler: @escaping((UITextField)->(Bool))) -> Self {
setShouldReturnBlock(handler)
return self
}
/// 最大输入字符长度
///
/// - Parameter length: length
/// - Returns: self
@discardableResult
func maxLength(_ length: Int) -> Self {
self.maxLength = length
return self
}
/// 当进入编辑的时候是否需要震动
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func shake(_ bool: Bool) -> Self {
shouldBegindEditingShake = bool
return self
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToNSAttributedStringKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.Key: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
<file_sep>//
// DDPhotoStyleConfig.swift
// DDCustomCameraDemo
//
// Created by weiwei.li on 2019/1/4.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
public class DDPhotoStyleConfig: NSObject {
public static let shared = DDPhotoStyleConfig()
///MARK: - UI相关,主要针对e肚仔
public var navigationBackImage: UIImage?
public var navigationBackgroudColor: UIColor?
public var navigationTintColor: UIColor?
public var navigationBarStyle:UIBarStyle = .black
public var seletedImageCircleColor: UIColor?
public var bottomBarBackgroudColor: UIColor?
public var bottomBarTintColor: UIColor?
///MARK: - 基本参数设置
//是否使用DDKit/Hud提示框。主要为了e肚仔项目
public var isEnableDDKitHud = false
//最大可选择的图片数量
public var maxSelectedNumber: Int = 1
//此属性只能设置从相册选择返回的图片大小。拍照无效
//选择返回图片size大小,为需要展示的缩略图大小。
//若默认返回原图,大图片会导致内存问题
//展示时按需获取图片大小
//若为上传图片,请调用DDPhotoImageManager.requestOriginalImage方法获取。或者DDCustomCameraManager都有同样的方法调用
//请至少设置 140 * 140
public var imageSize:CGSize = CGSize.init(width: 140, height: 140)
//选择类型
public var photoAssetType: DDPhotoPickerAssetType = .all {
didSet {
if photoAssetType == .imageOnly {
isEnableRecordVideo = false
}
}
}
//是否支持录制视屏
public var isEnableRecordVideo: Bool = true
//是否支持拍照
public var isEnableTakePhoto: Bool = true {
didSet {
if isEnableRecordVideo == false {
photoAssetType = .imageOnly
}
}
}
//最大录制时长
public var maxRecordDuration: Int = 15
//拍照选择尺寸
public var sessionPreset: DDCaptureSessionPreset = .preset1280x720
//thumbnailSize,录制视屏完成回调需要显示的缩略图,录制视屏时有效。
//拍照默认返回原图,因为拍摄的照片还需存入相册,无需多操作此步骤
public var thumbnailSize: CGSize = CGSize(width: 150, height: 150)
//是否显示截图框
public var isShowClipperView: Bool = false
//截图框的大小
public var clipperSize: CGSize = CGSize(width: 250, height: 400)
//长按拍摄动画进度条颜色
public var circleProgressColor: UIColor = UIColor(red: 99.0/255.0, green: 181.0/255.0, blue: 244.0/255.0, alpha: 1)
//MARK: -- 授权提示
//相册授权
public var photoPermission = "您没有使用照片的权限\n请在设置->隐私->照片中打开权限"
//相机授权
public var cameraPermission = "您没有使用相机的权限\n请在设置->隐私->相机中打开权限"
//麦克风授权
public var microphonePermission = "您没有使用麦克风的权限\n请在设置->隐私->麦克风中打开权限"
}
<file_sep>//
// UISearchBar+Blocks.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UISearchBar {
fileprivate struct SearchBarKey {
static var SearchBarShouldBeginEditing = "SearchBarShouldBeginEditing"
static var SearchBarTextDidBeginEditing = "SearchBarTextDidBeginEditing"
static var SearchBarShouldEndEditing = "SearchBarShouldEndEditing"
static var SearchBarTextDidEndEditing = "SearchBarTextDidEndEditing"
static var SearchBarTextDidChange = "SearchBarTextDidChange"
static var SearchBarTextShouldChangeTextInRangeReplacementText = "SearchBarTextShouldChangeTextInRangeReplacementText"
static var SearchBarSearchButtonClicked = "SearchBarSearchButtonClicked"
static var SearchBarBookmarkButtonClicked = "SearchBarBookmarkButtonClicked"
static var SearchBarCancelButtonClicked = "SearchBarCancelButtonClicked"
static var SearchBarResultsListButtonClicked = "SearchBarResultsListButtonClicked"
static var SearchBarSelectedScopeButtonIndexDidChange = "SearchBarSelectedScopeButtonIndexDidChange"
}
fileprivate var searchBarShouldBeginEditingBlock: ((UISearchBar)->(Bool))? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarShouldBeginEditing) as? ((UISearchBar) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarShouldBeginEditing, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarTextDidBeginEditingBlock: ((UISearchBar)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarTextDidBeginEditing) as? ((UISearchBar) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarTextDidBeginEditing, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarShouldEndEditingBlock: ((UISearchBar)->(Bool))? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarShouldEndEditing) as? ((UISearchBar) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarShouldEndEditing, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarTextDidEndEditingBlock: ((UISearchBar)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarTextDidEndEditing) as? ((UISearchBar) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarTextDidEndEditing, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBartextDidChangeBlock: ((UISearchBar,String)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarTextDidChange) as? ((UISearchBar,String) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarTextDidChange, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarTextShouldChangeTextInRangeReplacementTextBlock: ((UISearchBar,String)->(Bool))? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarTextShouldChangeTextInRangeReplacementText) as? ((UISearchBar,String) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarTextShouldChangeTextInRangeReplacementText, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarSearchButtonClickedBlock: ((UISearchBar)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarSearchButtonClicked) as? ((UISearchBar) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarSearchButtonClicked, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarBookmarkButtonClickedBlock: ((UISearchBar)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarBookmarkButtonClicked) as? ((UISearchBar) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarBookmarkButtonClicked, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarCancelButtonClickedBlock: ((UISearchBar)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarCancelButtonClicked) as? ((UISearchBar) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarCancelButtonClicked, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarResultsListButtonClickedBlock: ((UISearchBar)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarResultsListButtonClicked) as? ((UISearchBar) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarResultsListButtonClicked, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var searchBarselectedScopeButtonIndexDidChangeBlock: ((UISearchBar, Int)->())? {
get {
return objc_getAssociatedObject(self, &SearchBarKey.SearchBarResultsListButtonClicked) as? ((UISearchBar,Int) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &SearchBarKey.SearchBarResultsListButtonClicked, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate func setDelegate() {
if delegate == nil || delegate?.isEqual(self) == false {
delegate = self
}
}
}
// MARK: - public method
extension UISearchBar {
public func setSearchBarShouldBeginEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->(Bool))) {
searchBarShouldBeginEditingBlock = handler
}
public func setSearchBarTextDidBeginEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) {
searchBarTextDidBeginEditingBlock = handler
}
public func setSearchBarShouldEndEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->(Bool))) {
searchBarShouldEndEditingBlock = handler
}
public func setSearchBarTextDidEndEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) {
searchBarTextDidEndEditingBlock = handler
}
public func setSearchBartextDidChangeBlock(_ handler: @escaping((_ searchBar: UISearchBar, _ searchText: String)->())) {
searchBartextDidChangeBlock = handler
}
public func setSearchBarTextShouldChangeTextInRangeReplacementTextBlock(_ handler: @escaping((_ searchBar: UISearchBar, _ replacementText: String)->(Bool))) {
searchBarTextShouldChangeTextInRangeReplacementTextBlock = handler
}
public func setSearchBarSearchButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) {
searchBarSearchButtonClickedBlock = handler
}
public func setSearchBarBookmarkButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) {
searchBarBookmarkButtonClickedBlock = handler
}
public func setSearchBarCancelButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) {
searchBarCancelButtonClickedBlock = handler
}
public func setSearchBarResultsListButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) {
searchBarResultsListButtonClickedBlock = handler
}
public func setSearchBarselectedScopeButtonIndexDidChangeBlock(_ handler: @escaping((_ searchBar: UISearchBar, _ selectedScope: Int)->())) {
searchBarselectedScopeButtonIndexDidChangeBlock = handler
}
}
extension UISearchBar: UISearchBarDelegate {
public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
if let block = searchBarShouldBeginEditingBlock {
return block(searchBar)
}
return true
}
public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBarTextDidBeginEditingBlock?(searchBar)
}
public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
if let block = searchBarShouldEndEditingBlock {
return block(searchBar)
}
return true
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBarTextDidEndEditingBlock?(searchBar)
}
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchBartextDidChangeBlock?(searchBar, searchText)
}
public func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let block = searchBarTextShouldChangeTextInRangeReplacementTextBlock {
return block(searchBar, text)
}
return true
}
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBarSearchButtonClickedBlock?(searchBar)
}
public func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
searchBarBookmarkButtonClickedBlock?(searchBar)
}
public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBarCancelButtonClickedBlock?(searchBar)
}
public func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
searchBarResultsListButtonClickedBlock?(searchBar)
}
public func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
searchBarselectedScopeButtonIndexDidChangeBlock?(searchBar, selectedScope)
}
}
<file_sep>//
// DDPhotoBrower.swift
// DDPhotoBrowserDemo
//
// Created by USER on 2018/11/22.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
public protocol DDPhotoBrowerDelegate: NSObjectProtocol {
/// 索引值改变
///
/// - Parameter index: 索引
func photoBrowser(controller: UIViewController?, didChanged index: Int?)
/// 单击事件,即将消失
///
/// - Parameter index: 索引
func photoBrowser(controller: UIViewController?, willDismiss index: Int?)
/// 长按事件事件
///
/// - Parameter index: 索引
func photoBrowser(controller: UIViewController?, longPress index: Int?)
}
extension DDPhotoBrowerDelegate {
func photoBrowser(controller: UIViewController?, didChanged index: Int?) {}
func photoBrowser(controller: UIViewController?, willDismiss index: Int?) {}
func photoBrowser(controller: UIViewController?, longPress index: Int?) {}
}
public class DDPhotoBrower: NSObject {
/// 代理
public weak var delegate: DDPhotoBrowerDelegate?
/// 滑动消失时是否隐藏原来的视图
public var isHideSourceView: Bool = false
/// 长按是否自动保存图片到相册,若为true,则长按代理不在回调。若为false,返回长按代理
public var isLongPressAutoSaveImageToAlbum: Bool = true
/// 配置保存图片权限提示
public var photoPermission: String = "请在iPhone的\"设置-隐私-照片\"选项中,允许访问您的照片"
/// 是否需要显示状态栏,默认不显示
// public var isShowStatusBar: Bool = false
public var photos: [DDPhoto]?
public var currentIndex: Int?
public init(photos: [DDPhoto], currentIndex: Int) {
super.init()
self.photos = photos
self.currentIndex = currentIndex
}
}
extension DDPhotoBrower {
public static func photoBrowser(Photos photos: [DDPhoto], currentIndex: Int) -> DDPhotoBrower {
return DDPhotoBrower(photos: photos, currentIndex: currentIndex)
}
public func show() {
let topController = getTopViewController
let vc = DDPhotoBrowerController(Photos: photos, currentIndex: currentIndex)
vc.modalTransitionStyle = .coverVertical
vc.modalPresentationStyle = .custom
vc.deleagte = delegate
vc.isHideSourceView = isHideSourceView
vc.isLongPressAutoSaveImageToAlbum = isLongPressAutoSaveImageToAlbum
vc.photoPermission = photoPermission
vc.previousStatusBarStyle = UIApplication.shared.statusBarStyle
// 是否接管状态栏外观,即重写的 prefersStatusBarHidden 等方法是否会被调用
vc.modalPresentationCapturesStatusBarAppearance = true
topController?.present(vc, animated: false, completion: nil)
}
}
private extension DDPhotoBrower {
private var getTopViewController: UIViewController? {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
return getTopViewController(viewController: rootViewController)
}
private func getTopViewController(viewController: UIViewController?) -> UIViewController? {
if let presentedViewController = viewController?.presentedViewController {
return getTopViewController(viewController: presentedViewController)
}
if let tabBarController = viewController as? UITabBarController,
let selectViewController = tabBarController.selectedViewController {
return getTopViewController(viewController: selectViewController)
}
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return getTopViewController(viewController: visibleViewController)
}
if let pageViewController = viewController as? UIPageViewController,
pageViewController.viewControllers?.count == 1 {
return getTopViewController(viewController: pageViewController.viewControllers?.first)
}
for subView in viewController?.view.subviews ?? [] {
if let childViewController = subView.next as? UIViewController {
return getTopViewController(viewController: childViewController)
}
}
return viewController
}
}
<file_sep>//
// UITextView+Blocks.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/9.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UITextView {
fileprivate struct TextViewKey {
static var UITextViewShouldBeginEditingKey = "UITextViewShouldBeginEditingKey"
static var UITextViewShouldEndEditingKey = "UITextViewShouldEndEditingKey"
static var UITextViewDidBeginEditingKey = "UITextViewDidBeginEditingKey"
static var UITextViewDidEndEditingKey = "UITextViewDidEndEditingKey"
static var UITextViewShouldChangeTextInRangeReplacementText = "UITextViewShouldChangeTextInRangeReplacementText"
static var UITextViewDidChangeKey = "UITextViewDidChangeKey"
static var UITextViewDidChangeSelectionKey = "UITextViewDidChangeSelectionKey"
static var UITextViewshouldInteractWithURLCharacterRangeInteraction = "UITextViewshouldInteractWithURLCharacterRangeInteraction"
static var UITextViewShouldInteractWithTextAttachmentCharacterRangeInteraction = "UITextViewShouldInteractWithTextAttachmentCharacterRangeInteraction"
static var UITextViewshouldInteractWithURLcharacterRange = "UITextViewshouldInteractWithURLcharacterRange"
static var UITextViewShouldInteractWithTextAttachmentCharacterRange = "UITextViewShouldInteractWithTextAttachmentCharacterRange"
}
fileprivate var shouldBegindEditingBlock: ((UITextView)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewShouldBeginEditingKey) as? ((UITextView) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewShouldBeginEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldEndEditingBlock: ((UITextView)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewShouldEndEditingKey) as? ((UITextView) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewShouldEndEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didBeginEditingBlock: ((UITextView)->())? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewDidBeginEditingKey) as? ((UITextView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewDidBeginEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didEndEditingBlock: ((UITextView)->())? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewDidEndEditingKey) as? ((UITextView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewDidEndEditingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var shouldChangeTextInRangeReplacementTextBlock: ((UITextView, NSRange, String)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewShouldChangeTextInRangeReplacementText) as? ((UITextView, NSRange, String) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewShouldChangeTextInRangeReplacementText, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didChangeBlock: ((UITextView)->())? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewDidChangeKey) as? ((UITextView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewDidChangeKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var didChangeSelectionBlock: ((UITextView)->())? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewDidChangeSelectionKey) as? ((UITextView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewDidChangeSelectionKey, value, .OBJC_ASSOCIATION_COPY);
}
}
@available(iOS 10.0, *)
fileprivate var shouldInteractWithURLCharacterRangeInteractionBlock: ((UITextView, URL, NSRange, UITextItemInteraction)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewshouldInteractWithURLCharacterRangeInteraction) as? ((UITextView, URL, NSRange, UITextItemInteraction) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewshouldInteractWithURLCharacterRangeInteraction, value, .OBJC_ASSOCIATION_COPY);
}
}
@available(iOS 10.0, *)
fileprivate var shouldInteractWithTextAttachmentCharacterRangeInteractionBlock: ((UITextView, NSTextAttachment, NSRange, UITextItemInteraction)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewShouldInteractWithTextAttachmentCharacterRangeInteraction) as? ((UITextView, NSTextAttachment, NSRange, UITextItemInteraction) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewShouldInteractWithTextAttachmentCharacterRangeInteraction, value, .OBJC_ASSOCIATION_COPY);
}
}
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead")
fileprivate var shouldInteractWithURLcharacterRangeBlock: ((UITextView, URL, NSRange)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewshouldInteractWithURLcharacterRange) as? ((UITextView, URL, NSRange) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewshouldInteractWithURLcharacterRange, value, .OBJC_ASSOCIATION_COPY);
}
}
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithTextAttachment:inRange:forInteractionType: instead")
fileprivate var shouldInteractWithTextAttachmentCharacterRangeBlock: ((UITextView, NSTextAttachment, NSRange)->(Bool))? {
get {
return objc_getAssociatedObject(self, &TextViewKey.UITextViewShouldInteractWithTextAttachmentCharacterRange) as? ((UITextView, NSTextAttachment, NSRange) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &TextViewKey.UITextViewShouldInteractWithTextAttachmentCharacterRange, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate func setDelegate() {
if delegate == nil || delegate?.isEqual(self) == false {
delegate = self
}
}
}
// MARK: - Public Method
extension UITextView {
public func setShouldBegindEditingBlock(_ handler: @escaping((UITextView)->(Bool))) {
shouldBegindEditingBlock = handler
}
public func setShouldEndEditingBlock(_ handler: @escaping((UITextView)->(Bool))) {
shouldEndEditingBlock = handler
}
public func setDidBeginEditingBlock(_ handler: @escaping((UITextView)->())) {
didBeginEditingBlock = handler
}
public func setDidEndEditingBlock(_ handler: @escaping((UITextView)->())) {
didEndEditingBlock = handler
}
public func setShouldChangeTextInRangeReplacementTextBlock(_ handler: @escaping((UITextView, NSRange, String)->(Bool))) {
shouldChangeTextInRangeReplacementTextBlock = handler
}
public func setDidChangeBlock(_ handler: @escaping((UITextView)->())) {
didChangeBlock = handler
}
public func setDidChangeSelectionBlock(_ handler: @escaping((UITextView)->())) {
didChangeSelectionBlock = handler
}
@available(iOS 10.0, *)
public func setShouldInteractWithURLCharacterRangeInteractionBlock(_ handler: @escaping((UITextView, URL, NSRange, UITextItemInteraction)->(Bool))) {
shouldInteractWithURLCharacterRangeInteractionBlock = handler
}
@available(iOS 10.0, *)
public func setShouldInteractWithTextAttachmentCharacterRangeInteractionBlock(_ handler: @escaping((UITextView, NSTextAttachment, NSRange, UITextItemInteraction)->(Bool))) {
shouldInteractWithTextAttachmentCharacterRangeInteractionBlock = handler
}
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead")
public func setShouldInteractWithURLcharacterRangeBlock(_ handler: @escaping((UITextView, URL, NSRange)->(Bool))) {
shouldInteractWithURLcharacterRangeBlock = handler
}
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithTextAttachment:inRange:forInteractionType: instead")
public func setShouldInteractWithTextAttachmentCharacterRangeBlock(_ handler: @escaping((UITextView, NSTextAttachment, NSRange)->(Bool))) {
shouldInteractWithTextAttachmentCharacterRangeBlock = handler
}
}
extension UITextView: UITextViewDelegate {
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
if let block = shouldBegindEditingBlock {
return block(textView)
}
return true
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
if let block = shouldEndEditingBlock {
return block(textView)
}
return true
}
public func textViewDidBeginEditing(_ textView: UITextView) {
didBeginEditingBlock?(textView)
}
public func textViewDidEndEditing(_ textView: UITextView) {
didEndEditingBlock?(textView)
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let block = shouldChangeTextInRangeReplacementTextBlock {
return block(textView, range, text)
}
return true
}
public func textViewDidChange(_ textView: UITextView) {
didChangeBlock?(textView)
}
public func textViewDidChangeSelection(_ textView: UITextView) {
didChangeSelectionBlock?(textView)
}
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead")
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if let block = shouldInteractWithURLcharacterRangeBlock {
return block(textView, URL, characterRange)
}
return true
}
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithTextAttachment:inRange:forInteractionType: instead")
public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
if let block = shouldInteractWithTextAttachmentCharacterRangeBlock {
return block(textView, textAttachment, characterRange)
}
return true
}
@available(iOS 10.0, *)
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if let block = shouldInteractWithURLCharacterRangeInteractionBlock {
return block(textView, URL, characterRange, interaction)
}
return true
}
@available(iOS 10.0, *)
public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if let block = shouldInteractWithTextAttachmentCharacterRangeInteractionBlock {
return block(textView, textAttachment, characterRange, interaction)
}
return true
}
}
<file_sep>//
// SheetTableVC.swift
// Example
//
// Created by senyuhao on 2018/7/4.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
class SheetTableVC: UITableViewController {
var items = ["Sheet-normal", "Sheet-title", "Sheet-message", "Sheet-message-title", "Sheet-destructive"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
SheetTool.shared.show(cancel: "取消", titles: ["2", "1"], target: view) { tag in
print(tag)
}
} else if indexPath.row == 1 {
SheetTool.shared.show(value: (title: "提示", message: nil), cancel: "取消", titles: ["2", "1"], target: view) { tag in
print(tag)
}
} else if indexPath.row == 2 {
SheetTool.shared.show(value: (title: nil, message: "infomessage"), cancel: "取消", titles: ["2", "1"], target: view) { tag in
print(tag)
let alertinfo = AlertInfo(sure: "确定", targetView: self.view)
Alert.shared.show(info: alertinfo, handler: { value in
print(value)
})
}
} else if indexPath.row == 3 {
SheetTool.shared.show(value: (title: "提示", message: "infomessage"), cancel: "取消", titles: ["2", "1"], target: view) { tag in
print(tag)
}
} else if indexPath.row == 4 {
SheetTool.shared.show(value: (title: "提示", message: nil, destructive: "退出登录"), cancel: "取消", titles: [], target: view) {
print($0)
}
}
}
}
<file_sep>//
// DDPhotoPickerCell.swift
// Photo
//
// Created by USER on 2018/10/24.
// Copyright © 2018年 leo. All rights reserved.
//
import UIKit
import Photos
class DDPhotoPickerCell: UICollectionViewCell {
private var requestId: PHImageRequestID?
private lazy var selectCircle: UILabel = {
let selectCircle = UILabel()
selectCircle.layer.borderWidth = 1
selectCircle.layer.borderColor = UIColor.white.cgColor
selectCircle.layer.backgroundColor = normalBackBtnColor.cgColor
selectCircle.layer.cornerRadius = 11
selectCircle.layer.masksToBounds = true
selectCircle.isUserInteractionEnabled = true
selectCircle.textColor = UIColor.white
selectCircle.font = UIFont.systemFont(ofSize: 13)
selectCircle.textAlignment = .center
let tap = UITapGestureRecognizer(target: self, action: #selector(tapGesture(_:)))
selectCircle.addGestureRecognizer(tap)
return selectCircle
}()
private lazy var gifLab: UILabel = {
let gifLab = UILabel()
gifLab.textColor = UIColor.white
gifLab.font = UIFont.systemFont(ofSize: 13)
gifLab.text = "GIF"
gifLab.textAlignment = .center
return gifLab
}()
lazy var photoImageView: UIImageView = {
let imageView = UIImageView()
imageView.frame = self.contentView.bounds
imageView.contentMode = .scaleAspectFill
imageView.isUserInteractionEnabled = true
imageView.clipsToBounds = true
return imageView
}()
lazy var VideoImageView: UIImageView = {
let VideoImageView = UIImageView()
VideoImageView.contentMode = .scaleAspectFill
if let path = Bundle(for: DDPhotoPickerCell.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "zl_video", in: bundle, compatibleWith: nil)
{
VideoImageView.image = image
}
return VideoImageView
}()
lazy var durationLab: UILabel = {
let durationLab = UILabel()
durationLab.textColor = UIColor.white
durationLab.font = UIFont.systemFont(ofSize: 13)
durationLab.textAlignment = .right
return durationLab
}()
//当前cell的indexpath
private var indexPath: IndexPath?
//model
private var model: DDPhotoGridCellModel?
private var selectButtonCallBack: ((_ indexPath: IndexPath) -> ())?
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(photoImageView)
contentView.addSubview(selectCircle)
contentView.addSubview(gifLab)
contentView.addSubview(VideoImageView)
contentView.addSubview(durationLab)
selectCircle.snp.makeConstraints { (make) in
make.width.height.equalTo(22)
make.right.equalTo(self.snp.right).offset(-3)
make.top.equalTo(self.snp.top).offset(3)
}
gifLab.snp.makeConstraints { (make) in
make.left.bottom.equalTo(contentView)
}
VideoImageView.snp.makeConstraints { (make) in
make.left.equalTo(contentView).offset(7)
make.bottom.equalTo(contentView).offset(-7)
make.width.equalTo(16)
make.height.equalTo(12)
}
durationLab.snp.makeConstraints { (make) in
make.left.equalTo(VideoImageView.snp.right).offset(12)
make.right.equalTo(contentView).offset(-5)
make.centerY.equalTo(VideoImageView.snp.centerY)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DDPhotoPickerCell {
public func displayCellWithModel(model: DDPhotoGridCellModel, indexPath: IndexPath, selectedCallBack:@escaping (_ indexPath: IndexPath)->()) {
self.indexPath = indexPath
selectButtonCallBack = selectedCallBack
self.model = model
gifLab.isHidden = true
VideoImageView.isHidden = true
durationLab.isHidden = true
if model.type == .gif {
gifLab.isHidden = false
} else if model.type == .video {
VideoImageView.isHidden = false
durationLab.isHidden = false
durationLab.text = model.duration
}
//设置按钮背景图片
changeSelectCircle(model.isSelected, text: "\(model.index)")
if let id = requestId {
if id > 0 {
DDPhotoImageManager.default().cancelImageRequest(id)
}
}
requestId = DDPhotoPickerSource.imageFromPHImageManager(model) {[weak self] (image) in
self?.photoImageView.image = image
}
}
public func changeSelectCircle(_ res: Bool? = false, text: String? = "") {
if res == true {
if let color = DDPhotoStyleConfig.shared.seletedImageCircleColor {
selectCircle.layer.borderColor = color.cgColor
selectCircle.layer.backgroundColor = color.cgColor
} else {
selectCircle.layer.borderColor = selectedBackBtnColor.cgColor
selectCircle.layer.backgroundColor = selectedBackBtnColor.cgColor
}
selectCircle.text = text
} else {
selectCircle.layer.borderColor = UIColor.white.cgColor
selectCircle.layer.backgroundColor = normalBackBtnColor.cgColor
selectCircle.text = ""
}
}
}
private extension DDPhotoPickerCell {
@objc func tapGesture(_ tap: UIGestureRecognizer) {
if let callBack = selectButtonCallBack,
let indexPath = indexPath {
callBack(indexPath)
}
}
}
<file_sep>//
// Bundle+Localized.swift
// DDCustomCameraDemo
//
// Created by weiwei.li on 2019/1/4.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
extension Bundle {
public static func localizedString(_ key: String, value: String? = nil) -> String {
let language = getLanguageFromSystem()
let bundlePath = getBundle().path(forResource: language, ofType: "lproj")
let bundle = Bundle(path: bundlePath ?? "")
let newValue = bundle?.localizedString(forKey: key, value: value, table: nil)
let result = Bundle.main.localizedString(forKey: key, value: newValue, table: nil)
return result
}
fileprivate static func getBundle() -> Bundle {
if let path = Bundle(for: DDPhotoPickerManager.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path)
{
return bundle
}
return Bundle.main
}
fileprivate static func getLanguageFromSystem() -> String {
var language = Locale.preferredLanguages.first as NSString?
if language?.hasPrefix("en") == true {
language = "en"
} else if language?.hasPrefix("zh") == true {
if language?.range(of: "Hans").location != NSNotFound {
language = "zh-Hans"; // 简体中文
} else {
language = "zh-Hant"; // 繁體中文
}
} else {
language = "zh-Hans"
}
return (language as String?) ?? "zh-Hans"
}
}
<file_sep>//
// DDPhotoPickerViewController.swift
// Photo
//
// Created by USER on 2018/10/24.
// Copyright © 2018年 leo. All rights reserved.
//
import UIKit
import Photos
import SnapKit
private let cellIdentifier = "PhotoCollectionCell"
public enum DDPhotoPickerAssetType: Int {
case imageOnly
case videoOnly
case all
}
class DDPhotoPickerViewController: UIViewController {
private var currentFetchResult: PHFetchResult<PHAsset>?
private lazy var bottomView = DDPhotoPickerBottomView(frame: CGRect.zero, leftBtnCallBack: {[weak self] in
//预览按钮
if self?.photoPickerSource.selectedPhotosArr.count == 0 {
DDPhotoToast.showToast(msg: Bundle.localizedString("请选择图片预览"))
return
}
self?.gotoBorwserVC(.preview, index: 0)
}) { [weak self] in
//完成按钮
if let completion = self?.completion {
completion(self?.photoPickerSource.selectedPhotosArr ?? [])
}
if self?.isFromDDCustomCameraPresent == true {
var vc: UIViewController? = self
while(vc?.presentingViewController != nil) {
vc = vc?.presentingViewController
}
vc?.dismiss(animated: true, completion: nil)
return
}
self?.dismiss(animated: true, completion: nil)
}
//为了适配iphonex以上机型,下边空白问题
private let bottomContainer = UIView(frame: CGRect.zero)
private lazy var photoCollectionView: UICollectionView = { [weak self] in
// 竖屏时每行显示4张图片
let shape: CGFloat = 3
let cellWidth: CGFloat = (DDPhotoScreenWidth - 5 * shape) / 4
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: DDPhotoNavigationTotalHeight, left: shape, bottom: DDPhotoHomeBarHeight, right: shape)
flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
flowLayout.minimumLineSpacing = shape
flowLayout.minimumInteritemSpacing = shape
// collectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
collectionView.backgroundColor = UIColor.white
collectionView.scrollIndicatorInsets = UIEdgeInsets(top: DDPhotoNavigationTotalHeight, left: 0, bottom: DDPhotoHomeBarHeight, right: 0)
// 添加协议方法
collectionView.delegate = self
collectionView.dataSource = self
collectionView.alwaysBounceVertical = true //数量不够一个屏幕时能够拖拽
// 设置 cell
collectionView.register(DDPhotoPickerCell.self, forCellWithReuseIdentifier: cellIdentifier)
collectionView.register(DDPhotoPickerTakePicCell.self,
forCellWithReuseIdentifier: "DDPhotoPickerTakePicCell")
return collectionView
}()
//数据源
private lazy var photoPickerSource = DDPhotoPickerSource()
//选择相册类型
public var photoAssetType:DDPhotoPickerAssetType = .all
//最大选择数量
public var maxSelectedNumber: Int = 1
//完成回调
public var completion: ((_ selectedArr: [DDPhotoGridCellModel]) -> ())?
//当前对象是否是从DDCustomCamera present呈现
public var isFromDDCustomCameraPresent: Bool = false
//是否支持录制视屏
public var isEnableRecordVideo: Bool = true
//是否支持拍照
public var isEnableTakePhoto: Bool = true
//最大录制时长
public var maxRecordDuration: Int = 15
//是否获取限制区域中的图片
public var isShowClipperView: Bool = false
private let cameraManager = DDCustomCameraManager()
//构造方法
public init(assetType: DDPhotoPickerAssetType, maxSelectedNumber: Int, completion: @escaping (_ selectedArr: [DDPhotoGridCellModel]?) -> ()) {
super.init(nibName: nil, bundle: nil)
self.maxSelectedNumber = maxSelectedNumber
self.completion = completion
photoAssetType = assetType
loadLibraryData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
//监控相册的变化
PHPhotoLibrary.shared().register(self)
//添加右滑手势
let screenEdgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(screenHanlePan(pan:)))
screenEdgePan.edges = .left
view.addGestureRecognizer(screenEdgePan)
// navigationController?.navigationBar.barStyle = .black
}
@objc func screenHanlePan(pan: UIPanGestureRecognizer) {
dismiss(animated: true, completion: nil)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var inset = UIEdgeInsetsMake(0, 0, 0, 0);
if #available(iOS 11.0, *) {
inset = view.safeAreaInsets
}
bottomContainer.backgroundColor = UIColor(red: 25.0/255.0, green: 25.0/255.0, blue: 25.0/255.0, alpha: 1)
bottomContainer.snp.makeConstraints { (make) in
make.left.right.equalTo(view)
make.height.equalTo(DDPhotoPickerBottomViewHeight + inset.bottom)
make.bottom.equalTo(view)
}
bottomView.snp.makeConstraints { (make) in
make.left.equalTo(bottomContainer)
make.right.equalTo(bottomContainer)
make.height.equalTo(DDPhotoPickerBottomViewHeight)
make.top.equalTo(bottomContainer)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DDLandscapeManager.shared.isForceLandscape = false
navigationController?.setNavigationBarHidden(false, animated: false)
photoCollectionView.reloadData()
//更新bottom button状态
bottomView.didChangeButtonStatus(count: photoPickerSource.selectedPhotosArr.count)
}
}
//MARK -- PHPhotoLibraryChangeObserver
extension DDPhotoPickerViewController: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
guard let currentFetchResult = currentFetchResult,
let collectionChanges = changeInstance.changeDetails(for: currentFetchResult) else {
return
}
DispatchQueue.main.async {
//重新设置数据源
let fetchAssets = collectionChanges.fetchResultAfterChanges
self.currentFetchResult = fetchAssets
//将所有PHAsset存入数据源
let tmpPHAssets = fetchAssets.objects(at: IndexSet.init(integersIn: 0..<fetchAssets.count))
//设置cell数据源
self.setAllCellModel(assets: tmpPHAssets)
//刷新collection
self.reloadCollectionView()
}
}
}
//MARK --- UICollectionViewDelegate & UICollectionViewDataSource
extension DDPhotoPickerViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoPickerSource.modelsArr.count + 1
}
private func takePic() {
if isFromDDCustomCameraPresent == true {
dismiss(animated: true, completion: nil)
return
}
cameraManager.isFromDDPhotoPickerPresent = true
cameraManager.presentCameraController()
cameraManager.completionBack = {[weak self] (arr) in
let result = arr?.map({ (model) -> DDPhotoGridCellModel in
guard let asset = model.asset else {
return DDPhotoGridCellModel(asset: PHAsset(), type: .unknown, duration: "")
}
var type:DDAssetMediaType = .unknown
switch asset.mediaType {
case .unknown:
type = .unknown
case .image:
type = .image
case .video:
type = .video
default:
type = .unknown
}
let cellModel = DDPhotoGridCellModel(asset: asset, type: type, duration: model.duration ?? "")
cellModel.image = model.image
return cellModel
})
self?.completion?(result ?? [])
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 设置拍照cell
if indexPath.row >= photoPickerSource.modelsArr.count {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DDPhotoPickerTakePicCell", for: indexPath) as! DDPhotoPickerTakePicCell
cell.takePicCallBack = {[weak self] in
self?.takePic()
}
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! DDPhotoPickerCell
cell.displayCellWithModel(model: photoPickerSource.modelsArr[indexPath.row], indexPath: indexPath) {[weak self] (index: IndexPath) in
//大于规定选中的数量,不能选中
let selectedCount = self?.photoPickerSource.selectedPhotosArr.count ?? 9
let maxCount = self?.maxSelectedNumber ?? Int.max
let cellModel = self?.photoPickerSource.modelsArr[index.row]
//1.如果数量大于最大,且没有选中的图片,就不能选中。
if (selectedCount >= maxCount){
//2. 如果数量大于最大,当前图片是选中状态,需要改变状态
if cellModel?.isSelected == true {
self?.selectedBtnChangedCellModel(indexPath: index)
self?.photoCollectionView.reloadData()
return
}
DDPhotoToast.showToast(msg: Bundle.localizedString("最多只能选择") + "\(maxCount)" + Bundle.localizedString("张图片"))
return
}
self?.selectedBtnChangedCellModel(indexPath: index)
self?.photoCollectionView.reloadData()
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.row >= photoPickerSource.modelsArr.count {
return
}
gotoBorwserVC(.all, index: indexPath.row)
}
}
//MARK --- private method
private extension DDPhotoPickerViewController {
/// 跳转预览控制器
///
/// - Parameter type: 选择类型
func gotoBorwserVC(_ type: DDPhotoPickerBorwserType, index: Int) {
let vc = DDPhotoPickerBorwserController()
if type == .preview {
//预览时初始化预览数组
photoPickerSource.getPreviewPhotosArr()
}
vc.photoPickerSource = photoPickerSource
vc.currentIndex = index
vc.borwserType = type
vc.maxSelectedNumber = maxSelectedNumber
navigationController?.pushViewController(vc, animated: true)
}
//选中按钮回调,改变model状态
func selectedBtnChangedCellModel(indexPath: IndexPath) {
photoPickerSource.selectedBtnChangedCellModel(index: indexPath.row)
//更新bottom button状态
bottomView.didChangeButtonStatus(count: photoPickerSource.selectedPhotosArr.count)
}
//加载所有的图片资源
func loadLibraryData() {
//获取相册授权状态
let status = PHPhotoLibrary.authorizationStatus()
if status == .restricted || status == .denied {
dismiss(animated: true, completion: nil)
return
}
DispatchQueue.global(qos: .userInteractive).async {
//获取所有系统图片信息集合体
let allOptions = PHFetchOptions()
allOptions.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: true)]
if self.photoAssetType == .imageOnly {
allOptions.predicate = NSPredicate(format: "mediaType == %d", Int8(PHAssetMediaType.image.rawValue))
} else if self.photoAssetType == .videoOnly {
allOptions.predicate = NSPredicate(format: "mediaType == %d", Int8(PHAssetMediaType.video.rawValue))
}
// else if self.photoAssetType == .audioOnly {
// allOptions.predicate = NSPredicate(format: "mediaType == %d", Int8(PHAssetMediaType.audio.rawValue))
// }
//将集合拆散开
let fetchAssets = PHAsset.fetchAssets(with: allOptions)
self.currentFetchResult = fetchAssets
//将所有PHAsset存入数据源
let tmpPHAssets = fetchAssets.objects(at: IndexSet.init(integersIn: 0..<fetchAssets.count))
//设置cell数据源
self.setAllCellModel(assets: tmpPHAssets)
//刷新collection
self.reloadCollectionView()
}
}
//设置所有cell数据源
func setAllCellModel(assets: [PHAsset]) {
//清除所有数据
photoPickerSource.modelsArr.removeAll()
photoPickerSource.previewPhotosArr.removeAll()
photoPickerSource.selectedPhotosArr.removeAll()
//遍历创建数据
_ = assets.map({ [weak self] (asset) -> Void in
let type = DDPhotoImageManager.transformAssetType(asset)
let duratiom = DDPhotoImageManager.getVideoDuration(asset)
let model = DDPhotoGridCellModel(asset: asset, type: type, duration: duratiom)
self?.photoPickerSource.modelsArr.append(model)
})
}
//reload collection
func reloadCollectionView() {
DispatchQueue.main.async {
//初始化底部栏状态
self.bottomView.didChangeButtonStatus(count: 0)
self.photoCollectionView.reloadData()
//默认滚动到最后
if self.photoPickerSource.modelsArr.count == 0 {
return
}
let index = self.photoPickerSource.modelsArr.count - 1
self.photoCollectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredVertically, animated: false)
}
}
func setLeftBtnItem() {
let btn = UIButton(type: .custom)
btn.bounds = CGRect(x: 0, y: 0, width: 30, height: 21)
if let image = DDPhotoStyleConfig.shared.navigationBackImage {
btn.setImage(image, for: .normal)
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
} else {
if let path = Bundle(for: DDPhotoPickerViewController.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "photo_nav_icon_back_black", in: bundle, compatibleWith: nil)
{
btn.setImage(image, for: .normal)
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
}
}
btn.addTarget(self, action: #selector(leftBtnAction), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
}
@objc func leftBtnAction() {
dismiss(animated: true, completion: nil)
}
func setupUI() {
view.backgroundColor = UIColor.white
title = Bundle.localizedString("图片")
//设置返回按钮
setLeftBtnItem()
//添加cellectionview
view.addSubview(photoCollectionView)
//添加bottom
view.addSubview(bottomContainer)
bottomContainer.addSubview(bottomView)
photoCollectionView.snp.makeConstraints { (make) in
make.left.right.equalTo(self.view)
make.top.equalTo(self.view)
make.bottom.equalTo(self.bottomView.snp.top).offset(-5)
}
if #available(iOS 11.0, *) {
photoCollectionView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
}
}
<file_sep>//
// DDPhotoPickerManager.swift
// Photo
//
// Created by USER on 2018/10/25.
// Copyright © 2018年 leo. All rights reserved.
//
import UIKit
import Photos
//import DDKit
public class DDPhotoPickerManager: NSObject {
//当前对象是否是从DDCustomCamera present呈现,外界禁止调用禁止设置此值
var isFromDDCustomCameraPresent: Bool = false
}
// MARK: - 类方法调用
extension DDPhotoPickerManager {
//入口
public static func show(finishedHandler:@escaping ([DDPhotoGridCellModel]?)->()) {
let manager = DDPhotoPickerManager()
manager.presentImagePickerController(finishedHandler: finishedHandler)
}
/// 预览选择上传的资源
///
/// - Parameter uploadPhotoSource: 要预览的资源文件
public static func showUploadBrowserController(uploadPhotoSource: [PHAsset], seletedIndex: Int) {
let manager = DDPhotoPickerManager()
manager.showUploadBrowser(uploadPhotoSource: uploadPhotoSource, seletedIndex: seletedIndex)
}
}
// MARK: - 私有方法
extension DDPhotoPickerManager {
/// 预览选择上传的资源
///
/// - Parameter uploadPhotoSource: 要预览的资源文件
public func showUploadBrowser(uploadPhotoSource: [PHAsset], seletedIndex: Int) {
//遍历创建数据
let arr = uploadPhotoSource.map({ (asset) -> DDPhotoGridCellModel in
let type = DDPhotoImageManager.transformAssetType(asset)
let duratiom = DDPhotoImageManager.getVideoDuration(asset)
let model = DDPhotoGridCellModel(asset: asset, type: type, duration: duratiom)
return model
})
let vc = DDPhotoUploadBrowserController()
vc.photoArr = arr
vc.currentIndex = seletedIndex
if getTopViewController?.navigationController == nil {
getTopViewController?.present(vc, animated: true, completion: nil)
return
}
getTopViewController?.navigationController?.pushViewController(vc, animated: true)
}
/// 显示图片选择控制器
///
/// - Parameter finishedHandler: 完成回调
public func presentImagePickerController(finishedHandler:@escaping ([DDPhotoGridCellModel]?)->()) {
DDCustomCameraManager.authorizePhoto { (res) in
if res == false {
DDPhotoPickerManager.showAlert(DDPhotoStyleConfig.shared.photoPermission)
return
}
//类方法不会循环引用,不能设为weak,否则self为空
self.presentVC(finishedHandler: finishedHandler)
}
}
private func presentVC(finishedHandler:@escaping ([DDPhotoGridCellModel]?)->()) {
if isHavePhotoLibraryAuthority() == false {
return
}
//已经授权通过,获取当前controller
guard let vc = getTopViewController else {
print("未获取presentController")
return
}
//present picker controller
let pickerVC = DDPhotoPickerViewController(assetType: DDPhotoStyleConfig.shared.photoAssetType, maxSelectedNumber: DDPhotoStyleConfig.shared.maxSelectedNumber) {(selectedArr) in
guard let arr = selectedArr else {
finishedHandler(nil)
return
}
for cellModel in arr {
_ = DDPhotoImageManager.default().requestTargetImage(for: cellModel.asset, targetSize: CGSize(width: 150, height: 150), resultHandler: { (image, dic) in
cellModel.image = image
})
}
//回调
finishedHandler(arr)
}
//清空gif缓存
DDPhotoImageManager.default().removeAllCache()
let nav = DDPhotoPickerNavigationController(rootViewController: pickerVC)
nav.previousStatusBarStyle = UIApplication.shared.statusBarStyle
pickerVC.isFromDDCustomCameraPresent = isFromDDCustomCameraPresent
pickerVC.isEnableRecordVideo = DDPhotoStyleConfig.shared.isEnableRecordVideo
pickerVC.isEnableTakePhoto = DDPhotoStyleConfig.shared.isEnableTakePhoto
pickerVC.maxSelectedNumber = DDPhotoStyleConfig.shared.maxSelectedNumber
pickerVC.maxRecordDuration = DDPhotoStyleConfig.shared.maxRecordDuration
pickerVC.isShowClipperView = DDPhotoStyleConfig.shared.isShowClipperView
vc.present(nav, animated: true, completion: nil)
}
static func showAlert(_ content: String) {
if DDPhotoStyleConfig.shared.isEnableDDKitHud == false {
//弹窗提示
let alertVC = UIAlertController(title: "温馨提示", message: content, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .default) { (action) in
}
let actionCommit = UIAlertAction(title: "去设置", style: .default) { (action) in
//去设置
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
alertVC.addAction(cancelAction)
alertVC.addAction(actionCommit)
TopViewController().getTopViewController?.present(alertVC, animated: true, completion: nil)
} else {
guard let window = UIApplication.shared.keyWindow else {
return
}
let info = AlertInfo(title: Bundle.localizedString("温馨提示"),
subTitle: nil,
needInput: nil,
cancel: Bundle.localizedString("取消"),
sure: Bundle.localizedString("去设置"),
content: content,
targetView: window)
Alert.shared.show(info: info) { (tag) in
if tag == 0 {
return
}
//去设置
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
}
}
}
private extension DDPhotoPickerManager {
var getTopViewController: UIViewController? {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
return getTopViewController(viewController: rootViewController)
}
func getTopViewController(viewController: UIViewController?) -> UIViewController? {
if let presentedViewController = viewController?.presentedViewController {
return getTopViewController(viewController: presentedViewController)
}
if let tabBarController = viewController as? UITabBarController,
let selectViewController = tabBarController.selectedViewController {
return getTopViewController(viewController: selectViewController)
}
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return getTopViewController(viewController: visibleViewController)
}
if let pageViewController = viewController as? UIPageViewController,
pageViewController.viewControllers?.count == 1 {
return getTopViewController(viewController: pageViewController.viewControllers?.first)
}
for subView in viewController?.view.subviews ?? [] {
if let childViewController = subView.next as? UIViewController {
return getTopViewController(viewController: childViewController)
}
}
return viewController
}
/// 是否有相册访问权限
///
/// - Returns: bool
func isHavePhotoLibraryAuthority() -> Bool {
let status = PHPhotoLibrary.authorizationStatus()
if status == .authorized {
return true
}
return false
}
}
<file_sep>//
// BrowserController.swift
// Example
//
// Created by USER on 2018/11/26.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
import DDKit
import Kingfisher
class BrowserController: UIViewController {
let imageViewA = UIImageView()
let imageViewB = UIImageView()
let imageViewC = UIImageView()
let imageViewD = UIImageView()
let imageViewE = UIImageView()
let imageViewF = UIImageView()
var browser: DDPhotoBrower?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// Do any additional setup after loading the view.
setupUI()
}
func setupUI() {
imageViewA.isUserInteractionEnabled = true
imageViewB.isUserInteractionEnabled = true
imageViewC.isUserInteractionEnabled = true
imageViewD.isUserInteractionEnabled = true
imageViewE.isUserInteractionEnabled = true
imageViewF.isUserInteractionEnabled = true
let tap1 = UITapGestureRecognizer(target: self, action: #selector(tagAGesture))
imageViewA.addGestureRecognizer(tap1)
view.addSubview(imageViewA)
view.addSubview(imageViewB)
view.addSubview(imageViewC)
view.addSubview(imageViewD)
view.addSubview(imageViewE)
view.addSubview(imageViewF)
imageViewA.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(100)
make.width.height.equalTo(80)
}
imageViewB.snp.makeConstraints { (make) in
make.left.equalTo(imageViewA.snp.right).offset(20)
make.top.equalTo(100)
make.width.height.equalTo(80)
}
imageViewC.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(imageViewA.snp.bottom).offset(20)
make.width.height.equalTo(80)
}
imageViewD.snp.makeConstraints { (make) in
make.left.equalTo(imageViewC.snp.right).offset(20)
make.top.equalTo(imageViewB.snp.bottom).offset(20)
make.width.height.equalTo(80)
}
imageViewE.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(imageViewC.snp.bottom).offset(20)
make.width.height.equalTo(80)
}
imageViewF.snp.makeConstraints { (make) in
make.left.equalTo(imageViewE.snp.right).offset(20)
make.top.equalTo(imageViewD.snp.bottom).offset(20)
make.width.height.equalTo(80)
}
// let url1 = URL(string: "https://i2.hoopchina.com.cn/hupuapp/bbs/180015943752119/thread_180015943752119_20181123173449_s_5063176_w_357_h_345_28251.gif")
let url1 = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056077048&di=e67f672075c673e6ffaa0625564133e7&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201406%2F12%2F20140612211118_YYXAC.jpeg")
imageViewA.kf.setImage(with: url1)
let url2 = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056077048&di=e67f672075c673e6ffaa0625564133e7&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201406%2F12%2F20140612211118_YYXAC.jpeg")
imageViewB.kf.setImage(with: url2)
let url3 = URL(string: "http://img1.mydrivers.com/img/20171008/s_da7893ed38074cbc994e0ff3d85adeb5.jpg")
imageViewC.kf.setImage(with: url3)
let url4 = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056728983&di=0377ea3d0ef5acdefe8863c1657a67f4&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e90159a5094ba801211d25bec351.jpg")
imageViewD.kf.setImage(with: url4)
let url5 = URL(string: "https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2908508425,3257588227&fm=173&s=F1925395C88BA20F313898C3030040B3&w=100&h=100&img.JPEG")
imageViewE.kf.setImage(with: url5)
let url6 = URL(string: "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=137597753,3924281842&fm=173&s=E109D719483A6B9EB6ACCD5E0300F030&w=100&h=100&img.JPEG")
imageViewF.kf.setImage(with: url6)
imageViewA.contentMode = .scaleAspectFit
imageViewB.contentMode = .scaleAspectFit
imageViewC.contentMode = .scaleAspectFit
imageViewD.contentMode = .scaleAspectFit
imageViewF.contentMode = .scaleAspectFit
}
@objc func tagAGesture() {
print("tagAGesture")
var photos = [DDPhoto]()
let photo1 = DDPhoto()
// https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=925649403,644817718&fm=173&s=B084DF15C2206D1DCAA9504B0300E010&w=640&h=1058&img.JPEG
// photo1.url = URL(string: "https://i2.hoopchina.com.cn/hupuapp/bbs/180015943752119/thread_180015943752119_20181123173449_s_5063176_w_357_h_345_28251.gif")
photo1.url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056077048&di=e67f672075c673e6ffaa0625564133e7&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201406%2F12%2F20140612211118_YYXAC.jpeg")
photo1.sourceImageView = imageViewA
let photo2 = DDPhoto()
photo2.url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056077048&di=e67f672075c673e6ffaa0625564133e7&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201406%2F12%2F20140612211118_YYXAC.jpeg")
photo2.sourceImageView = imageViewB
let photo3 = DDPhoto()
photo3.url = URL(string: "http://img1.mydrivers.com/img/20171008/s_da7893ed38074cbc994e0ff3d85adeb5.jpg")
photo3.sourceImageView = imageViewC
let photo4 = DDPhoto()
photo4.url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056728983&di=0377ea3d0ef5acdefe8863c1657a67f4&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e90159a5094ba801211d25bec351.jpg")
photo4.sourceImageView = imageViewD
let photo5 = DDPhoto()
photo5.url = URL(string: "https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2908508425,3257588227&fm=173&s=F1925395C88BA20F313898C3030040B3&w=640&h=1000&img.JPEG")
let photo6 = DDPhoto()
photo6.url = URL(string: "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=137597753,3924281842&fm=173&s=E109D719483A6B9EB6ACCD5E0300F030&w=640&h=1000&img.JPEG")
photos.append(photo1)
photos.append(photo2)
photos.append(photo3)
photos.append(photo4)
photos.append(photo5)
photos.append(photo6)
browser = DDPhotoBrower.photoBrowser(Photos: photos, currentIndex: 0)
browser?.delegate = self
browser?.show()
}
}
extension BrowserController: DDPhotoBrowerDelegate {
func photoBrowser(controller: UIViewController?, didChanged index: Int?) {
// print(controller)
}
func photoBrowser(controller: UIViewController?, willDismiss index: Int?) {
// print(controller)
}
func photoBrowser(controller: UIViewController?, longPress index: Int?) {
// print(controller)
}
}
<file_sep>//
// DDPlayerBrightnessView.swift
// mpdemo
//
// Created by leo on 2018/10/31.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import UIKit
class DDPlayerBrightnessView: UIView {
lazy private var backImage: UIImageView = {
let backImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 79, height: 76))
if let path = Bundle(for: DDPlayerBrightnessView.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "ZFPlayer_brightness", in: bundle, compatibleWith: nil) {
backImage.image = image
}
return backImage
}()
lazy private var titleLab: UILabel = {
let titleLab = UILabel(frame: CGRect(x: 0, y: 5, width: self.bounds.size.width, height: 30))
titleLab.font = UIFont.boldSystemFont(ofSize: 16)
titleLab.textColor = UIColor(red: 0.25, green: 0.22, blue: 0.21, alpha: 1)
titleLab.textAlignment = .center
titleLab.text = "亮度"
return titleLab
}()
lazy private var longView: UIView = {
let longView = UIView(frame: CGRect(x: 13, y: 132, width: self.bounds.size.width - 26, height: 7))
longView.backgroundColor = UIColor(red: 0.25, green: 0.22, blue: 0.21, alpha: 1)
return longView
}()
private var tipArr = [UIImageView]()
private var orientationDidChange = false
override init(frame: CGRect) {
super.init(frame: frame)
self.frame = CGRect(x: DDVPScreenWidth * 0.5, y: DDVPScreenHeight * 0.5, width: 155, height: 155)
layer.cornerRadius = 10
layer.masksToBounds = true
// 使用UIToolbar实现毛玻璃效果,简单粗暴,支持iOS7+
let toolBar: UIToolbar = UIToolbar(frame: self.bounds)
toolBar.alpha = 0.97
addSubview(toolBar)
addSubview(backImage)
addSubview(titleLab)
addSubview(longView)
createTips()
addNotification()
addObserver()
alpha = 0
}
public convenience init() {
self.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
backImage.center = CGPoint(x: 155 * 0.5, y: 155 * 0.5)
center = CGPoint(x: DDVPScreenWidth * 0.5, y: DDVPScreenHeight * 0.5)
}
deinit {
UIScreen.main.removeObserver(self, forKeyPath: "brightness")
NotificationCenter.default.removeObserver(self)
print(self)
}
}
extension DDPlayerBrightnessView {
func addObserver() {
let options = NSKeyValueObservingOptions([.new])
UIScreen.main.addObserver(self, forKeyPath: "brightness", options: options, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let sound = change?[.newKey] as? CGFloat {
appearSoundView()
updateLongView(sound: sound)
}
}
func addNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(updateLayer(notify:)), name: UIDevice.orientationDidChangeNotification, object: nil)
}
@objc func updateLayer(notify: Notification) {
orientationDidChange = true
setNeedsLayout()
layoutIfNeeded()
}
}
extension DDPlayerBrightnessView {
private func createTips() {
let tipW: CGFloat = (longView.bounds.size.width - 17) / 16.0
let tipH: CGFloat = 5.0
let tipY: CGFloat = 1.0
for i in 0..<16 {
let tipX: CGFloat = CGFloat(i) * (tipW + 1.0) + 1.0
let image = UIImageView()
image.backgroundColor = UIColor.white
image.frame = CGRect(x: tipX, y: tipY, width: tipW, height: tipH)
longView.addSubview(image)
tipArr.append(image)
}
updateLongView(sound: UIScreen.main.brightness)
}
private func updateLongView(sound: CGFloat) {
let stage: CGFloat = 1.0 / 15.0
let level = Int(sound / stage)
let count = tipArr.count
for i in 0..<count {
let img = tipArr[i]
if i<=level {
img.isHidden = false
} else {
img.isHidden = true
}
}
}
private func appearSoundView() {
if alpha == 0 {
orientationDidChange = false
alpha = 1
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.disAppearSoundView()
}
}
}
private func disAppearSoundView() {
if alpha == 1 {
UIView.animate(withDuration: 0.8) {
self.alpha = 0.0
}
}
}
}
<file_sep>//
// UITextView+LengthLimit.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
fileprivate let UITextViewDisposebag = DisposeBag()
extension UITextView {
fileprivate struct TextViewMaxLengthKey {
static var kTextViewMaxLengthKey = "kTextViewMaxLengthKey"
}
public var maxLength: Int {
get {
return (objc_getAssociatedObject(self, &TextViewMaxLengthKey.kTextViewMaxLengthKey) as? Int) ?? LONG_MAX
}
set(value) {
var newValue = value
if newValue < 1 {
newValue = LONG_MAX
}
objc_setAssociatedObject(self, &TextViewMaxLengthKey.kTextViewMaxLengthKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// NotificationCenter.default
// .rx.notification(NSNotification.Name.UITextViewTextDidChange)
// .takeUntil(self.rx.deallocated) //页面销毁自动移除通知监听
// .subscribe(onNext: {[weak self] _ in
// self?.textViewTextChanged()
// })
// .disposed(by: UITextViewDisposebag)
self.rx.text.orEmpty
.map {[weak self] (text) -> Bool in
return text.count > self?.maxLength ?? LONG_MAX
}
.share(replay: 1)
.subscribe(onNext: {[weak self] (res) in
if res == true,
let strongSelf = self,
let text = self?.text {
let index = text.index(text.startIndex, offsetBy: strongSelf.maxLength)
self?.text = String(text[..<index])
}
})
.disposed(by: UITextViewDisposebag)
}
}
// fileprivate func textViewTextChanged() {
// let toBeString = self.text as NSString?
// guard let textStr = toBeString else {
// return
// }
//
// if textStr.length == 0 {
// return
// }
// //获取高亮方法
// let selectedRange = self.markedTextRange ?? UITextRange()
// let position = self.position(from: selectedRange.start, offset: 0)
//
// // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
// if position != nil {
// return
// }
// if (textStr.length ) > self.maxLength {
// let rangeIndex = textStr.rangeOfComposedCharacterSequence(at: self.maxLength)
// if rangeIndex.length == 1 {
// self.text = textStr.substring(to: self.maxLength)
// } else {
// let range = textStr.rangeOfComposedCharacterSequences(for: NSRange(location: 0, length: self.maxLength))
// self.text = textStr.substring(with: range)
// }
// }
// }
}
<file_sep>//
// PopViewController.swift
// EatojoyBiz
//
// Created by 胡峰 on 2016/10/31.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
/// PopViewController 弹出样式,效果和 UIAlertController 一致
///
/// - alert: 弹出在屏幕中间
/// - actionSheet: iPhone 上从底部弹出,iPad 上显示会显示为 .popover 样式,必须设置 popoverPresentationController 属性
/// - popover: iPhone 和 iPad 都指向位置弹出,必须设置 popoverPresentationController 属性
/// - actionSheetPad: iPhone iPad 都显示 actionSheet 样式(从底部弹出)
public enum PopControllerStyle: Int {
case alert
case actionSheet
case popover
case actionSheetPad
}
/// 全局弹出窗口,继承 `PopViewController` 以自定义弹出界面,支持 storyboard 中完成界面
///
/// iPhone 和 iPad 所有弹出界面都需要使用此类,不再使用 `UIView.addSubView(:)` 的方式
open class PopViewController: UIViewController, UIViewControllerTransitioningDelegate, UIPopoverPresentationControllerDelegate {
/// 弹出窗口圆角,会自动设置 clipsToBounds = true
var cornerRadius: CGFloat { return 5.0 }
/// 是否允许点击空白区域关闭弹窗
var tapToDismiss: Bool { return true }
/// 弹出方式,效果和 UIAlertController 一致
var style: PopControllerStyle { return .alert }
/// .actionSheet(iPad) 和 .popover 样式需要重新指向位置时的回调,通常在转屏和 SplitView 模式时需要调整
var willRepositionPopover: ((_ popover: PopViewController, _ rect: CGRect, _ view: UIView) -> CGRect)?
// MARK: -
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
if style == .popover || (style == .actionSheet && UIDevice.current.userInterfaceIdiom == .pad) {
modalPresentationStyle = .popover
popoverPresentationController?.delegate = self
} else {
modalPresentationStyle = .custom
transitioningDelegate = self
}
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
override open func viewDidLoad() {
super.viewDidLoad()
view.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
if cornerRadius > 0 {
view.layer.cornerRadius = CGFloat(cornerRadius)
view.clipsToBounds = true
}
let flag = style != .actionSheet || popoverPresentationController?.sourceView != nil || popoverPresentationController?.barButtonItem != nil || UIDevice.current.userInterfaceIdiom == .phone
assert(flag, "PopControllerStyle.actionSheet 方式必须设置 popover 相关的参数,iPad 上需要")
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(false)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Keyboard
private var keyboardFrame: CGRect?
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
if let keyboardFrame = keyboardFrame {
popController?.updateKeyboard(keyboardFrame)
}
}
// MARK: - Delegate
private weak var popController: PopController?
public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let popController = PopController(presentedViewController: presented, presenting: presenting)
popController.tapToDimiss = { [weak self]() -> Bool in
self?.tapToDismiss ?? true
}
self.popController = popController
popController.style = style
if let keyboardFrame = keyboardFrame {
popController.updateKeyboard(keyboardFrame)
}
return popController
}
public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
public func presentationController(_ presentationController: UIPresentationController,
willPresentWithAdaptiveStyle style: UIModalPresentationStyle,
transitionCoordinator: UIViewControllerTransitionCoordinator?) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * 0.1)) / Double(NSEC_PER_SEC)) {
self.popoverPresentationController?.passthroughViews = nil
}
}
public func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController,
willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>,
in view: AutoreleasingUnsafeMutablePointer<UIView>) {
if let willRepositionPopover = willRepositionPopover {
rect.pointee = willRepositionPopover(self, rect.pointee, view.pointee)
} else if let sourceView = popoverPresentationController.sourceView {
let sourceRect = popoverPresentationController.sourceRect
let originRect = sourceView.frame
let xPosition = sourceRect.origin.x / rect.pointee.width
let yPosition = sourceRect.origin.y / rect.pointee.height
let widthP = sourceRect.width / rect.pointee.width
let heightP = sourceRect.height / rect.pointee.height
let newRect = CGRect(x: originRect.width * xPosition, y: originRect.height * yPosition, width: originRect.width * widthP, height: originRect.height * heightP)
popoverPresentationController.sourceRect = newRect
rect.pointee = newRect
}
}
}
<file_sep>//
// Router.swift
// Route
//
// Created by 鞠鹏 on 2018/6/5.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
public enum RouterError: Int {
case routeInvalid
case route404
case urlInvalid
case url404
case unmatch
public static let domain = "RouterErrorDomain"
func error() -> NSError {
switch self {
case .routeInvalid:
return error(info: "Route illegal")
case .route404:
return error(info: "Route is illegal or not registration")
case .urlInvalid:
return error(info: "url invalid")
case .url404:
return error(info: "can not open")
case .unmatch:
return error(info: "No match for the results")
}
}
func error(info: String) -> NSError {
let error = NSError(domain: RouterError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: info])
return error
}
}
public enum Jump: Int {
case push
case present
}
public class Router: NSObject {
public typealias Handler = ((RouterURL) -> UIViewController)
public typealias Completion = (() -> Void)
public static let shareInstance = Router()
public var error: NSError?
// 保存路由模块和模块跳转
private var routerMap = [String: Handler]()
// 获取所以注册路由
public static func allRoutes() -> [String] {
return Array(Router.shareInstance.routerMap.keys)
}
// MARK: - public
/// 注册路由
public static func register(route: String, handler:@escaping Handler) -> NSError? {
return Router.shareInstance.add(route: route, handler: handler)
}
/// 注销路由
public static func deRegister(route: String) {
Router.shareInstance.remove(route: route)
}
// MARK: - private
private func add(route: String, handler:@escaping Handler) -> NSError? {
guard let route = RouterURL.route(urlStr: route) else {
return RouterError.routeInvalid.error()
}
guard URL(string: route) != nil else {
return RouterError.routeInvalid.error()
}
routerMap.updateValue(handler, forKey: route)
return nil
}
private func remove(route: String) {
routerMap.removeValue(forKey: route)
}
private override init() {
}
}
extension Router {
/// push 模块和参数拼接在一起
///
/// paramter: urlStr后面拼接了参数
@discardableResult
public static func push(urlStr: String, animated: Bool = true) -> Router {
return open(urlStr: urlStr, animated: animated, jumpType: .push, completion: nil)
}
/// push 自定义参数
///
/// paramter: route跳转的模块
/// paramter: params
@discardableResult
public static func push(route: String, params: [String: String]?, animated: Bool = true) -> Router {
return open(route: route, params: params, animated: animated, jumpType: .push, completion: nil)
}
/// present 模块和参数拼接在一起
///
/// paramter: urlStr后面拼接了参数
@discardableResult
public static func present(urlStr: String, animated: Bool = true, completion: Completion?) -> Router {
return open(urlStr: urlStr, animated: animated, jumpType: .present, completion: completion)
}
/// present 自定义参数
///
/// paramter: route跳转的模块
/// paramter: params
@discardableResult
public static func present(route: String, params: [String: String]?, animated: Bool = true, completion: Completion?) -> Router {
return open(route: route, params: params, animated: animated, jumpType: .present, completion: completion)
}
static func open(urlStr: String, animated: Bool, jumpType: Jump, completion: Completion?) -> Router {
let router = Router()
guard !urlStr.isEmpty else {
router.error = RouterError.urlInvalid.error()
return router
}
guard let routerURL = RouterURL(urlStr: urlStr) else {
router.error = RouterError.route404.error()
return router
}
let params = routerURL.params as? [String: String]
switch jumpType {
case .push:
return push(route: routerURL.route, params: params, animated: animated)
case .present:
return present(route: routerURL.route, params: params, animated: animated, completion: completion)
}
}
static func open(route: String, params: [String: String]?, animated: Bool, jumpType: Jump, completion: Completion?) -> Router {
let router = Router()
guard let route = RouterURL.route(urlStr: route) else {
router.error = RouterError.route404.error()
return router
}
guard let handler = shareInstance.routerMap[route] else {
router.error = RouterError.route404.error()
return router
}
guard let routerURL = RouterURL(urlStr: route) else {
router.error = RouterError.unmatch.error()
return router
}
routerURL.params = params
let viewController = handler(routerURL)
switch jumpType {
case .push:
pushViewController(viewController: viewController, animated: animated)
return router
case .present:
presentViewController(viewController: viewController, animated: animated, completion: completion)
return router
}
}
}
extension Router {
@discardableResult
static func pushViewController(viewController: UIViewController, animated: Bool) -> UIViewController? {
guard !viewController.isKind(of: UINavigationController.self) else {
return nil
}
guard let navigationController = UIViewController.getTopViewController?.navigationController else {
return nil
}
navigationController.pushViewController(viewController, animated: animated)
return viewController
}
@discardableResult
static func presentViewController(viewController: UIViewController, animated: Bool, completion: Completion?) -> UIViewController? {
guard let fromViewController = UIViewController.getTopViewController else {
return nil
}
fromViewController.present(viewController, animated: true, completion: completion)
return viewController
}
}
<file_sep>//
// UIKitChainableVC.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/8.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class UIKitChainableVC: UIViewController {
@IBOutlet weak var lab: UILabel!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var switchView: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
//UIView 扩展了单击,双击,长按手势
UIView()
// .frame(CGRect(x: 50, y: 400, width: 50, height: 50))
.backgroundColor(UIColor.black)
.sizeFit()
.isUserInteractionEnabled(true)
.addTapGesture { (v, tap) in
print("单击")
}
.addDoubleGesture { (v, tap) in
print("双击")
}
.addLongGesture { (v, long) in
print("长按")
}
.add(to: view)
.makeConstraints { (make) in
make.left.equalTo(50)
make.top.equalTo(500)
make.width.equalTo(50)
make.height.equalTo(50)
}
lab.backgroundColor(UIColor.red)
.alpha(0.4)
.border(UIColor.black, 1)
.textAlignment(.center)
.numberOfLines(0)
.font(12)
.frame(CGRect(x: 50, y: 200, width: 200, height: 100))
.text("收到货方式来开发框架地方sdfkhjjhsjfdkh是否点击康师傅")
.textColor(UIColor.green)
.shadowColor(UIColor.black)
.shadowOffset(CGSize(width: 1, height: 2))
.lineBreakMode(.byCharWrapping)
.attributedText(NSAttributedString(string: "是打飞机了就开始发动机"))
.highlightedTextColor(UIColor.purple)
.isHighlighted(true)
.isUserInteractionEnabled(true)
.isEnabled(true)
.adjustsFontSizeToFitWidth(true)
.minimumScaleFactor(10)
//Button扩展新功能
//imagePosition 任意切换文字和图片混合button的位置
// 提供TargetAction点击事件。目前只提供.touchUpInside
UIButton(type: .system)
.frame(CGRect(x: 150, y: 400, width: 50, height: 50))
.setTitle("按钮", state: .normal)
.setImage(UIImage(named: "nav_icon_back_black"), state: .normal)
.setTitleColor(UIColor.red, state: .normal)
.add(to: view)
.addActionTouchUpInside({ (btn) in
print("sdf ")
})
.font(18)
.image(position: .top, space: 10)
.setBackground(color: UIColor.red, forState: .highlighted)
UIImageView()
.frame(CGRect(x: 250, y: 400, width: 50, height: 50))
.addTapGesture { (v, tap) in
print("图片")
}
.image(UIImage(named: "nav_icon_back_black"))
.add(to: view)
slider
.maximumValue(1.0)
.minimumValue(0)
.value(0)
.maximumTrackTintColor(UIColor.red)
.minimumTrackTintColor(UIColor.blue)
.addAction(events: .valueChanged) {[weak self] (sender) in
print("slider---\(sender.value)")
self?.progressView.setProgress(sender.value, animated: true)
}
switchView
.onTintColor(UIColor.red)
.thumbTintColor(UIColor.black)
.isOn(false)
.addAction(events: .valueChanged) { (s) in
print("switch的值:\(s.isOn)")
}
progressView
.progress(0)
.progressViewStyle(.bar)
.progressTintColor(UIColor.green)
.trackTintColor(UIColor.yellow)
UISegmentedControl(items: ["吕布", "曹操", "白起","程咬金"])
.frame(CGRect(x: 50, y: 320, width: 200, height: 30))
.tintColor(UIColor.red)
.apportionsSegmentWidthsByContent(true)
.selectedSegmentIndex(1)
.addAction(events: .valueChanged) { (sender) in
print("选中了: \(sender.selectedSegmentIndex)")
}
.add(to: view)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
deinit {
print(self)
}
}
extension UIKitChainableVC : UITextFieldDelegate {
// func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
//
// return false
// }
}
<file_sep>
//
// UIScrollView+Blocks.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
extension UIScrollView {
fileprivate struct ScrollViewKey {
static var UIScrollViewScrollViewDidScrollKey = "UIScrollViewScrollViewDidScrollKey"
static var UIScrollViewScrollViewDidZoomKey = "UIScrollViewScrollViewDidZoomKey"
static var UIScrollViewScrollViewWillBeginDraggingKey = "UIScrollViewScrollViewWillBeginDraggingKey"
static var UIScrollViewScrollViewWillEndDraggingWithVelocityTargetContentOffsetKey = "UIScrollViewScrollViewWillEndDraggingWithVelocityTargetContentOffsetKey"
static var UIScrollViewScrollViewDidEndDraggingWillDecelerateKey = "UIScrollViewScrollViewDidEndDraggingWillDecelerateKey"
static var UIScrollViewScrollViewWillBeginDeceleratingKey = "UIScrollViewScrollViewWillBeginDeceleratingKey"
static var UIScrollViewScrollViewDidEndDeceleratingKey = "UIScrollViewScrollViewDidEndDeceleratingKey"
static var UIScrollViewScrollViewDidEndScrollingAnimationKey = "UIScrollViewScrollViewDidEndScrollingAnimationKey"
static var UIScrollViewViewForZoomingKey = "UIScrollViewViewForZoomingKey"
static var UIScrollViewScrollViewWillBeginZoomingKey = "UIScrollViewScrollViewWillBeginZoomingKey"
static var UIScrollViewScrollViewDidEndZoomingKey = "UIScrollViewScrollViewDidEndZoomingKey"
static var UIScrollViewScrollViewShouldScrollToTopKey = "UIScrollViewScrollViewShouldScrollToTopKey"
static var UIScrollViewScrollViewDidScrollToTopKey = "UIScrollViewScrollViewDidScrollToTopKey"
static var UIScrollViewScrollViewDidChangeAdjustedContentInsetKey = "UIScrollViewScrollViewDidChangeAdjustedContentInsetKey"
}
fileprivate var scrollViewDidScrollBlock: ((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidScrollKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidScrollKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewDidZoomBlock: ((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidZoomKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidZoomKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewWillBeginDraggingBlock: ((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillBeginDraggingKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillBeginDraggingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewWillEndDraggingWithVelocityTargetContentOffsetBlock: ((UIScrollView, CGPoint, UnsafeMutablePointer<CGPoint>)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillEndDraggingWithVelocityTargetContentOffsetKey) as? ((UIScrollView, CGPoint, UnsafeMutablePointer<CGPoint>) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillEndDraggingWithVelocityTargetContentOffsetKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewDidEndDraggingWillDecelerateBlock: ((UIScrollView, Bool)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndDraggingWillDecelerateKey) as? ((UIScrollView, Bool) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndDraggingWillDecelerateKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewWillBeginDeceleratingBlock: ((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillBeginDeceleratingKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillBeginDeceleratingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewDidEndDeceleratingBlock: ((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndDeceleratingKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndDeceleratingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewDidEndScrollingAnimationBlock: ((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndScrollingAnimationKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndScrollingAnimationKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var viewForZoomingBlock:((UIScrollView)->(UIView?))? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewViewForZoomingKey) as? ((UIScrollView) -> (UIView?))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewViewForZoomingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewWillBeginZoomingBlock:((UIScrollView, UIView?)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillBeginZoomingKey) as? ((UIScrollView, UIView?) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewWillBeginZoomingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewDidEndZoomingBlock:((UIScrollView, UIView?, CGFloat)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndZoomingKey) as? ((UIScrollView, UIView?, CGFloat) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidEndZoomingKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewShouldScrollToTopBlock:((UIScrollView)->(Bool))? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewShouldScrollToTopKey) as? ((UIScrollView) -> (Bool))
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewShouldScrollToTopKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewDidScrollToTopBlock:((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidScrollToTopKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidScrollToTopKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate var scrollViewDidChangeAdjustedContentInsetBlock:((UIScrollView)->())? {
get {
return objc_getAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidChangeAdjustedContentInsetKey) as? ((UIScrollView) -> ())
}
set(value) {
setDelegate()
objc_setAssociatedObject(self, &ScrollViewKey.UIScrollViewScrollViewDidChangeAdjustedContentInsetKey, value, .OBJC_ASSOCIATION_COPY);
}
}
fileprivate func setDelegate() {
if delegate == nil || delegate?.isEqual(self) == false {
delegate = self
}
}
}
// MARK: - Public method
extension UIScrollView {
public func setScrollViewDidScrollBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewDidScrollBlock = handler
}
public func setScrollViewDidZoomBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewDidZoomBlock = handler
}
public func setScrollViewWillBeginDraggingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewWillBeginDraggingBlock = handler
}
public func setScrollViewWillEndDraggingWithVelocityTargetContentOffsetBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ velocity: CGPoint, _ targetContentOffset: UnsafeMutablePointer<CGPoint>)->())) {
scrollViewWillEndDraggingWithVelocityTargetContentOffsetBlock = handler
}
public func setScrollViewDidEndDraggingWillDecelerateBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ decelerate: Bool)->())) {
scrollViewDidEndDraggingWillDecelerateBlock = handler
}
public func setScrollViewWillBeginDeceleratingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewWillBeginDeceleratingBlock = handler
}
public func setScrollViewDidEndDeceleratingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewDidEndDeceleratingBlock = handler
}
public func setScrollViewDidEndScrollingAnimationBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewDidEndScrollingAnimationBlock = handler
}
public func setViewForZoomingBlock(_ handler: @escaping((_ scrollView: UIScrollView)->(UIView?))) {
viewForZoomingBlock = handler
}
public func setScrollViewWillBeginZoomingBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ view: UIView?)->())) {
scrollViewWillBeginZoomingBlock = handler
}
public func setScrollViewDidEndZoomingBlock(_ handler: @escaping((_ scrollView: UIScrollView, _ view: UIView?, _ scale: CGFloat)->())) {
scrollViewDidEndZoomingBlock = handler
}
public func setScrollViewShouldScrollToTopBlock(_ handler: @escaping((_ scrollView: UIScrollView)->(Bool))) {
scrollViewShouldScrollToTopBlock = handler
}
public func setScrollViewDidScrollToTopBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewDidScrollToTopBlock = handler
}
@available(iOS 11.0, *)
public func setScrollViewDidChangeAdjustedContentInsetBlock(_ handler: @escaping((_ scrollView: UIScrollView)->())) {
scrollViewDidChangeAdjustedContentInsetBlock = handler
}
}
extension UIScrollView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollViewDidScrollBlock?(scrollView)
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
scrollViewDidZoomBlock?(scrollView)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollViewWillBeginDraggingBlock?(scrollView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
scrollViewWillEndDraggingWithVelocityTargetContentOffsetBlock?(scrollView, velocity, targetContentOffset)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
scrollViewDidEndDraggingWillDecelerateBlock?(scrollView, decelerate)
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
scrollViewWillBeginDeceleratingBlock?(scrollView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewDidEndDeceleratingBlock?(scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
scrollViewDidEndScrollingAnimationBlock?(scrollView)
}
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
if let block = viewForZoomingBlock {
return block(scrollView)
}
return nil
}
public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollViewWillBeginZoomingBlock?(scrollView, view)
}
public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollViewDidEndZoomingBlock?(scrollView, view, scale)
}
public func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
if let block = scrollViewShouldScrollToTopBlock {
return block(scrollView)
}
return true
}
public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
scrollViewDidScrollToTopBlock?(scrollView)
}
@available(iOS 11.0, *)
public func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
scrollViewDidChangeAdjustedContentInsetBlock?(scrollView)
}
}
<file_sep>//
// RequestTableVC.swift
// Example
//
// Created by senyuhao on 2018/7/11.
// Copyright © 2018年 dd01. All rights reserved.
//
import DDKit
import UIKit
class RequestTableVC: UITableViewController {
@IBOutlet weak var requestTextView: UITextView!
@IBOutlet weak var cacheTextView: UITextView!
var items = ["normal-login"]
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "网络请求"
DDRequest.shared.api = "https://eatojoy-api.hktester.com/api/1.0/ios/1.0"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "清除缓存", style: .plain, target: self, action: #selector(clearCache))
normalLogin()
}
@objc private func clearCache() {
CacheManager.share.removeAllCache {
print($0)
}
}
private func normalLogin() {
DDRequest.login(mobile: "56789012", password: "<PASSWORD>") {[weak self] value in
if let data = value.data {
self?.cacheTextView.text = "\(data)"
}
}.done {[weak self] value in
if let data = value.data {
self?.requestTextView.text = "\(data)"
}
}.catch { error in
print(error.localizedDescription)
}
}
}
<file_sep>//
// WebManager.swift
// DDKit
//
// Created by senyuhao on 2018/10/31.
// Copyright © 2018 dd01. All rights reserved.
//
import Foundation
import WebKit
public class WebManager: NSObject {
private var bridge: WKWebViewJavascriptBridge?
public static let shared = WebManager()
/// JS主动调用Native的config方法,返回结果,并可回调
public var configBlock: WKWebViewJavascriptBridgeBase.Handler?
/// JS主动调用Native的send方法,返回结果,并可回调
public var sendBlock: WKWebViewJavascriptBridgeBase.Handler?
/// JS主动调用Native的request方法,返回结果,并可回调
public var requestBlock: WKWebViewJavascriptBridgeBase.Handler?
private var configValue: [String: Any]?
private var configHandler: WKWebViewJavascriptBridgeBase.Callback?
/// 配置WkWebView
public func configManager(_ web: WKWebView) {
bridge = WKWebViewJavascriptBridge(webView: web)
bridge?.register(handlerName: "config", handler: { [weak self] value, block in
self?.configValue = value
self?.configHandler = block
self?.configBlock?(value, block)
})
bridge?.register(handlerName: "send", handler: { [weak self] value, block in
self?.sendBlock?(value, block)
})
bridge?.register(handlerName: "request", handler: { [weak self] value, block in
self?.requestBlock?(value, block)
})
}
/// Native调用JS的push方法,传递参数,并回调回结果
public func push(param: Any, handler: WKWebViewJavascriptBridgeBase.Callback? = nil) {
if let bridge = bridge {
bridge.call(handlerName: "push", data: param, callback: handler)
}
}
/// Native调用JS方法sendCallback方法,传递参数,并回调回结果。 err与response必有一个有值
public func callback(err: String?, response: Any?) -> Any? {
if bridge != nil {
var param = [String: Any]()
if let err = err {
param["err"] = err
}
if let response = response {
param["message"] = response
}
if let data = try? JSONSerialization.data(withJSONObject: param, options: []), let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) {
return json
}
}
return nil
}
/// 字典转json
public func dictToJson(_ sender: [String: Any]) -> String? {
if let data = try? JSONSerialization.data(withJSONObject: sender, options: []) {
return String(data: data, encoding: .utf8)
}
return nil
}
public func configFinished() {
if let value = WebManager.shared.callback(err: nil, response: "request response") {
configHandler?(value)
}
}
}
<file_sep>//
// Assert.swift
// AssertDemo
//
// Created by weiwei.li on 2019/1/24.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
public class DDAssert: NSObject {
public class func ddAssert(_ condition: Bool, _ message: String, file: StaticString = #file, line: UInt = #line) {
#if DEBUG
assert(condition, message, file: file, line: line)
#else
// TODO: - 后面会上传日志系统
// print(message)
#endif
}
}
extension NSObject {
public func Assert(_ condition: Bool, _ message: String, file: StaticString = #file, line: UInt = #line) {
DDAssert.ddAssert(condition, message, file: file, line: line)
}
}
<file_sep>
//
// PageTabsContainerView.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/18.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
let kPageTabsContainerTableCell = "kPageTabsContainerTableCell"
public protocol PageTabsContainerViewDelegate: NSObjectProtocol {
/// 当内容可以滚动时会调用
func pageTabsContentCanScroll(containerView: PageTabsContainerView)
/// 当容器可以滚动时会调用
func pageTabsContainerCanScroll(containerView: PageTabsContainerView)
/// 当容器正在滚动时调用,参数scrollView就是充当容器的tableView
func pageTabsContainerDidScroll(scrollView: UIScrollView)
}
public protocol PageTabsContainerViewDataSource: NSObjectProtocol {
// 根据 navigationBar 是否透明,返回不同的值
// 1. 当设置 navigationBar.translucent = NO 时,
// 普通机型 InsetTop = 0, iPhoneX InsetTop = 0 (默认情况)
// 2. 当设置 navigationBar.translucent = YES 时,
// 普通机型 InsetTop = 64, iPhoneX InsetTop = 88
func pageTabsContainerViewInsetTop(containerView: PageTabsContainerView) -> CGFloat
// 一般不需要实现
// 普通机型 InsetBottom = 0, iPhoneX InsetBottom = 34 (默认情况)
func pageTabsContainerViewInsetBottom(containerView: PageTabsContainerView) -> CGFloat
}
public class PageTabsContainerView: UIView {
public weak var delegate: PageTabsContainerViewDelegate?
public weak var dataSource: PageTabsContainerViewDataSource?
// /// 允许手势传递的view列表
// public var allowGestureEventPassViews: [UIView]? {
// didSet {
// tableView.allowGestureEventPassViews = allowGestureEventPassViews
// }
// }
public var tabsType: PageTabsType = .multiWork
/// 设置容器是否可以滚动
public var canScroll = true {
didSet {
if canScroll == true {
// 通知delegate,容器开始可以滚动
delegate?.pageTabsContainerCanScroll(containerView: self)
}
}
}
public var headerView: UIView? {
didSet {
tableView.tableHeaderView = headerView
resizeContentHeight()
tableView.reloadData()
}
}
public var segmentView: UIView? {
didSet {
resizeSegmentView()
tableView.reloadData()
}
}
public var contentView: UIView? {
didSet {
resizeContentHeight()
tableView.reloadData()
}
}
public var footerView: UIView? {
didSet {
resizeContentHeight()
tableView.reloadData()
}
}
public lazy var tableView: PageTabsBaseTableView = {
let tableView = PageTabsBaseTableView(frame: CGRect.zero, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(UITableViewCell.self, forCellReuseIdentifier: kPageTabsContainerTableCell)
return tableView
}()
override public init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
resizeTableView()
resizeSegmentView()
resizeContentHeight()
if headerView == nil {
tableView.isScrollEnabled = false
}
tableView.reloadData()
}
}
extension PageTabsContainerView: UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kPageTabsContainerTableCell, for: indexPath)
if let contentView = contentView {
cell.selectionStyle = .none
cell.contentView.addSubview(contentView)
}
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let contentView = contentView {
return contentView.bounds.height
}
return 0
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return segmentViewHeight()
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return segmentView
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return footerView
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return footerViewHeight()
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffset = heightForContainerCanScroll()
if canScroll == false {
// 这里通过固定contentOffset的值,来实现不滚动
scrollView.contentOffset = CGPoint(x: 0, y: contentOffset)
} else if (scrollView.contentOffset.y >= contentOffset) {
scrollView.contentOffset = CGPoint(x: 0, y: contentOffset)
canScroll = false
// 通知delegate内容开始可以滚动
delegate?.pageTabsContentCanScroll(containerView: self)
}
scrollView.showsVerticalScrollIndicator = canScroll
delegate?.pageTabsContainerDidScroll(scrollView: tableView)
}
}
extension PageTabsContainerView {
private func setupUI() {
addSubview(tableView)
canScroll = true
}
public func heightForContainerCanScroll() -> CGFloat {
if let headerView = tableView.tableHeaderView {
let headerH = headerView.frame.height
let insetTop = contentInsetTop()
return (headerH - insetTop)
}
return 0
}
private func resizeTableView() {
tableView.frame = bounds
}
private func resizeSegmentView() {
segmentView?.frame = CGRect(x: 0, y: 0, width: bounds.width, height: segmentView?.frame.height ?? 0)
}
private func resizeContentHeight() {
let height = bounds.height - segmentViewHeight() - contentInsetTop() - contentInsetBottom() - footerViewHeight()
contentView?.frame = CGRect(x: 0, y: 0, width: bounds.width, height: height)
}
private func segmentViewHeight() -> CGFloat {
return segmentView?.bounds.height ?? 0
}
private func footerViewHeight() -> CGFloat {
return footerView?.bounds.height ?? 0
}
private func contentInsetTop() -> CGFloat {
return dataSource?.pageTabsContainerViewInsetTop(containerView: self) ?? 0
}
private func contentInsetBottom() -> CGFloat {
return dataSource?.pageTabsContainerViewInsetBottom(containerView: self) ?? 0
}
}
<file_sep>//
// CacheKey.swift
// DDRequest
//
// Created by jp on 2018/9/20.
// Copyright © 2018年 dd01. All rights reserved.
//
import Cache
import Foundation
func cacheKey(_ url: String, _ params: [String: HTTPParam]?) -> String {
guard let params = params else {
return MD5(url)
}
if let stringData = try? JSONSerialization.data(withJSONObject: params, options: []),
let paramString = String(data: stringData, encoding: String.Encoding.utf8) {
let str = "\(url)" + "\(paramString)"
return MD5(str)
} else {
return MD5(url)
}
}
<file_sep>
//
// DDPhotoPickerResultModel.swift
// Photo
//
// Created by USER on 2018/11/14.
// Copyright © 2018 leo. All rights reserved.
//
import UIKit
import Photos
public struct DDPhotoPickerResultModel {
var asset: PHAsset?
var isGIF: Bool?
var image: UIImage?
init(aset: PHAsset?, isgif: Bool? = false, im: UIImage?) {
self.asset = aset
self.isGIF = isgif
self.image = im
}
}
<file_sep>//
// NSObject+TopViewController.swift
// DDKit
//
// Created by USER on 2018/12/21.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
extension UIViewController {
public class var getTopViewController: UIViewController? {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
return getTopViewController(viewController: rootViewController)
}
public class func getTopViewController(viewController: UIViewController?) -> UIViewController? {
if let presentedViewController = viewController?.presentedViewController {
return getTopViewController(viewController: presentedViewController)
}
if let tabBarController = viewController as? UITabBarController,
let selectViewController = tabBarController.selectedViewController {
return getTopViewController(viewController: selectViewController)
}
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return getTopViewController(viewController: visibleViewController)
}
if let pageViewController = viewController as? UIPageViewController,
pageViewController.viewControllers?.count == 1 {
return getTopViewController(viewController: pageViewController.viewControllers?.first)
}
for subView in viewController?.view.subviews ?? [] {
if let childViewController = subView.next as? UIViewController {
return getTopViewController(viewController: childViewController)
}
}
return viewController
}
}
<file_sep>//
// NumberSelect.swift
// NumberSelectDemo
//
// Created by weiwei.li on 2019/1/7.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
//fileprivate let numberSelectWidth: CGFloat = 100.0
//fileprivate let numberSelectHeight: CGFloat = 32.0
fileprivate let numberSelectTextColor: UIColor = UIColor(red: 38.0/255.0, green: 38.0/255.0, blue: 38.0/255.0, alpha: 1)
fileprivate let numberSelectFont: UIFont = UIFont.systemFont(ofSize: 16)
fileprivate let numberSelectBorderColor: UIColor = UIColor(red: 217.0/255.0, green: 217.0/255.0, blue: 217.0/255.0, alpha: 1)
fileprivate let numberSelectBorderWidth: CGFloat = 1.0
public class NumberSelect: UIView {
/// 可选择最少数字
public var minNumber: Int = 1
/// 可选择最大数字
public var maxNumber: Int = 10
// 达到最大或最少值都允许回调
public var isEnableCallBack = false
/// 当前选择的数字
public var currentNum: Int = 1 {
didSet {
if isEnableCallBack == false {
reduceBtn.isEnabled = currentNum <= minNumber ? false : true
addBtn.isEnabled = currentNum >= maxNumber ? false : true
}
currentNum = currentNum < minNumber ? minNumber : currentNum
currentNum = currentNum > maxNumber ? maxNumber : currentNum
numberLab.text = "\(currentNum)"
}
}
/// 步进设置
public var stepNumber: Int = 1
/// 选择数字回调
public var selectedNumberComplete: ((Int) -> ())?
/// 减btn
public lazy var reduceBtn: UIButton = {
let btn = UIButton(type: .system)
if let path = Bundle(for: NumberSelect.classForCoder()).path(forResource: "NumberSelect", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "icoMinus", in: bundle, compatibleWith: nil)
{
btn.setImage(image, for: .normal)
}
btn.tintColor = UIColor.black
btn.layer.borderColor = numberSelectBorderColor.cgColor
btn.layer.borderWidth = numberSelectBorderWidth
btn.addTarget(self, action: #selector(reduceAction), for: .touchUpInside)
return btn
}()
/// 加btn
public lazy var addBtn: UIButton = {
let btn = UIButton(type: .system)
if let path = Bundle(for: NumberSelect.classForCoder()).path(forResource: "NumberSelect", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "icoAdd", in: bundle, compatibleWith: nil)
{
btn.setImage(image, for: .normal)
}
btn.tintColor = UIColor.black
btn.layer.borderColor = numberSelectBorderColor.cgColor
btn.layer.borderWidth = numberSelectBorderWidth
btn.addTarget(self, action: #selector(addAction), for: .touchUpInside)
return btn
}()
/// 数字显示lab
public lazy var numberLab: UILabel = {
let lab = UILabel(frame: CGRect.zero)
lab.font = numberSelectFont
lab.textColor = numberSelectTextColor
lab.textAlignment = .center
lab.text = "1"
lab.layer.borderColor = numberSelectBorderColor.cgColor
lab.layer.borderWidth = numberSelectBorderWidth
return lab
}()
override public init(frame: CGRect) {
super.init(frame: frame)
addSubview(reduceBtn)
addSubview(addBtn)
addSubview(numberLab)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(reduceBtn)
addSubview(addBtn)
addSubview(numberLab)
}
override public func layoutSubviews() {
super.layoutSubviews()
let rect = frame
let btnW = rect.height
let btnH = btnW
reduceBtn.frame = CGRect(x: 0, y: 0, width: btnW, height: btnH)
addBtn.frame = CGRect(x: rect.width - btnW - numberSelectBorderWidth * 2, y: 0, width: btnW, height: btnH)
numberLab.frame = CGRect(x: btnW - numberSelectBorderWidth, y: 0, width: rect.width - btnW * 2, height: btnH)
}
}
extension NumberSelect {
@objc private func reduceAction() {
if isEnableCallBack == true && currentNum <= minNumber {
selectedNumberComplete?(currentNum)
return
}
currentNum -= stepNumber
selectedNumberComplete?(currentNum)
}
@objc private func addAction() {
if isEnableCallBack == true && currentNum >= maxNumber {
selectedNumberComplete?(currentNum)
return
}
currentNum += stepNumber
selectedNumberComplete?(currentNum)
}
}
<file_sep>
//
// DDPhotoVideoView.swift
// PhotoDemo
//
// Created by USER on 2018/11/19.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
class DDPhotoVideoView: UIView {
//隐藏预览图回调
public var hiddenPreviewCallBack: ((_ isTap: Bool)->())?
lazy private var playBtn: UIButton = {
let playBtn = UIButton(type: .custom)
if let path = Bundle(for: DDPhotoVideoView.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "video_btn_play_two", in: bundle, compatibleWith: nil)
{
playBtn.setImage(image, for: .normal)
}
playBtn.isEnabled = false
// playBtn.addTarget(self, action: #selector(playBtnAction(_:)), for: .touchUpInside)
return playBtn
}()
private var playLayer: AVPlayerLayer = AVPlayerLayer()
private var player: AVPlayer?
private var requestId: PHImageRequestID?
lazy private var bottomView = DDPhotoVideoBottom()
//监听player时间回调
private var timeObserver: Any?
private var playerItemStatus: AVPlayerItem.Status = .unknown
var model: DDPhotoGridCellModel? {
didSet {
bringSubviewToFront(playBtn)
playBtn.isHidden = false
bottomView.isHidden = true
reset()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
playBtn.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
playBtn.center = center
playLayer.frame = bounds
var inset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0);
if #available(iOS 11.0, *) {
inset = safeAreaInsets
}
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
bottomView.frame = CGRect(x: 0, y: screenHeight - inset.bottom - 50, width: screenWidth, height: 50)
}
deinit {
print(self)
reset()
}
}
extension DDPhotoVideoView {
public func play() {
playBtn.isHidden = true
bottomView.isHidden = false
bringSubviewToFront(bottomView)
player?.play()
bottomView.changePlayBtnImage(true)
}
public func pause() {
playBtn.isHidden = false
bottomView.isHidden = true
bringSubviewToFront(playBtn)
player?.pause()
bottomView.changePlayBtnImage(false)
}
public func reset() {
playLayer.removeFromSuperlayer()
player?.removeObserver(self, forKeyPath: "status")
player?.removeTimeObserver(timeObserver as Any)
NotificationCenter.default.removeObserver(self)
// player?.pause()
pause()
player = nil
}
public func seekTime(_ time: TimeInterval, completion: ((Bool) -> Void)?) {
if time.isNaN || playerItemStatus != .readyToPlay {
if completion != nil {
completion!(false)
}
return
}
DispatchQueue.main.async { [weak self] in
self?.pause()
self?.player?.currentItem?.seek(to: CMTimeMakeWithSeconds(time, preferredTimescale: Int32(NSEC_PER_SEC)), completionHandler: { (finished) in
DispatchQueue.main.async(execute: {
self?.play()
if let completion = completion {
completion(finished)
}
})
})
}
}
}
private extension DDPhotoVideoView {
func setupUI() {
addSubview(playBtn)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognizer(_:)))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
tap.delegate = self
addGestureRecognizer(tap)
addSubview(bottomView)
bottomView.videoView = self
}
/// 是否正在播放
func isPlay() -> Bool {
if (player?.rate ?? 0) > Float(0) {
return true
}
return false
}
func addNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(playFinished), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object:nil)
let options = NSKeyValueObservingOptions([.new, .initial])
player?.addObserver(self, forKeyPath: "status", options: options, context: nil)
timeObserver = player?.addPeriodicTimeObserver(forInterval: .init(value: 1, timescale: 1), queue: DispatchQueue.main, using: { [weak self] time in
if let currentTime = self?.player?.currentTime().seconds,
let totalDuration = self?.player?.currentItem?.duration.seconds {
self?.bottomView.playerDurationDidChange(currentTime, totalDuration: totalDuration)
}
})
}
func setHiddenPreviewCallBack(_ isTap: Bool) {
if let callBack = hiddenPreviewCallBack {
callBack(isPlay())
}
}
}
extension DDPhotoVideoView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view?.isDescendant(of: bottomView) == true {
return false
} else {
return true
}
}
@objc func playBtnAction(_ sender: UIButton?) {
if isPlay() {
pause()
return
}
if player != nil {
play()
return
}
reset()
if let id = requestId {
if id > 0 {
DDPhotoImageManager.default().cancelImageRequest(id)
}
}
requestId = DDPhotoPickerSource.requesetAVPlayerItem(for: model) {[weak self] (playerItem) in
DispatchQueue.main.async(execute: {
guard let playerItem = playerItem else {
DDPhotoToast.showToast(msg: "加载失败")
return
}
let player = AVPlayer(playerItem: playerItem)
if let playLayer = self?.playLayer {
self?.layer.addSublayer(playLayer)
self?.playLayer.player = player
self?.playLayer.videoGravity = .resizeAspectFill
self?.player = player
//添加通知,添加监听
self?.addNotification()
self?.play()
}
})
}
}
@objc func tapGestureRecognizer(_ tap: UITapGestureRecognizer) {
playBtnAction(nil)
setHiddenPreviewCallBack(true)
}
@objc func playFinished() {
playBtn.isHidden = false
bottomView.isHidden = true
bringSubviewToFront(playBtn)
player?.seek(to: CMTime.zero)
setHiddenPreviewCallBack(true)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let status: AVPlayerItem.Status
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
playerItemStatus = status
if status == .readyToPlay {
setHiddenPreviewCallBack(true)
}
}
}
<file_sep>//
// Action.swift
// MediatorDemo
//
// Created by weiwei.li on 2019/3/19.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
/// 若调用sdk中的模块,或者pod管理的模块,需要传入模块名,swift中存在命名空间
public let kMediatorTargetModuleName = "kMediatorTargetModuleName"
public class Parameter {
var chainDic = [String: Any]()
private var chainCurrentKey: String = ""
}
public extension Parameter {
//初始化
static func create() -> Parameter {
return Parameter()
}
//设置key值
func key(_ pKey: String) -> Parameter {
chainCurrentKey = pKey
return self
}
//设置value
func value(_ pValue: Any) -> Parameter {
if chainCurrentKey.isEmpty {
assert(false, "Parameter----请先设置key再设置value")
}
chainDic[chainCurrentKey] = pValue
return self
}
/// 若调用sdk中的模块,或者pod管理的模块,需要传入模块名,swift中存在命名空间
// ps: DDKit -> "DDKit"
func addModule(_ value: String) -> Parameter {
chainDic[kMediatorTargetModuleName] = value
return self
}
}
<file_sep>//
// Array+Safe.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/18.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
// MARK: - 使用 arr[10, true]
extension Array {
public subscript(index: Int, safe: Bool ) -> Element? {
if safe {
if self.count > index {
return self[index]
} else {
return nil
}
}
return self[index]
}
}
<file_sep>//
// UISearchBar+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UISearchBar {
@discardableResult
func barStyle(_ style: UIBarStyle) -> Self {
barStyle = style
return self
}
@discardableResult
func text(_ text: String?) -> Self {
self.text = text
return self
}
@discardableResult
func prompt(_ text: String?) -> Self {
prompt = text
return self
}
@discardableResult
func placeholder(_ holder: String?) -> Self {
placeholder = holder
return self
}
@discardableResult
func showsBookmarkButton(_ bool: Bool) -> Self {
showsBookmarkButton = bool
return self
}
@discardableResult
func showsCancelButton(_ bool: Bool) -> Self {
showsCancelButton = bool
return self
}
@discardableResult
func showsSearchResultsButton(_ bool: Bool) -> Self {
showsSearchResultsButton = bool
return self
}
@discardableResult
func isSearchResultsButtonSelected(_ selected: Bool) -> Self {
isSearchResultsButtonSelected = selected
return self
}
@discardableResult
func tintColor(_ color: UIColor) -> Self {
tintColor = color
return self
}
@discardableResult
func barTintColor(_ color: UIColor) -> Self {
barTintColor = color
return self
}
@discardableResult
func searchBarStyle(_ style: UISearchBar.Style) -> Self {
searchBarStyle = style
return self
}
@discardableResult
func isTranslucent(_ bool: Bool) -> Self {
isTranslucent = bool
return self
}
@discardableResult
func scopeButtonTitles(_ titles: [String]?) -> Self {
scopeButtonTitles = titles
return self
}
@discardableResult
func selectedScopeButtonIndex(_ index: Int) -> Self {
selectedScopeButtonIndex = index
return self
}
@discardableResult
func showsScopeBar(_ bool: Bool) -> Self {
showsScopeBar = bool
return self
}
@discardableResult
func inputAccessoryView(_ view: UIView?) -> Self {
inputAccessoryView = view
return self
}
@discardableResult
func backgroundImage(_ image: UIImage?) -> Self {
backgroundImage = image
return self
}
@discardableResult
func scopeBarBackgroundImage(_ image: UIImage?) -> Self {
scopeBarBackgroundImage = image
return self
}
@discardableResult
func searchFieldBackgroundPositionAdjustment(_ offset: UIOffset) -> Self {
searchFieldBackgroundPositionAdjustment = offset
return self
}
@discardableResult
func searchTextPositionAdjustment(_ offset: UIOffset) -> Self {
searchTextPositionAdjustment = offset
return self
}
}
public extension UIKitChainable where Self: UISearchBar {
@discardableResult
public func addSearchBarShouldBeginEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->(Bool))) -> Self {
setSearchBarShouldBeginEditingBlock(handler)
return self
}
@discardableResult
public func addSearchBarTextDidBeginEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) -> Self {
setSearchBarTextDidBeginEditingBlock(handler)
return self
}
@discardableResult
public func addSearchBarShouldEndEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->(Bool))) -> Self {
setSearchBarShouldEndEditingBlock(handler)
return self
}
@discardableResult
public func addSearchBarTextDidEndEditingBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) -> Self {
setSearchBarTextDidEndEditingBlock(handler)
return self
}
@discardableResult
public func addSearchBartextDidChangeBlock(_ handler: @escaping((_ searchBar: UISearchBar, _ searchText: String)->())) -> Self {
setSearchBartextDidChangeBlock(handler)
return self
}
@discardableResult
public func addSearchBarTextShouldChangeTextInRangeReplacementTextBlock(_ handler: @escaping((_ searchBar: UISearchBar, _ replacementText: String)->(Bool))) -> Self {
setSearchBarTextShouldChangeTextInRangeReplacementTextBlock(handler)
return self
}
@discardableResult
public func addSearchBarSearchButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) -> Self {
setSearchBarSearchButtonClickedBlock(handler)
return self
}
@discardableResult
public func addSearchBarBookmarkButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) -> Self {
setSearchBarBookmarkButtonClickedBlock(handler)
return self
}
@discardableResult
public func addSearchBarCancelButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) -> Self {
setSearchBarCancelButtonClickedBlock(handler)
return self
}
@discardableResult
public func addSearchBarResultsListButtonClickedBlock(_ handler: @escaping((_ searchBar: UISearchBar)->())) -> Self {
setSearchBarResultsListButtonClickedBlock(handler)
return self
}
@discardableResult
public func setSearchBarselectedScopeButtonIndexDidChangeBlock(_ handler: @escaping((_ searchBar: UISearchBar, _ selectedScope: Int)->())) -> Self {
setSearchBarselectedScopeButtonIndexDidChangeBlock(handler)
return self
}
}
<file_sep>
[更多方法使用参考demo](https://github.com/weiweilidd01/DDPhotoBrowser)
#### 1.使用方式, pod DDKit
```
var photos = [DDPhoto]()
//九宫格图片显示,请自行结合赋值,赋值参照如下
let photo1 = DDPhoto()
//url必传,若为本地图片,请直接复制image
photo1.url = URL(string: "https://i2.hoopchina.com.cn/hupuapp/bbs/180015943752119/thread_180015943752119_20181123173449_s_5063176_w_357_h_345_28251.gif")
//必传,预览时才能获取当前imageView的frame,实现展示和消失动画操作
photo1.sourceImageView = imageViewA
let photo2 = DDPhoto()
photo2.url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056077048&di=e67f672075c673e6ffaa0625564133e7&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201406%2F12%2F20140612211118_YYXAC.jpeg")
photo2.sourceImageView = imageViewB
let photo3 = DDPhoto()
photo3.url = URL(string: "http://img1.mydrivers.com/img/20171008/s_da7893ed38074cbc994e0ff3d85adeb5.jpg")
photo3.sourceImageView = imageViewC
let photo4 = DDPhoto()
photo4.url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533056728983&di=0377ea3d0ef5acdefe8863c1657a67f4&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01e90159a5094ba801211d25bec351.jpg")
photo4.sourceImageView = imageViewD
photos.append(photo1)
photos.append(photo2)
photos.append(photo3)
photos.append(photo4)
//photos数组,
//currentIndex 当前选择图片的索引值
browser = DDPhotoBrower.photoBrowser(Photos: photos, currentIndex: 0)
browser?.delegate = self
browser?.show()
```
#### 2.DDPhoto Model
```
/** 图片地址 */ 是否必传
var url: URL? 是
/** 来源imageView */
var sourceImageView: UIImageView? 是
/** 来源frame */
var sourceFrame: CGRect? // 否
/** 图片(静态)若为本地图片,请直接赋值 */
var image: UIImage? 否
/** 占位图 */
var placeholderImage: UIImage? 否
```
#### 4.代理方法
```
extension ViewController: DDPhotoBrowerDelegate {
func photoBrowser(controller: DDPhotoBrowerController?, willDismiss index: Int?) {
}
func photoBrowser(controller: DDPhotoBrowerController?, didChanged index: Int?) {
}
func photoBrowser(controller: DDPhotoBrowerController?, longPress index: Int?) {
let photo = browser?.photos?[index ?? 0]
guard let image = photo?.image else {
return
}
//存储图片
UIImageWriteToSavedPhotosAlbum(image, self,#selector(saved(image:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func saved(image: UIImage, didFinishSavingWithError erro: NSError?, contextInfo: AnyObject) {
if erro != nil {
print("错误")
return
}
print("ok")
}
}
```
#### 5.若支持长按保存图片,请实现上述长按回调协议
```
请在info.plist文件中添加权限 Privacy - Photo Library Additions Usage Description
```
#### 6.详细使用,请参照demo
<file_sep>//
// DDPhotoPickerNavigationView.swift
// Photo
//
// Created by USER on 2018/10/24.
// Copyright © 2018年 leo. All rights reserved.
//
import UIKit
import SnapKit
class DDPhotoPickerNavigationView: UIView {
private var rightBtnCallBack: (()->())?
private var leftBtnCallBack: (()->())?
private lazy var containerView: UIView = {
let containerView = UIView()
containerView.backgroundColor = UIColor.clear
return containerView
}()
lazy var titleLabel: UILabel = {
let titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textAlignment = .center
if let color = DDPhotoStyleConfig.shared.navigationTintColor {
titleLabel.textColor = color
} else {
titleLabel.textColor = UIColor.white
}
titleLabel.font = UIFont.systemFont(ofSize: 18)
titleLabel.text = Bundle.localizedString("相册")
return titleLabel
}()
lazy var rightBtn: UIButton = {
let rightBtn = UIButton(type: .custom)
rightBtn.backgroundColor = UIColor.clear
rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
rightBtn.addTarget(self, action: #selector(rightBtnAction(button:)), for: .touchUpInside)
return rightBtn
}()
lazy var leftBtn: UIButton = {
let leftBtn = UIButton(type: .custom)
leftBtn.backgroundColor = UIColor.clear
leftBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
leftBtn.addTarget(self, action: #selector(leftBtnAction(button:)), for: .touchUpInside)
if let image = DDPhotoStyleConfig.shared.navigationBackImage {
leftBtn.setImage(image, for: .normal)
} else {
if let path = Bundle(for: DDPhotoPickerNavigationView.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "photo_nav_icon_back_black", in: bundle, compatibleWith: nil)
{
leftBtn.setImage(image, for: .normal)
}
}
leftBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
return leftBtn
}()
init(frame: CGRect, leftBtnCallBack: (() -> ())?, rightBtnCallBack: (() -> ())? ) {
super.init(frame: frame)
self.leftBtnCallBack = leftBtnCallBack
self.rightBtnCallBack = rightBtnCallBack
if let color = DDPhotoStyleConfig.shared.navigationBackgroudColor {
backgroundColor = color
} else {
backgroundColor = UIColor.black
}
addSubview(containerView)
containerView.addSubview(titleLabel)
containerView.addSubview(rightBtn)
containerView.addSubview(leftBtn)
}
override func layoutSubviews() {
super.layoutSubviews()
addConstraint()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: --- action
extension DDPhotoPickerNavigationView {
@objc func rightBtnAction(button: UIButton) {
if let rightBtnCallBack = rightBtnCallBack {
rightBtnCallBack()
}
}
@objc func leftBtnAction(button: UIButton) {
if let leftBtnCallBack = leftBtnCallBack {
leftBtnCallBack()
}
}
}
extension DDPhotoPickerNavigationView {
private func addConstraint() {
containerView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(DDPhotoNavigationHeight)
}
titleLabel.snp.makeConstraints { (make) in
make.bottom.top.equalTo(containerView)
make.center.equalTo(containerView)
}
rightBtn.snp.makeConstraints { (make) in
make.bottom.top.equalTo(containerView).offset(0)
make.width.equalTo(50)
make.right.equalTo(containerView).offset(-12)
}
leftBtn.snp.makeConstraints { (make) in
make.bottom.top.equalTo(containerView).offset(0)
make.width.equalTo(50)
make.left.equalTo(containerView).offset(10)
}
}
}
<file_sep>//
// DevelopManager.swift
// Hotel
//
// Created by senyuhao on 2018/12/3.
// Copyright © 2018 HK01. All rights reserved.
//
import UIKit
import AFNetworking
// MARK: - TypeDefine
public typealias handleCloser = () -> ()
public typealias netListenerCloser = (_ status: DDNetworkReachabilityStatus) -> ()
public enum DDNetworkReachabilityStatus: Int {
case unknown = 0
case notReachable
case reachableViaWWAN
case reachableViaWiFi
}
// MARK: - API
extension DevelopManager {
/// 注册 Host 到 DevelopManager 中
///
/// - Parameters:
/// - environments: hosts,键值对形式,key:host 说明,value:host 值
/// - notificationName: 通知名字,默认为 DevelopmentsNotification
public class func registerHost(environments: [String: String], notificationName: String = "DevelopConfigSettingNotification") {
DevelopManager.shared.registerHost(environments: environments, notificationName: notificationName)
}
/// 显示Host设置界面
///
/// - Parameters:
/// - currentHost: 当前Host
/// - settinghandle: 设置回调,设置完成后会使用 UserDefaults 保存,key为:DD-Environment-Host
public class func showSettingsVC(currentHost: String, settinghandle: handleCloser?) {
DevelopManager.shared.currentHost = currentHost
DevelopManager.shared.changeHostHandle = settinghandle
DevelopManager.shared.showDeveloperSettingsVC()
}
/// 开启网络监听
///
/// - Parameter listener: 网络状态回调
public class func startNetworkMonitoring(listener: netListenerCloser?) {
DevelopManager.shared.networkMonitor(listener)
}
/// 关闭网络监听
public class func stopNetworkMonitoring() {
DevelopManager.shared.stopNetworkMonitoring()
}
}
// MARK: - Class
public class DevelopManager: NSObject {
static let shared = DevelopManager()
var hostInfos = [String: String]()
var notificationN = ""
var currentHost = ""
var changeHostHandle: handleCloser?
func registerHost(environments: [String: String], notificationName: String) {
hostInfos = environments
notificationN = notificationName
}
func showDeveloperSettingsVC() {
if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
let nav = UINavigationController(rootViewController: DevelopSettingVC(style: .grouped))
rootVC.present(nav, animated: true, completion: nil)
}
}
}
// MARK: - NetworkMonitor
extension DevelopManager {
private func networkMonitor(_ listener: netListenerCloser?) {
/*
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2,
};
*/
AFNetworkReachabilityManager.shared().setReachabilityStatusChange { [weak self] (netStatus) in
print("DevelopManager networkMonitor:\(self?.netStatusString(netStatus) ?? "")")
var currentStatus: DDNetworkReachabilityStatus = .unknown
switch netStatus {
case .unknown:
currentStatus = .unknown
break
case .notReachable:
currentStatus = .notReachable
break
case .reachableViaWWAN:
currentStatus = .reachableViaWWAN
break
case .reachableViaWiFi:
currentStatus = .unknown
break
}
listener?(currentStatus)
}
AFNetworkReachabilityManager.shared().startMonitoring()
}
private func stopNetworkMonitoring() {
AFNetworkReachabilityManager.shared().stopMonitoring()
}
private func netStatusString(_ status: AFNetworkReachabilityStatus) -> String {
switch status {
case .unknown:
return "unknown"
case .notReachable:
return "notReachable"
case .reachableViaWWAN:
return "reachableViaWWAN"
case .reachableViaWiFi:
return "reachableViaWiFi"
}
}
}
<file_sep>//
// ServiceManager.swift
// Route
//
// Created by 鞠鹏 on 6/4/2018.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
public class ServiceManager: NSObject {
public static let shareInstance = ServiceManager()
// serviceAPI (协议) 和 service (实现)
var serviceMap: Dictionary = [String: Any]()
private override init() {
}
/// 注册 serviceAPI 和 service
public static func register(service: Any, serviceAPIName: String) {
shareInstance.serviceMap.updateValue(service, forKey: serviceAPIName)
}
/// 通过协议获取Service
///
/// - Parameter p: 协议名
/// - Returns: 实现了此协议的Service实现
func service<T>(_ apiName: T.Type = T.self) -> T? {
let service = Array(ServiceManager.shareInstance.serviceMap.values).compactMap { item -> T? in
item as? T
}.first
return service
}
/// 注册所有的 service
///
/// 传入自定义 Dictionary
public static func registerAll(serviceMap: [String: String]) {
for (serviceAPI, serviceName) in serviceMap {
let classStringName = serviceName
let classType = NSClassFromString("Route" + "." + classStringName) as? NSObject.Type
if let type = classType {
let service = type.init()
register(service: service, serviceAPIName: serviceAPI)
}
}
}
/// 注册所有的 service
/// 默认 service.plist
public static func registerAll() {
let servicePlistPath = Bundle.main.path(forResource: "service", ofType: "plist")
if let servicePlistPath = servicePlistPath {
let map = NSDictionary(contentsOfFile: servicePlistPath)
if let map = map as? [String: String] {
registerAll(serviceMap: map)
}
}
}
}
/// 通过协议获取Service
/// let api = API() as XxxAPI?
/// let api: XxxAPI? = API()
///
/// - Parameter p: 协议名,默认为类型自动推导的泛型类型
/// - Returns: 实现了此协议的Service实现
public func API<T>(_ apiName: T.Type = T.self) -> T? {
return ServiceManager.shareInstance.service(apiName)
}
<file_sep>//
// UIButton+EdgeInsets.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/7.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public enum ButtonImagePosition {
case top
case left
case bottom
case right
}
extension UIButton {
/// 设置UIButton图片的位置,可为上左下右四个方向
///
/// - Parameters:
/// - position: 位置
/// - space: 间隔
public func imagePosition(_ position: ButtonImagePosition, space: CGFloat) {
switch position {
case .top:
resetEdgeInsets()
setNeedsLayout()
layoutIfNeeded()
let contentRect = self.contentRect(forBounds: bounds)
let titleSize = self.titleRect(forContentRect: contentRect).size
let imageSize = self.imageRect(forContentRect: contentRect).size
let halfWidth: CGFloat = (titleSize.width + imageSize.width) / 2.0
let halfHeight: CGFloat = (titleSize.height + imageSize.height) / 2.0
let topInset: CGFloat = CGFloat.minimum(halfHeight, titleSize.height)
let leftInset: CGFloat = (titleSize.width - imageSize.width) > 0 ? (titleSize.height - imageSize.height) / 2.0 : 0
let bottomInset = (titleSize.height - imageSize.height) > 0 ? (titleSize.height - imageSize.height) / 2.0 : 0
let rightInset = CGFloat.minimum(halfWidth, titleSize.width)
titleEdgeInsets = UIEdgeInsets(top: imageSize.height + space, left: -halfWidth, bottom: -titleSize.height - space, right: halfWidth)
contentEdgeInsets = UIEdgeInsets(top: -bottomInset, left: leftInset, bottom: topInset + space, right: -rightInset)
case .bottom:
resetEdgeInsets()
setNeedsLayout()
layoutIfNeeded()
let contentRect = self.contentRect(forBounds: bounds)
let titleSize = self.titleRect(forContentRect: contentRect).size
let imageSize = self.imageRect(forContentRect: contentRect).size
let halfWidth: CGFloat = (titleSize.width + imageSize.width) / 2.0
let halfHeight: CGFloat = (titleSize.height + imageSize.height) / 2.0
let topInset: CGFloat = CGFloat.minimum(halfHeight, titleSize.height)
let leftInset: CGFloat = (titleSize.width - imageSize.width) > 0 ? (titleSize.height - imageSize.height) / 2.0 : 0
let bottomInset = (titleSize.height - imageSize.height) > 0 ? (titleSize.height - imageSize.height) / 2.0 : 0
let rightInset = CGFloat.minimum(halfWidth, titleSize.width)
titleEdgeInsets = UIEdgeInsets(top: -titleSize.height - space, left: -halfWidth, bottom: imageSize.height + space, right: halfWidth)
contentEdgeInsets = UIEdgeInsets(top: topInset + space, left: leftInset, bottom: -bottomInset, right: -rightInset)
case .left:
resetEdgeInsets()
setNeedsLayout()
layoutIfNeeded()
titleEdgeInsets = UIEdgeInsets(top: 0, left: space, bottom: 0, right: -space)
contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: space)
case .right:
resetEdgeInsets()
setNeedsLayout()
layoutIfNeeded()
let contentRect = self.contentRect(forBounds: bounds)
let titleSize = self.titleRect(forContentRect: contentRect).size
let imageSize = self.imageRect(forContentRect: contentRect).size
contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: space)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: 0, right: imageSize.width)
imageEdgeInsets = UIEdgeInsets(top: 0, left: titleSize.width + space, bottom: 0, right: -titleSize.width - space)
}
}
fileprivate func resetEdgeInsets() {
contentEdgeInsets = UIEdgeInsets.zero
imageEdgeInsets = UIEdgeInsets.zero
titleEdgeInsets = UIEdgeInsets.zero
}
}
<file_sep>
//
// DDCustomCameraPlayer.swift
// DDCustomCamera
//
// Created by USER on 2018/11/16.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import AVFoundation
class DDCustomCameraPlayer: UIView {
private var playerLayer: AVPlayerLayer?
private var player: AVPlayer?
public var videoUrl: URL? {
didSet {
setPlayVideoUrl(videoUrl)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
player?.removeObserver(self, forKeyPath: "status")
NotificationCenter.default.removeObserver(self)
player?.pause()
player = nil
}
}
extension DDCustomCameraPlayer {
/// 播放
func play() {
player?.play()
}
/// 暂停
func pause() {
player?.pause()
}
/// 重置
func reset() {
player?.removeObserver(self, forKeyPath: "status")
NotificationCenter.default.removeObserver(self)
player?.pause()
player = nil
}
/// 是否正在播放
func isPlay() -> Bool {
if (player?.rate ?? 0) > Float(0) {
return true
}
return false
}
}
private extension DDCustomCameraPlayer {
func setPlayVideoUrl(_ url:URL?) {
guard let url = url else {
return
}
player = AVPlayer(url: url)
if #available(iOS 10.0, *) {
player?.automaticallyWaitsToMinimizeStalling = false
}
//kvo
// _ = player?.observe(\.status, options: [.initial, .old, .new], changeHandler: {[weak self] (player, change) in
// print(change)
// player.status
// if change.newValue == .readyToPlay {
// UIView.animate(withDuration: 0.25, animations: {
// self?.alpha = 1
// })
// }
// })
let options = NSKeyValueObservingOptions([.new, .initial])
player?.addObserver(self, forKeyPath: "status", options: options, context: nil)
//通知
NotificationCenter.default.addObserver(self, selector: #selector(playFinished), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
playerLayer?.player = player
playerLayer?.videoGravity = .resizeAspect
}
func setupUI() {
backgroundColor = UIColor.black
alpha = 0
playerLayer = AVPlayerLayer()
playerLayer?.frame = bounds
if let tempLayer = playerLayer {
layer.addSublayer(tempLayer)
}
}
}
extension DDCustomCameraPlayer {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let status: AVPlayerItem.Status
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
if status == .readyToPlay {
UIView.animate(withDuration: 0.25, animations: {
self.alpha = 1
})
}
}
@objc func playFinished() {
player?.seek(to: CMTime.zero)
player?.play()
}
}
<file_sep>//
// UIColor+Extension.swift
// hk01-uikit
//
// Created by USER on 2018/5/22.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
extension UIColor {
public static func imageFromColor(color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
<file_sep>//
// DDPhotoPickerTakePicCell.swift
// PhotoDemo
//
// Created by USER on 2018/11/29.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class DDPhotoPickerTakePicCell: UICollectionViewCell {
public var takePicCallBack: (()->())?
private lazy var takePicBtn: UIButton = {
let takePicBtn = UIButton(type: .custom)
takePicBtn.setTitle(Bundle.localizedString("拍摄照片"), for: .normal)
takePicBtn.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
takePicBtn.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 12)
if let path = Bundle(for: DDPhotoPickerTakePicCell.classForCoder()).path(forResource: "DDPhotoPicker", ofType: "bundle"),
let bundle = Bundle(path: path),
let image = UIImage(named: "list_icon_photo", in: bundle, compatibleWith: nil)
{
takePicBtn.setImage(image, for: .normal)
}
takePicBtn.addTarget(self, action: #selector(takePicAction), for: .touchUpInside)
return takePicBtn
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(takePicBtn)
takePicBtn.frame = contentView.bounds
takePicBtn.photoimagePositionTop()
contentView.backgroundColor = UIColor(red: 25.0/255.0, green: 25.0/255.0, blue: 25.0/255.0, alpha: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func takePicAction() {
takePicCallBack?()
}
}
extension UIButton {
func photoimagePositionTop () {
if self.imageView != nil, let titleLabel = self.titleLabel {
let imageSize = self.imageRect(forContentRect: self.frame)
var titleSize = CGRect.zero
if let txtFont = titleLabel.font, let str = titleLabel.text {
titleSize = (str as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: txtFont], context: nil)
}
let spacing: CGFloat = 6
titleEdgeInsets = UIEdgeInsets(top: imageSize.height + titleSize.height + spacing, left: -imageSize.width, bottom: 0, right: 0)
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
}
}
}
<file_sep>//
// SearchBarVC.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class SearchBarVC: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
//支持所有delegate回调
searchBar
.placeholder("点击我输入")
.tintColor(UIColor.orange)
.addSearchBarShouldBeginEditingBlock { (bar) -> (Bool) in
return true
}
.addSearchBarTextDidBeginEditingBlock({ (bar) in
bar.setShowsCancelButton(true, animated: true)
})
.addSearchBarTextShouldChangeTextInRangeReplacementTextBlock { (bar, text) -> (Bool) in
print(text)
return true
}
.addSearchBarTextDidEndEditingBlock { (bar) in
bar.setShowsCancelButton(false, animated: true)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
deinit {
print(self)
}
}
<file_sep>//
// UIKit+Action.swift
// UIKit
//
// Created by 胡峰 on 2017/7/12.
// Copyright © 2017年 . All rights reserved.
//
import UIKit
/// 扩展了 UIKit 控件,支持闭包事件回调
///
/// 支持 UIView,UIControl,UIButton,UIBarButtonItem,UIGestureRecognizer。
/// 使用时一定要注意循环引用的问题,根据此API的使用场景,不使用 [weak self] 几乎 100% 产生循环引用
public protocol UIKitClosurable: NSObjectProtocol {
init() // 仅为了解决 ActionClosureTarget.invoke(_:) 转化 Any 不成功时的兼容,理论上不可能转不成功
}
// 需要在方法参数中使用 Self,目前只能使用 protocol 的 extension 实现,参考 https://stackoverflow.com/q/42660874
extension UIView: UIKitClosurable { }
extension UIBarButtonItem: UIKitClosurable { }
extension UIGestureRecognizer: UIKitClosurable { }
// MARK: - 闭包回调
public extension UIKitClosurable where Self: UIControl {
/// 添加事件回调(闭包)
///
/// - Parameters:
/// - event: 事件类型
/// - handler: 闭包回调,sender 为产生事件的控件,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func action(_ event: UIControl.Event, _ handler: @escaping (_ sender: Self) -> Void) -> Self {
let actionTarget = ClosureActionTarget(handler: handler)
addTarget(actionTarget, action: #selector(actionTarget.invoke(_:)), for: event)
allActionClosureTargets.append(actionTarget)
return self
}
}
public extension UIKitClosurable where Self: UIButton {
/// 添加点击(即`.touchUpInside`)事件回调(闭包)
///
/// - Parameter handler: 闭包回调,sender 为产生事件的控件,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func press(_ handler: @escaping (_ sender: Self) -> Void) -> Self {
return action(.touchUpInside, handler)
}
}
public extension UIKitClosurable where Self: UIBarButtonItem {
/// 添加点击事件回调(闭包)
///
/// - Parameter handler: 闭包回调,sender 为产生事件的控件,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func action(_ handler: @escaping (_ sender: Self) -> Void) -> Self {
let actionTarget = ClosureActionTarget(handler: handler)
target = actionTarget
action = #selector(actionTarget.invoke(_:))
allActionClosureTargets.append(actionTarget)
return self
}
}
public extension UIKitClosurable where Self: UIGestureRecognizer {
/// 添加手势事件回调(闭包)
///
/// - Parameter handler: 闭包回调,sender 为产生事件的手势,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func action(_ handler: @escaping (_ sender: Self) -> Void) -> Self {
let actionTarget = ClosureActionTarget(handler: handler)
addTarget(actionTarget, action: #selector(actionTarget.invoke(_:)))
allActionClosureTargets.append(actionTarget)
return self
}
}
public extension UIKitClosurable where Self: UIView {
/// 添加单击手势事件回调(闭包),若添加了双击手势,将等待双击识别失败后才回调
///
/// - Parameter handler: 闭包回调,闭包的参数为产生事件的view和手势,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func tap(_ handler: @escaping (Self, UITapGestureRecognizer) -> Void) -> Self {
gesture(UITapGestureRecognizer(), handler)
checkTapConflict()
return self
}
/// 添加双击手势事件回调(闭包),若添加了单击手势,将等待双击识别失败后才回调单击手势的事件
///
/// - Parameter handler: 闭包回调,闭包的参数为产生事件的view和手势,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func doubleTap(_ handler: @escaping (Self, UITapGestureRecognizer) -> Void) -> Self {
let recognizer = UITapGestureRecognizer()
recognizer.numberOfTapsRequired = 2
gesture(recognizer, handler)
checkTapConflict()
return self
}
/// 添加长按手势事件回调(闭包)
///
/// 默认长按时间为系统默认的0.5s,事件仅回调一次,不会按住时持续回调
/// - Parameter handler: 闭包回调,闭包的参数为产生事件的view和手势,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func longPress(_ handler: @escaping (Self, UILongPressGestureRecognizer) -> Void) -> Self {
gesture(UILongPressGestureRecognizer()) { (view, sender) in
// if sender.state == .began {
// }
handler(view, sender)
}
return self
}
/// 添加任意手势事件回调(闭包)
///
/// - Parameters:
/// - recognizer: 需要添加的手势
/// - handler: 闭包回调,闭包的参数为产生事件的view和手势,闭包内一定要使用 `[weak self]` 避免循环引用
/// - Returns: 返回 self,支持链式调用
@discardableResult func gesture<T: UIGestureRecognizer>(_ recognizer: T,_ handler: @escaping (Self, T) -> Void) -> Self {
isUserInteractionEnabled = true
addGestureRecognizer(recognizer.action({ (sender) in
handler(self, sender)
}))
return self
}
/// 检测 tap 事件的冲突,如同时添加双击和单击事件时,需等待双击失败才响应单击事件
private func checkTapConflict() {
var taps = [[UITapGestureRecognizer]](repeating: [], count: 10)
gestureRecognizers?.compactMap({ $0 as? UITapGestureRecognizer })
.forEach({ taps[$0.numberOfTapsRequired].append($0) })
taps = taps.compactMap({ $0.count > 0 ? $0 : nil })
zip(taps, taps.dropFirst()).forEach { (left, right) in
left.forEach({ (leftGesture) in
right.forEach({ (rightGesture) in
leftGesture.require(toFail: rightGesture)
})
})
}
}
}
// MARK: - 内部方法
private var UIKitClosureKey: Void?
extension UIKitClosurable {
fileprivate var allActionClosureTargets: [ClosureActionTarget<Self>] {
get { return objc_getAssociatedObject(self, &UIKitClosureKey) as? [ClosureActionTarget] ?? [] }
set { objc_setAssociatedObject(self, &UIKitClosureKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
}
private class ClosureActionTarget<T>: NSObject where T: UIKitClosurable {
var handler: (T) -> Void
init(handler: @escaping (T) -> Void) {
self.handler = handler
super.init()
}
@objc func invoke(_ sender: Any) {
guard let originalSender = sender as? T else {
assertionFailure("\(type(of: sender)) 的事件回调 sender != self")
handler(T())
return
}
handler(originalSender)
}
}
<file_sep>
//
// DDPhotoImageManager.swift
// Photo
//
// Created by USER on 2018/11/12.
// Copyright © 2018 leo. All rights reserved.
//
import UIKit
import Photos
public class DDPhotoImageManager: PHCachingImageManager {
private static let shared = DDPhotoImageManager()
public override class func `default`() -> DDPhotoImageManager {
return shared
}
private var gifImagesCache = [String: [UIImage]]()
private var gifImagesDurationCache = [String: TimeInterval]()
private let semaphoreSignal = DispatchSemaphore(value: 1)
}
extension DDPhotoImageManager {
static func transformAssetType(_ asset: PHAsset?) -> DDAssetMediaType {
guard let asset = asset else {
return .unknown
}
switch asset.mediaType {
case .audio:
return .audio
case .video:
return .video
case .image:
let str: String = asset.value(forKey: "filename") as? String ?? ""
if str.hasSuffix("GIF") {
return .gif
}
if #available(iOS 9.1, *) {
if asset.mediaSubtypes == .photoLive || Int(asset.mediaSubtypes.rawValue) == 10 {
return .livePhoto
}
}
return .image
default:
return .unknown
}
}
static func getVideoDuration(_ asset: PHAsset?) -> String {
if asset?.mediaType != .video {
return ""
}
var duration: Int = 0
if asset?.mediaType == .video {
duration = Int(asset?.duration ?? 0)
}
if duration < 60 {
return String(format: "00:%02ld", arguments: [duration])
} else if duration < 3600 {
let m = duration / 60
let s = duration % 60
return String(format: "%02ld:%02ld", arguments: [m, s])
} else {
let h = duration / 3600
let m = (duration % 3600) / 60
let s = duration % 60
return String(format: "%02ld:%02ld:%02ld", arguments: [h, m, s])
}
}
}
extension DDPhotoImageManager {
private func getRequestOptions() -> PHImageRequestOptions {
let option = PHImageRequestOptions()
// PHImageRequestOptions是否有效
option.isSynchronous = true
// 缩略图的压缩模式设置为无
option.resizeMode = .fast
// 缩略图的质量为快速
option.deliveryMode = .fastFormat
//必要时从icould下载
option.isNetworkAccessAllowed = true;
return option
}
/// 返回指定大小的图片
///
/// - Parameters:
/// - asset: asset
/// - targetSize: size
/// - resultHandler: 回调
/// - Returns: id
public func requestTargetImage(for asset: PHAsset?, targetSize: CGSize, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
let option = self.getRequestOptions()
return self.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: option, resultHandler: { (image, dic) in
var downloadFinined = true
if let cancelled = dic?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dic?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dic?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let image = image {
resultHandler(image,dic)
}
})
}
/// 返回原始图
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
public func requestOriginalImage(for asset: PHAsset?, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
let option = self.getRequestOptions()
let targetSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
return self.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: option, resultHandler: { (image, dic) in
resultHandler(image,dic)
})
}
/// 获取原始图片的data(用于上传)
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
public func requestOriginalImageDataForAsset(for asset: PHAsset?, resultHandler: @escaping (Data?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
let option = PHImageRequestOptions()
option.resizeMode = .exact
option.isNetworkAccessAllowed = true
option.isSynchronous = true
return PHCachingImageManager.default().requestImageData(for: asset, options: option, resultHandler: { (data, uti, orientation, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let photoData = data {
resultHandler(photoData,dictionry)
}
})
}
/// 获取相册视屏播放的item
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestVideoForAsset(for asset: PHAsset?, resultHandler: @escaping (AVPlayerItem?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
return PHCachingImageManager.default().requestPlayerItem(forVideo: asset, options: nil, resultHandler: { (item, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let item = item {
resultHandler(item,dictionry)
}
})
}
/// 获取视屏的avasset 用于视屏上传时使用
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: id
static public func requestAVAssetForAsset(for asset: PHAsset?, resultHandler: @escaping (AVAsset?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
return PHCachingImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (avAsset, mix, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let avAsset = avAsset {
resultHandler(avAsset,dictionry)
}
})
}
/// 获取缩略图
///
/// - Parameters:
/// - asset: asset
/// - resultHandler: 回调
/// - Returns: 请求id
public func requestThumbnailImage(for asset: PHAsset?, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
let option = self.getRequestOptions()
let targetSize = getThumbnailSize(originSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight))
return self.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: option, resultHandler: { (image, dic) in
resultHandler(image,dic)
})
}
/// 获取预览图
///
/// - Parameters:
/// - asset: 照片源
/// - progressHandler: 请求进度回调
/// - resultHandler: 请求完成回调
/// - Returns: 请求ID
public func requestPreviewImage(for asset: PHAsset?, isGIF: Bool? = false, progressHandler: Photos.PHAssetImageProgressHandler?, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
return 0
}
let option = PHImageRequestOptions()
option.resizeMode = .exact
option.isNetworkAccessAllowed = true
// option.isSynchronous = true
option.progressHandler = progressHandler
let targetSize = getPriviewSize(originSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight))
if isGIF == true {
_ = requestPreviewImageData(for: asset, progressHandler: nil) { (data, dic) in
}
}
return self.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: option) { (image: UIImage?, dictionry: Dictionary?) in
resultHandler(image, dictionry)
}
}
/// 获取原始图data,主要用户获取gif图片
///
/// - Parameters:
/// - asset: asset
/// - progressHandler: 进度回调
/// - resultHandler: 回调
/// - Returns: id
public func requestPreviewImageData(for asset: PHAsset?,isUpload: Bool? = false, progressHandler: Photos.PHAssetImageProgressHandler?, resultHandler: @escaping (Data?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID {
guard let asset = asset else {
resultHandler(nil,nil)
return 0
}
//判断缓存中是否数据,有就直接返回
let tempIamges = getImagesCache(asset.localIdentifier)
if tempIamges != nil {
resultHandler(nil,nil)
return 0
}
let option = PHImageRequestOptions()
option.resizeMode = .exact
option.isNetworkAccessAllowed = true
// option.isSynchronous = true
option.progressHandler = progressHandler
return self.requestImageData(for: asset, options: option, resultHandler: {[weak self] (data, uti, orientation, dictionry) in
var downloadFinined = true
if let cancelled = dictionry?[PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry?[PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry?[PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let photoData = data {
if isUpload == false {
self?.getImages(photoData, localIdentifier: asset.localIdentifier)
}
resultHandler(data,dictionry)
}
})
}
func getImages(_ photoData: Data, localIdentifier: String) {
//判断缓存中是否数据,有就直接返回
let tempIamges = getImagesCache(localIdentifier)
if tempIamges != nil {
return
}
DispatchQueue.global().async {
//2.从data中读取数据,转换为CGImageSource
guard let imageSource = CGImageSourceCreateWithData(photoData as CFData, nil) else {return}
let imageCount = CGImageSourceGetCount(imageSource)
//3.遍历所有图片
var images = [UIImage]()
var totalDuration : TimeInterval = 0
for i in 0..<imageCount {
//3.1取出图片
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else {continue}
let image = UIImage(cgImage: cgImage)
images.append(image)
//3.2取出持续时间
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? NSDictionary else {continue}
guard let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else {continue}
guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else {continue}
totalDuration += frameDuration.doubleValue
}
//缓存数据
self.setImagesCache(localIdentifier, obj: images)
self.setImagesDurationCache(localIdentifier, obj: totalDuration)
}
}
public func setImagesCache(_ key: String, obj: [UIImage]) {
semaphoreSignal.wait()
gifImagesCache[key] = obj
semaphoreSignal.signal()
}
public func setImagesDurationCache(_ key: String, obj: TimeInterval) {
semaphoreSignal.wait()
gifImagesDurationCache[key] = obj
semaphoreSignal.signal()
}
public func getImagesCache(_ key: String) -> [UIImage]? {
return gifImagesCache[key]
}
public func getImagesDurationCache(_ key: String) -> TimeInterval? {
return gifImagesDurationCache[key]
}
public func removeImagesCacheObj(_ key: String) {
gifImagesCache.removeValue(forKey: key)
}
public func removeImagesDurationCacheObj(_ key: String) {
gifImagesDurationCache.removeValue(forKey: key)
}
public func removeAllCache() {
gifImagesDurationCache.removeAll()
gifImagesCache.removeAll()
}
}
private extension DDPhotoImageManager {
func getThumbnailSize(originSize: CGSize) -> CGSize {
let thumbnailWidth: CGFloat = (DDPhotoScreenWidth - 5 * 5) / 4 * UIScreen.main.scale
let pixelScale = CGFloat(originSize.width)/CGFloat(originSize.height)
let thumbnailSize = CGSize(width: thumbnailWidth, height: thumbnailWidth/pixelScale)
return thumbnailSize
}
private func getPriviewSize(originSize: CGSize) -> CGSize {
let width = originSize.width
let height = originSize.height
let pixelScale = CGFloat(width)/CGFloat(height)
var targetSize = CGSize()
if width <= 1280 && height <= 1280 {
//a,图片宽或者高均小于或等于1280时图片尺寸保持不变,不改变图片大小
targetSize.width = CGFloat(width)
targetSize.height = CGFloat(height)
} else if width > 1280 && height > 1280 {
//宽以及高均大于1280,但是图片宽高比例大于(小于)2时,则宽或者高取小(大)的等比压缩至1280
if pixelScale > 2 {
targetSize.width = 1280*pixelScale
targetSize.height = 1280
} else if pixelScale < 0.5 {
targetSize.width = 1280
targetSize.height = 1280/pixelScale
} else if pixelScale > 1 {
targetSize.width = 1280
targetSize.height = 1280/pixelScale
} else {
targetSize.width = 1280*pixelScale
targetSize.height = 1280
}
} else {
//b,宽或者高大于1280,但是图片宽度高度比例小于或等于2,则将图片宽或者高取大的等比压缩至1280
if pixelScale <= 2 && pixelScale > 1 {
targetSize.width = 1280
targetSize.height = 1280/pixelScale
} else if pixelScale > 0.5 && pixelScale <= 1 {
targetSize.width = 1280*pixelScale
targetSize.height = 1280
} else {
targetSize.width = CGFloat(width)
targetSize.height = CGFloat(height)
}
}
return targetSize
}
}
<file_sep>//
// UIViewController+DDRouter.swift
// DDRouterDemo
//
// Created by USER on 2018/12/5.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
// MARK: - 扩展UIViewController,给每个控制器绑定一个属性
extension UIViewController {
// 嵌套结构体
private struct DDRouterAssociatedKeys {
static var paramsKey = "DDRouterParameterKey"
static var completeKey = "DDRouterComplete"
}
public var params: DDRouterParameter? {
set {
objc_setAssociatedObject(self, &DDRouterAssociatedKeys.paramsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &DDRouterAssociatedKeys.paramsKey) as? DDRouterParameter
}
}
/// 添加回调闭包,适用于反向传值,只能层级传递
public var complete: ((Any?)->())? {
set {
objc_setAssociatedObject(self, &DDRouterAssociatedKeys.completeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &DDRouterAssociatedKeys.completeKey) as? ((Any?) -> ())
}
}
/// push sb控制器
///
/// - Parameters:
/// - sbName: storybord名字
/// - identifier: id
/// - params: 参数
/// - animated: 是否动画
/// - complete: 回调
public func pushSBViewController(_ sbName: String,
identifier: String? = nil,
params: DDRouterParameter? = nil,
animated: Bool = true,
complete:((Any?)->())? = nil) {
DDRouter.share.pushSBViewController(sbName, identifier: identifier, params: params, animated: animated, complete: complete)
}
/// present sb控制器
///
/// - Parameters:
/// - sbName: storybord名字
/// - identifier: id
/// - params: 入参
/// - animated: 是否动画
/// - complete: 回调
public func presentSBViewController(_ sbName: String,
identifier: String? = nil,
params: DDRouterParameter? = nil,
animated: Bool = true,
complete:((Any?)->())? = nil) {
DDRouter.share.presentSBViewController(sbName, identifier: identifier, params: params, animated: animated, complete: complete)
}
/// 路由入口 push
///
/// - Parameters:
/// - key: 定义的key
/// - params: 需要传递的参数
/// - parent: 是否是present显示
/// - animated: 是否需要动画
/// - complete: 上级控制器回调传值,只能层级传递
public func pushViewController(_ key: String, params: DDRouterParameter? = nil, animated: Bool = true, complete:((Any?)->())? = nil) {
DDRouter.share.pushViewController(key, params: params, animated: animated, complete: complete)
}
/// 路由入口 present
///
/// - Parameters:
/// - key: 路由key
/// - params: 参数
/// - animated: 是否需要动画
/// - complete: 上级控制器回调传值,只能层级传递
public func presentViewController(_ key: String, params: DDRouterParameter? = nil, animated: Bool = true, complete:((Any?)->())? = nil) {
DDRouter.share.presentViewController(key, params: params, animated: animated, complete: complete)
}
/// 正常的pop操作
///
/// - Parameters:
/// - vc: 当前控制器
/// - dismiss: true: dismiss退出,false: pop退出
/// - animated: 是否需要动画
public func pop(animated: Bool = true) {
DDRouter.share.pop(self, animated: animated)
}
/// pop到指定的控制器
///
/// - Parameters:
/// - currentVC: 当前控制器
/// - toVC: 目标控制器对应的key
/// - animated: 是否需要动画
public func pop(ToViewController toVC: String, animated: Bool = true) {
DDRouter.share.pop(ToViewController: self, toVC: toVC, animated: animated)
}
/// pop到根目录
///
/// - Parameters:
/// - currentVC: 当前控制器
/// - animated: 是否需要动画
public func pop(ToRootViewController animated: Bool = true) {
DDRouter.share.pop(ToRootViewController: self, animated: animated)
}
/// dismiss操作
///
/// - Parameters:
/// - vc: 当前控制器
/// - animated: 是否需要动画
public func dismiss(_ animated: Bool = true) {
DDRouter.share.dismiss(self, animated: animated)
}
}
<file_sep>//
// CHLogListViewController.swift
// CHLog
//
// Created by wanggw on 2018/6/30.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
import UIKit
class CHLogListViewController: UIViewController {
private var searchBar: UISearchBar?
private var tableView: UITableView?
private var dataSource: [CHLogItem] = []
private var isSearch = false
private var searchArray: [CHLogItem] = []
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//去掉返回按钮上的文字
navigationController?.navigationBar.topItem?.title = ""
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarConfig()
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupCHLog()
setupNavigationBar()
}
private func setupCHLog() {
dataSource = CHLog.currentLogArray()
tableView?.reloadData()
CHLog.logInfoArrayChanged { (logArray) in
self.dataSource.removeAll()
self.dataSource = logArray
if !self.isSearch {
self.tableView?.reloadData()
}
}
}
// MARK: - SetupUI
private func setupNavigationBar() {
let rect = CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.size.width, height: 64)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor(red: 255/255.0, green: 127/255.0, blue: 80/255.0, alpha: 1.0).cgColor)
context?.fill(rect)
let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
navigationController?.navigationBar.setBackgroundImage(image, for: .default)
}
private func navigationBarConfig() {
//设置标题颜色
navigationController?.navigationBar.topItem?.title = "调试日志"
//设置导航栏背景颜色
navigationController?.navigationBar.barTintColor = UIColor(red: 255/255.0, green: 127/255.0, blue: 80/255.0, alpha: 1.0)
//设置NagivationBar上按钮的颜色
navigationController?.navigationBar.tintColor = UIColor.white
//设置NavigationBar上的title的颜色以及属性
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
}
private func setupUI() {
title = "调试日志"
view.backgroundColor = UIColor.groupTableViewBackground
navigationController?.navigationBar.isTranslucent = false
initRightNavButton()
setupSearchBar()
setupTableView()
}
private func initRightNavButton() {
let alertButtonItem = UIBarButtonItem(title: "提示", style: .plain, target: self, action: #selector(self.alertAction))
navigationItem.leftBarButtonItem = alertButtonItem
let closeButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(self.dismissAction))
let cleanButtonItem = UIBarButtonItem(title: "清屏", style: .plain, target: self, action: #selector(self.cleanAction))
navigationItem.rightBarButtonItems = [closeButtonItem, cleanButtonItem] //倒序排序的
}
private func setupSearchBar() {
searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 49.5))
if let searchBar = searchBar {
view.addSubview(searchBar)
}
searchBar?.backgroundColor = UIColor.white
searchBar?.barStyle = .default
searchBar?.placeholder = "输入path进行搜索"
searchBar?.searchBarStyle = .minimal
searchBar?.delegate = self
}
private func setupTableView() {
let bottomSpace = ((UIScreen.main.bounds.size.height==812) ? 88 : 64)
tableView = UITableView(frame: CGRect(x: 0, y: 50, width: view.bounds.width, height: view.bounds.height - CGFloat(bottomSpace) - 50), style: .grouped)
if let tableView = tableView {
view.addSubview(tableView)
}
tableView?.delegate = self as UITableViewDelegate
tableView?.dataSource = self as UITableViewDataSource
tableView?.backgroundColor = UIColor.groupTableViewBackground
tableView?.keyboardDismissMode = .onDrag //滑动隐藏键盘
tableView?.showsVerticalScrollIndicator = true //显示滚动线
tableView?.separatorStyle = .singleLine //分割线
tableView?.tableFooterView = UIView.init() //去掉多余的分割线
//处理分割线前面 15px,下面👇两个一起才能去掉 tableView 分割线前面的 15px:cell 也要进行这样的写法才能去掉
if (tableView?.responds(to: #selector(setter: UITableView.layoutMargins)) ?? false) {
tableView?.layoutMargins = UIEdgeInsets.zero
}
if (tableView?.responds(to: #selector(setter: UITableView.separatorInset)) ?? false) {
tableView?.separatorInset = UIEdgeInsets.zero
}
tableView?.register(CHLogListCell.self, forCellReuseIdentifier: "CHLogListCell")
//给出傻瓜式的提示,不是所有人都明白操作流程
let height = CGFloat((UIScreen.main.bounds.size.height==568) ? 30 : 44)
let noteHeader = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: height))
noteHeader.font = UIFont.systemFont(ofSize: 12)
noteHeader.text = "Tips:点击出错的请求接口并拷贝发送给后台人员,可以快速排查问题"
noteHeader.textColor = UIColor.red
noteHeader.textAlignment = .center
noteHeader.backgroundColor = UIColor.groupTableViewBackground
//noteHeader.sizeToFit()//这个方法的效果是,让高度紧贴文字高度😂
noteHeader.adjustsFontSizeToFitWidth = true//字体适应大小
tableView?.tableHeaderView = noteHeader
}
}
// MARK: - Actions
extension CHLogListViewController {
@objc private func alertAction() {
let alert = UIAlertController(title: "提示", message: "单击接口请求列表,就可以拷贝请求参数信息至剪切板", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@objc private func dismissAction() {
dismiss(animated: true) {
CHLog.show()
}
}
@objc private func cleanAction() {
CHLog.clean()
}
private func searchAction(key: String) {
searchArray.removeAll()
dataSource.forEach { (logInfo) in
if logInfo.requstFullUrl.contains(key) {
searchArray.append(logInfo)
}
}
tableView?.reloadData()
}
}
// MARK: - UISearchBarDelegate
extension CHLogListViewController: UISearchBarDelegate {
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
return true
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
isSearch = true
tableView?.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchAction(key: searchText)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
searchBar.setShowsCancelButton(false, animated: true)
searchBar.resignFirstResponder()
isSearch = false
tableView?.reloadData()
}
}
// MARK: -
extension CHLogListViewController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
searchBar?.resignFirstResponder()
}
}
// MARK: - UITableViewDataSource & UITableViewDelegate
extension CHLogListViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return isSearch ? searchArray.count : dataSource.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isSearch ? searchArray[section].responses.count : dataSource[section].responses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let response = isSearch ? searchArray[indexPath.section].responses[indexPath.row] : dataSource[indexPath.section].responses[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "CHLogListCell", for: indexPath as IndexPath) as? CHLogListCell {
cell.updateContent(response: response)
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44;
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let height = isSearch ? searchArray[section].cellRowHeigt() + 10 : dataSource[section].cellRowHeigt() + 10
let logInfo = isSearch ? searchArray[section] : dataSource[section]
let head = CHLogHeader(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: height))
head.updateContent(logInfo: logInfo, target: self)
return head
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let height = isSearch ? searchArray[section].cellRowHeigt() + 10 : dataSource[section].cellRowHeigt() + 10
return height
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = UIView()
footer.backgroundColor = UIColor.groupTableViewBackground
return footer
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.5
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let response = isSearch ? searchArray[indexPath.section].responses[indexPath.row] : dataSource[indexPath.section].responses[indexPath.row]
let vc = CHLogDetailViewController(response: response)
navigationController?.pushViewController(vc, animated: true)
}
}
<file_sep>//
// CollectionViewVC.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class CollectionViewVC: UIViewController {
var collectionView: UICollectionView?
private let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let w = UIScreen.main.bounds.size.width
let h = UIScreen.main.bounds.size.height
override func viewDidLoad() {
super.viewDidLoad()
flowLayout.scrollDirection = .vertical
//将所有90%的delegate代理方法支持回调
//所有的datasource支持回调
//所有的UICollectionViewDelegateFlowLayout支持回调
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: w, height: h), collectionViewLayout: flowLayout)
.isPagingEnabled(false)
.registerCell(UICollectionViewCell.self, ReuseIdentifier: "UICollectionViewCell")
.registerSupplementaryView(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, ReuseIdentifier: "UICollectionReusableView")
.addNumberOfSectionsBlock({ (collection) -> (Int) in
return 10
})
.addNumberOfItemsInSectionBlock({ (collection, section) -> (Int) in
return 10
})
.addLayoutCollectionViewLayoutSizeForItemAtIndexPathBlock({[weak self] (collection, layout, indexPath) -> (CGSize) in
return CGSize(width: self?.w ?? 0, height: 200)
})
.addLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock({[weak self] (collection, layout, section) -> (CGSize) in
return CGSize(width: self?.w ?? 0, height: 130)
})
.addCellForItemAtIndexPathBlock({[weak self] (collection, indexPath) -> (UICollectionViewCell) in
if let cell = self?.collectionView?.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath) {
let lab = UILabel(frame: cell.bounds)
.text("\(indexPath.section) : \(indexPath.row)")
.textAlignment(.center)
.font(20)
.backgroundColor(UIColor.green)
cell.contentView
.removeAllSubViews()
.add(subView: lab)
return cell
}
return UICollectionViewCell()
})
.addViewForSupplementaryElementOfKindAtIndexPathBlock({ (collection, kind, indexPath) -> (UICollectionReusableView) in
if kind == UICollectionView.elementKindSectionHeader {
let header = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "UICollectionReusableView", for: indexPath)
let lab = UILabel()
.frame(header.bounds)
.text("我是第\(indexPath.section)组")
.textColor(UIColor.red)
.font(18)
.textAlignment(.center)
header.removeAllSubViews()
.add(subView: lab)
return header
}
return UICollectionReusableView()
})
.addDidSelectItemAtIndexPathBlock({ (collection, indexPath) in
print("\(indexPath.section): \(indexPath.row)")
})
.backgroundColor(UIColor.white)
.addLongGesture({[weak self](collection, longPress) in
let point = longPress.location(in: collection)
let indexPath = collection.indexPathForItem(at: point)
switch longPress.state {
case .began:
if let index = indexPath {
//开始移动
self?.collectionView?.beginInteractiveMovementForItem(at: index)
}
print("began")
case .changed:
//更新位置坐标
self?.collectionView?.updateInteractiveMovementTargetPosition(point)
print("changed")
case .ended:
//停止移动调用此方法
self?.collectionView?.endInteractiveMovement()
print("end")
default:
//取消移动
self?.collectionView?.cancelInteractiveMovement()
print("default")
break
}
})
.addCanMoveItemAtIndexPathBlock({ (collection, indexPath) -> (Bool) in
return true
})
.addMoveItemAtSourceIndexPathToDestinationIndexPathBlock({ (collection, sourceIndexPath, targetIndexPath) in
print("source: \(sourceIndexPath.section): \(sourceIndexPath.row)")
print("target: \(targetIndexPath.section): \(targetIndexPath.row)")
})
.add(to: view)
.reload()
}
deinit {
print(self)
}
}
<file_sep>
//
// DDPhotoPickerBottomView.swift
// Photo
//
// Created by USER on 2018/10/25.
// Copyright © 2018年 leo. All rights reserved.
//
import UIKit
class DDPhotoPickerBottomView: UIView {
private var rightBtnCallBack: (()->())?
private var leftBtnCallBack: (()->())?
lazy var rightBtn: UIButton = {
let rightBtn = UIButton(type: .custom)
rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
rightBtn.addTarget(self, action: #selector(rightBtnAction(button:)), for: .touchUpInside)
rightBtn.setTitle(Bundle.localizedString("完成"), for: .normal)
rightBtn.backgroundColor = selectNotEnableColor
rightBtn.layer.cornerRadius = 4.0
rightBtn.layer.masksToBounds = true
rightBtn.isEnabled = false
return rightBtn
}()
lazy var leftBtn: UIButton = {
let leftBtn = UIButton(type: .custom)
leftBtn.backgroundColor = UIColor.clear
leftBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
leftBtn.addTarget(self, action: #selector(leftBtnAction(button:)), for: .touchUpInside)
leftBtn.setTitle(Bundle.localizedString("预览"), for: .normal)
return leftBtn
}()
init(frame: CGRect, leftBtnCallBack: (() -> ())?, rightBtnCallBack: (() -> ())? ) {
super.init(frame: frame)
self.leftBtnCallBack = leftBtnCallBack
self.rightBtnCallBack = rightBtnCallBack
//背景颜色
if let color = DDPhotoStyleConfig.shared.bottomBarBackgroudColor {
backgroundColor = color
} else {
backgroundColor = UIColor(red: 25/255.0, green: 25/255.0, blue: 25/255.0, alpha: 1)
}
if let color = DDPhotoStyleConfig.shared.bottomBarTintColor {
leftBtn.setTitleColor(color, for: .normal)
}
addSubview(rightBtn)
addSubview(leftBtn)
rightBtn.snp.makeConstraints { (make) in
make.top.equalTo(10)
make.right.bottom.equalTo(-10)
make.width.equalTo(64)
}
leftBtn.snp.makeConstraints { (make) in
make.left.top.bottom.equalTo(0)
make.width.equalTo(60)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DDPhotoPickerBottomView {
//改变button状态
func didChangeButtonStatus(count: Int) {
if count > 0 {
rightBtn.isEnabled = true
rightBtn.setTitle(Bundle.localizedString("完成") + "(\(count))", for: .normal)
if let color = DDPhotoStyleConfig.shared.bottomBarTintColor {
rightBtn.backgroundColor = color
} else {
rightBtn.backgroundColor = selectEnableColor
}
} else {
rightBtn.isEnabled = false
rightBtn.setTitle(Bundle.localizedString("完成"), for: .normal)
rightBtn.backgroundColor = selectNotEnableColor
}
}
}
//MARK: --- action
private extension DDPhotoPickerBottomView {
@objc func rightBtnAction(button: UIButton) {
if let rightBtnCallBack = rightBtnCallBack {
rightBtnCallBack()
}
}
@objc func leftBtnAction(button: UIButton) {
if let leftBtnCallBack = leftBtnCallBack {
leftBtnCallBack()
}
}
}
<file_sep>//
// UITextView+Chainable.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UITextView
public extension UIKitChainable where Self: UITextView {
/// 设置最大值
///
/// - Parameter length: length
/// - Returns: self
@discardableResult
func maxLength(_ length: Int) -> Self {
maxLength = length
return self
}
/// placeholder
///
/// - Parameter holder: holder
/// - Returns: self
@discardableResult
func placeholder(_ holder: String?) -> Self {
placeholder = holder
return self
}
/// 设置代理
///
/// - Parameter delegate: delegate
/// - Returns: self
// @discardableResult
// func delegate(_ delegate: UITextViewDelegate?) -> UITextView {
// self.delegate = delegate
// return self
// }
/// text
///
/// - Parameter text: text
/// - Returns: self
@discardableResult
func text(_ text: String) -> Self {
self.text = text
return self
}
/// font
///
/// - Parameter font: font
/// - Returns: self
@discardableResult
func font(_ font: UIFontType) -> Self {
self.font = font.font
return self
}
/// textColor
///
/// - Parameter color: color
/// - Returns: self
@discardableResult
func textColor(_ color: UIColor?) -> Self {
textColor = color
return self
}
@discardableResult
func textAlignment(_ aligment: NSTextAlignment) -> Self {
textAlignment = aligment
return self
}
@discardableResult
func selectedRange(_ range: NSRange) -> Self {
selectedRange = range
return self
}
@discardableResult
func isEditable(_ able: Bool) -> Self {
isEditable = able
return self
}
@discardableResult
func isSelectable(_ able: Bool) -> Self {
isSelectable = able
return self
}
@discardableResult
func dataDetectorTypes(_ types: UIDataDetectorTypes) -> Self {
dataDetectorTypes = types
return self
}
@discardableResult
func allowsEditingTextAttributes(_ bool: Bool) -> Self {
allowsEditingTextAttributes = bool
return self
}
@discardableResult
func attributedText(_ text: NSAttributedString) -> Self {
attributedText = text
return self
}
@discardableResult
func typingAttributes(_ attributes: [String : Any]) -> Self {
typingAttributes = convertToNSAttributedStringKeyDictionary(attributes)
return self
}
@discardableResult
func inputView(_ view: UIView?) -> Self {
inputView = view
return self
}
@discardableResult
func inputAccessoryView(_ view: UIView?) -> Self {
inputAccessoryView = view
return self
}
@discardableResult
func clearsOnInsertion(_ bool: Bool) -> Self {
clearsOnInsertion = bool
return self
}
@discardableResult
func textContainerInset(_ inset: UIEdgeInsets) -> Self {
textContainerInset = inset
return self
}
@discardableResult
func linkTextAttributes(_ attributes: [String : Any]) -> Self {
linkTextAttributes = convertToOptionalNSAttributedStringKeyDictionary(attributes)
return self
}
//MARK: - 添加UITextViewDelegate
@discardableResult
func addShouldBegindEditingBlock(_ handler: @escaping((UITextView)->(Bool))) -> Self {
setShouldBegindEditingBlock(handler)
return self
}
@discardableResult
func addShouldEndEditingBlock(_ handler: @escaping((UITextView)->(Bool))) -> Self {
setShouldEndEditingBlock(handler)
return self
}
@discardableResult
func addDidBeginEditingBlock(_ handler: @escaping((UITextView)->())) -> Self {
setDidBeginEditingBlock(handler)
return self
}
@discardableResult
func addDidEndEditingBlock(_ handler: @escaping((UITextView)->())) -> Self {
setDidEndEditingBlock(handler)
return self
}
@discardableResult
func addShouldChangeTextInRangeReplacementTextBlock(_ handler: @escaping((UITextView, NSRange, String)->(Bool))) -> Self {
setShouldChangeTextInRangeReplacementTextBlock(handler)
return self
}
@discardableResult
func addDidChangeBlock(_ handler: @escaping((UITextView)->())) -> Self {
setDidChangeBlock(handler)
return self
}
@discardableResult
func addDidChangeSelectionBlock(_ handler: @escaping((UITextView)->())) -> Self {
setDidChangeSelectionBlock(handler)
return self
}
@discardableResult
@available(iOS 10.0, *)
func addShouldInteractWithURLCharacterRangeInteractionBlock(_ handler: @escaping((UITextView, URL, NSRange, UITextItemInteraction)->(Bool))) -> Self {
setShouldInteractWithURLCharacterRangeInteractionBlock(handler)
return self
}
@discardableResult
@available(iOS 10.0, *)
func addShouldInteractWithTextAttachmentCharacterRangeInteractionBlock(_ handler: @escaping((UITextView, NSTextAttachment, NSRange, UITextItemInteraction)->(Bool))) -> Self {
setShouldInteractWithTextAttachmentCharacterRangeInteractionBlock(handler)
return self
}
@discardableResult
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead")
func addShouldInteractWithURLcharacterRangeBlock(_ handler: @escaping((UITextView, URL, NSRange)->(Bool))) -> Self {
setShouldInteractWithURLcharacterRangeBlock(handler)
return self
}
@discardableResult
@available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithTextAttachment:inRange:forInteractionType: instead")
func addShouldInteractWithTextAttachmentCharacterRangeBlock(_ handler: @escaping((UITextView, NSTextAttachment, NSRange)->(Bool))) -> Self {
setShouldInteractWithTextAttachmentCharacterRangeBlock(handler)
return self
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToNSAttributedStringKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.Key: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
<file_sep>//
// Test.swift
// MediatorDemo
//
// Created by weiwei.li on 2019/3/19.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
public class ModuleB: NSObject {
@objc func test(_ pa: MediatorParamDic) -> String {
let back = pa["back"] as? (String) -> ()
back?("werwer")
return "sdfsfsdfdf"
}
}
<file_sep>//
// PageTabsContentView.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/18.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
public protocol PageTabsContentViewDelegate: NSObjectProtocol {
func contentView(view: PageTabsContentView, didScrollTo index: Int)
}
public class PageTabsContentView: UIView {
public weak var delegate: PageTabsContentViewDelegate?
public var viewControllerList:[PageTabsBaseController]? {
didSet {
loadedFlagArr.removeAll()
for _ in viewControllerList ?? [] {
loadedFlagArr.append(false)
}
}
}
private lazy var containerView: UIScrollView = {
let containerView = UIScrollView(frame: CGRect.zero)
containerView.showsVerticalScrollIndicator = false
containerView.showsHorizontalScrollIndicator = false
containerView.delegate = self
containerView.backgroundColor = UIColor.white
containerView.isPagingEnabled = true
containerView.scrollsToTop = true
return containerView
}()
/// 存取当前controller是否被加载
private var loadedFlagArr:[Bool] = [Bool]()
private var scrollIndex = 0
override public init(frame: CGRect) {
super.init(frame: frame)
addSubview(containerView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
let itemW = frame.width
let itemH = frame.height
containerView.frame = bounds
let res = loadedFlagArr[scrollIndex]
if res == true {
guard let vc = viewControllerList?[scrollIndex] else {
return
}
setChildViewFrame(vc.view, index: scrollIndex)
}
containerView.contentSize = CGSize(width: itemW * CGFloat(viewControllerList?.count ?? 0), height: itemH)
setContentOffset(scrollIndex)
loadChildViewController(scrollIndex)
}
public func scroll(To index: Int) {
if index >= viewControllerList?.count ?? -1 {
return
}
scrollIndex = index
setContentOffset(scrollIndex)
loadChildViewController(index)
}
}
extension PageTabsContentView: UIScrollViewDelegate {
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let page: Int = Int(offset.x / screenWidth)
scrollIndex = page
loadChildViewController(scrollIndex)
delegate?.contentView(view: self, didScrollTo: scrollIndex)
}
}
extension PageTabsContentView {
private func setContentOffset(_ index: Int) {
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
let offset: CGFloat = CGFloat(index) * screenWidth
containerView.setContentOffset(CGPoint(x: offset, y: 0), animated: true)
}
/// 加载对应的子控制器
///
/// - Parameter index: 下标
private func loadChildViewController(_ index: Int) {
if index >= loadedFlagArr.count {
return
}
/// 已经加载过就不在加载
if loadedFlagArr[index] == true {
guard let vc = viewControllerList?[index] else {
return
}
setChildViewFrame(vc.view, index: scrollIndex)
return
}
if index >= viewControllerList?.count ?? -1 {
return
}
guard let vc = viewControllerList?[index] else {
return
}
getViewController()?.addChildViewController(vc)
containerView.addSubview(vc.view)
loadedFlagArr[index] = true
setChildViewFrame(vc.view, index: index)
}
/// 设置子控制器的frame
///
/// - Parameters:
/// - childView: 子控制器的view
/// - index: 下标
private func setChildViewFrame(_ childView:UIView, index: Int) {
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
var rect = containerView.bounds
rect.origin.x = CGFloat(index) * screenWidth
rect.origin.y = 0
rect.size.height = rect.height
childView.frame = rect
//防止横屏时出错
containerView.bringSubview(toFront: childView)
}
private func getViewController () -> UIViewController? {
var next: UIResponder?
next = self.next
repeat {
if (next as? UIViewController) != nil {
return next as? UIViewController
} else {
next = next?.next
}
} while next != nil
return UIViewController()
}
}
<file_sep>
//
// DDVideoPlayerConfig.swift
// Example
//
// Created by USER on 2018/10/29.
// Copyright © 2018年 dd01. All rights reserved.
//
import Foundation
import UIKit
/// 导航条高度(不包含状态栏高度)默认44
public let DDPVPNavigationHeight: CGFloat = 44
public let DDVPScreenWidth: CGFloat = UIScreen.main.bounds.size.width
public let DDVPScreenHeight: CGFloat = UIScreen.main.bounds.size.height
//let DDVPIsiPhoneX: Bool = UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) && UIScreen.main.currentMode!.size == CGSize(width: 1125, height: 2436)
//#define IsiPhoneXSMax ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) : NO)
public let DDVPStatusBarHeight: CGFloat = DDVPIsiPhoneX.isIphonex() ? 44 : 20
public let DDVPNavigationTotalHeight: CGFloat = DDVPStatusBarHeight + DDPVPNavigationHeight
public let DDVPHomeBarHeight: CGFloat = DDVPIsiPhoneX.isIphonex() ? 34 : 0
public class DDVPIsiPhoneX {
static public func isIphonex() -> Bool {
var isIphonex = false
if UIDevice.current.userInterfaceIdiom != .phone {
return isIphonex
}
if #available(iOS 11.0, *) {
/// 利用safeAreaInsets.bottom > 0.0来判断是否是iPhone X。
let mainWindow = UIApplication.shared.keyWindow
if mainWindow?.safeAreaInsets.bottom ?? CGFloat(0.0) > CGFloat(0.0) {
isIphonex = true
}
}
return isIphonex
}
}
<file_sep>
//
// DDRouter.swift
// DDRouterDemo
//
// Created by USER on 2018/12/4.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
public typealias DDRouterParameter = [String: Any]
// MARK: - DDRouter
public class DDRouter: NSObject {
//单列
public static let share = DDRouter()
/// push sb控制器
///
/// - Parameters:
/// - sbName: storybord名字
/// - identifier: id
/// - params: 参数
/// - animated: 是否动画
/// - complete: 回调
open func pushSBViewController(_ sbName: String,
identifier: String? = nil,
params: DDRouterParameter? = nil,
animated: Bool = true,
complete:((Any?)->())? = nil) {
var vc: UIViewController = UIViewController()
if let id = identifier {
vc = UIStoryboard(name: sbName, bundle: nil).instantiateViewController(withIdentifier: id)
} else {
vc = UIStoryboard(name: sbName, bundle: nil).instantiateInitialViewController() ?? UIViewController()
}
vc.params = params
vc.complete = complete
vc.hidesBottomBarWhenPushed = true
let topViewController = DDRouterUtils.getTopViewController
if topViewController?.navigationController != nil {
topViewController?.navigationController?.pushViewController(vc, animated: animated)
} else {
topViewController?.present(vc, animated: animated, completion: nil)
}
}
/// present sb控制器
///
/// - Parameters:
/// - sbName: storybord名字
/// - identifier: id
/// - params: 入参
/// - animated: 是否动画
/// - complete: 回调
open func presentSBViewController(_ sbName: String,
identifier: String? = nil,
params: DDRouterParameter? = nil,
animated: Bool = true,
complete:((Any?)->())? = nil) {
var vc: UIViewController = UIViewController()
if let id = identifier {
vc = UIStoryboard(name: sbName, bundle: nil).instantiateViewController(withIdentifier: id)
} else {
vc = UIStoryboard(name: sbName, bundle: nil).instantiateInitialViewController() ?? UIViewController()
}
vc.params = params
vc.complete = complete
vc.params = params
vc.complete = complete
let topViewController = DDRouterUtils.getTopViewController
topViewController?.present(vc, animated: animated, completion: nil)
}
/// 路由入口 push
///
/// - Parameters:
/// - key: 定义的key
/// - params: 需要传递的参数
/// - parent: 是否是present显示
/// - animated: 是否需要动画
/// - complete: 上级控制器回调传值,只能层级传递
open func pushViewController(_ key: String, params: DDRouterParameter? = nil, animated: Bool = true, complete:((Any?)->())? = nil) {
let cls = classFromeString(key: key)
let vc = cls.init()
vc.params = params
vc.complete = complete
vc.hidesBottomBarWhenPushed = true
let topViewController = DDRouterUtils.getTopViewController
if topViewController?.navigationController != nil {
topViewController?.navigationController?.pushViewController(vc, animated: animated)
} else {
topViewController?.present(vc, animated: animated, completion: nil)
}
}
/// 路由入口 present
///
/// - Parameters:
/// - key: 路由key
/// - params: 参数
/// - animated: 是否需要动画
/// - complete: 上级控制器回调传值,只能层级传递
open func presentViewController(_ key: String, params: DDRouterParameter? = nil, animated: Bool = true, complete:((Any?)->())? = nil) {
//创建path对应的控制器
let cls = classFromeString(key: key)
let vc = cls.init()
vc.params = params
vc.complete = complete
let topViewController = DDRouterUtils.getTopViewController
topViewController?.present(vc, animated: animated, completion: nil)
}
/// 正常的pop操作
///
/// - Parameters:
/// - vc: 当前控制器
/// - dismiss: true: dismiss退出,false: pop退出
/// - animated: 是否需要动画
open func pop(_ vc: UIViewController, animated: Bool = true) {
if vc.navigationController == nil {
vc.dismiss(animated: animated, completion: nil)
return
}
vc.navigationController?.popViewController(animated: animated)
}
/// pop到指定的控制器
///
/// - Parameters:
/// - currentVC: 当前控制器
/// - toVC: 目标控制器对应的key
/// - animated: 是否需要动画
open func pop(ToViewController currentVC: UIViewController, toVC: String, animated: Bool = true) {
if currentVC.navigationController == nil {
currentVC.dismiss(animated: animated, completion: nil)
return
}
//创建path对应的控制器
let cls = classFromeString(key: toVC)
guard let viewControllers = currentVC.navigationController?.viewControllers else {
return
}
for subVC in viewControllers {
if subVC.isKind(of: cls) == true {
currentVC.navigationController?.popToViewController(subVC, animated: animated)
}
}
}
/// pop到根目录
///
/// - Parameters:
/// - currentVC: 当前控制器
/// - animated: 是否需要动画
open func pop(ToRootViewController currentVC: UIViewController, animated: Bool = true) {
if currentVC.navigationController == nil {
currentVC.dismiss(animated: animated, completion: nil)
return
}
currentVC.navigationController?.popToRootViewController(animated: animated)
}
/// dismiss操作
///
/// - Parameters:
/// - vc: 当前控制器
/// - animated: 是否需要动画
open func dismiss(_ vc: UIViewController, animated: Bool = true) {
if vc.navigationController == nil {
vc.dismiss(animated: animated, completion: nil)
return
}
vc.dismiss(animated: animated, completion: nil)
}
/// 通过key获取对象class
///
/// - Parameter key: key
/// - Returns: class
open func classFromeString(key: String) -> UIViewController.Type {
if key.contains(".") == true {
let clsName = key
let cls = NSClassFromString(clsName) as! UIViewController.Type
return cls
}
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
let clsName = namespace + "." + key
let cls = NSClassFromString(clsName) as! UIViewController.Type
return cls
}
}
// MARK: - DDRouterUtils --- 获取最上层的viewController
public class DDRouterUtils {
//获取当前页面
public class var getTopViewController: UIViewController? {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
return getTopViewController(viewController: rootViewController)
}
public class func getTopViewController(viewController: UIViewController?) -> UIViewController? {
if let presentedViewController = viewController?.presentedViewController {
return getTopViewController(viewController: presentedViewController)
}
if let tabBarController = viewController as? UITabBarController,
let selectViewController = tabBarController.selectedViewController {
return getTopViewController(viewController: selectViewController)
}
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return getTopViewController(viewController: visibleViewController)
}
if let pageViewController = viewController as? UIPageViewController,
pageViewController.viewControllers?.count == 1 {
return getTopViewController(viewController: pageViewController.viewControllers?.first)
}
for subView in viewController?.view.subviews ?? [] {
if let childViewController = subView.next as? UIViewController {
return getTopViewController(viewController: childViewController)
}
}
return viewController
}
}
<file_sep>//
// DDClipperView.swift
// DDCustomCameraDemo
//
// Created by USER on 2018/12/10.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class DDClipperView: UIView {
public var clipperSize: CGSize?
public lazy var clipperImgView: UIImageView? = {
let clipperImgView = UIImageView(frame: CGRect.zero)
clipperImgView.layer.borderColor = UIColor.white.cgColor
clipperImgView.layer.borderWidth = 2
return clipperImgView
}()
private lazy var fillLayer: CAShapeLayer? = {
let fillLayer = CAShapeLayer()
fillLayer.fillRule = CAShapeLayerFillRule.evenOdd
fillLayer.fillColor = UIColor.black.cgColor
fillLayer.opacity = 0.5
return fillLayer
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
clipperImgView?.frame = CGRect(x: 0, y: 100, width: clipperSize?.width ?? 0.0, height: clipperSize?.height ?? 0.0)
clipperImgView?.center = center
updateFillLayer()
}
}
private extension DDClipperView {
func setupUI() {
layer.contentsGravity = CALayerContentsGravity.resizeAspectFill
if let clipperView = clipperImgView {
addSubview(clipperView)
}
if let fillLayer = fillLayer {
layer.addSublayer(fillLayer)
}
}
func updateFillLayer() {
let path = UIBezierPath.init(roundedRect: bounds, cornerRadius: 0)
let circlePath = UIBezierPath.init(roundedRect: clipperImgView?.frame ?? CGRect.zero, cornerRadius: 0)
path.append(circlePath)
path.usesEvenOddFillRule = true
fillLayer?.path = path.cgPath
}
}
<file_sep>//
// CHLogDetailViewController.swift
// CHLog
//
// Created by wanggw on 2018/6/30.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
private let CHLog_ScreenWidth = UIScreen.main.bounds.size.width
private let CHLog_ScreenHeight = UIScreen.main.bounds.size.height
private let CHLog_IS_iPhone_5_8_X = (UIScreen.main.bounds.size.height == 812)
private let CHLog_Height_navigationBar = (CHLog_IS_iPhone_5_8_X ? CGFloat(88.0) : CGFloat(64.0)) /// 导航栏高度:64pt -> 88pt:iphoneX 增加24pt
class CHLogDetailViewController: UIViewController {
private var searchBar: UISearchBar?
private var textView: UITextView?
private var response: CHLogItem?
init(response: CHLogItem) {
self.response = response
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupContent()
}
}
// MARK: - SetupUI
extension CHLogDetailViewController {
private func setupUI() {
title = "接口请求返回详情"
view.backgroundColor = UIColor.white
navigationController?.navigationBar.isTranslucent = false
let closeButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(self.dismissAction))
let copyButtonItem = UIBarButtonItem(title: "拷贝", style: .plain, target: self, action: #selector(self.copyAction))
navigationItem.rightBarButtonItems = [closeButtonItem, copyButtonItem] //倒序排序的
setupSearchBar()
initTextView()
}
private func setupSearchBar() {
searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 49.5))
if let searchBar = searchBar {
view.addSubview(searchBar)
}
searchBar?.backgroundColor = UIColor.white
searchBar?.delegate = self
searchBar?.barStyle = .default
searchBar?.placeholder = "输入字段进行搜索"
searchBar?.searchBarStyle = .minimal
}
private func initTextView() {
textView = UITextView(frame: CGRect(x: 0, y: 50, width: CHLog_ScreenWidth, height: (CHLog_ScreenHeight - CHLog_Height_navigationBar)))
textView?.isEditable = false
textView?.backgroundColor = UIColor.black
textView?.font = UIFont.systemFont(ofSize: 12)
if let textView = textView {
view.addSubview(textView)
}
}
}
// MARK: - Actions
extension CHLogDetailViewController {
private func setupContent() {
textView?.text = response?.describeString()
textView?.textColor = (response?.isRequestError ?? false) ? UIColor.red : UIColor.white
}
@objc private func dismissAction() {
dismiss(animated: true) {
CHLog.show()
}
}
@objc private func copyAction() {
UIPasteboard.general.string = response?.describeString()
let alert = UIAlertController(title: "提示", message: "已经拷贝至剪切板", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
private func searchAction(key: String) {
guard key.count > 0 else {
setupContent()
return
}
let baseString = response?.describeString()
textView?.attributedText = generateAttributedString(with: key, targetString: baseString ?? "")
}
private func generateAttributedString(with searchTerm: String, targetString: String) -> NSAttributedString? {
let attributedString = NSMutableAttributedString(string: targetString)
attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 12), range: NSMakeRange(0, attributedString.length))
let color = (response?.isRequestError ?? false) ? UIColor.red : UIColor.white
attributedString.addAttribute(.foregroundColor, value: color, range: NSMakeRange(0, attributedString.length))
do {
let regex = try NSRegularExpression(pattern: searchTerm, options: .caseInsensitive)
let range = NSRange(location: 0, length: targetString.utf16.count)
for match in regex.matches(in: targetString, options: .withTransparentBounds, range: range) {
attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 14), range: match.range)
attributedString.addAttribute(.foregroundColor, value: UIColor.yellow, range: match.range)
}
return attributedString
} catch _ {
NSLog("Error creating regular expresion")
return nil
}
}
}
// MARK: - UISearchBarDelegate
extension CHLogDetailViewController: UISearchBarDelegate {
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
return true
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchAction(key: searchText)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
searchBar.setShowsCancelButton(false, animated: true)
searchBar.resignFirstResponder()
setupContent()
}
}
<file_sep>//
// DDDebug.swift
// DDDebug
//
// Created by shenzhen-dd01 on 2019/1/16.
// Copyright © 2019 shenzhen-dd01. All rights reserved.
//
import Foundation
public struct DDDebug {
}
// MARK: - CHLog
public extension DDDebug {
/// 显示日志按钮
///
/// - Parameters:
/// - showType: 显示类型
/// - listenUrls: 白名单
public static func setup(with showType: CHLogShowType, listenUrls: [String]?) {
CHURLSession.shared.addNotification()
CHLog.setup(with: showType, listenUrls: listenUrls)
let isLog = showType == .none ? false : true
URLSession.setupSwizzleAndOpenLog(isLog)
}
/// 显示终端打印的日志
///
/// - Parameters:
/// - info: 终端print信息
/// - isError: 是否是错误信息
public static func log(with info: String, isError: Bool = false) {
CHLog.log(with: info, isError: isError)
}
/// 显示网络请求的日志
///
/// - Parameter request: 网络请求描述
public static func log(with request: DDRequstItemProtocol) {
CHLog.log(with: request)
}
}
// MARK: - MethodSwizzling
public extension DDDebug {
/// 显示当前正在显示的试图控制器
public static func showCurrentViewController() {
UIViewController.ch_swizzle()
}
public static func hookURLSession() {
URLSession.ch_swizzle()
}
}
<file_sep>//
// DDPhotoPickerSource.swift
// Photo
//
// Created by USER on 2018/10/25.
// Copyright © 2018年 leo. All rights reserved.
//
import UIKit
import Photos
class DDPhotoPickerSource: NSObject {
//所有cellMode
lazy var modelsArr = [DDPhotoGridCellModel]()
//所有选中的model
lazy var selectedPhotosArr = [DDPhotoGridCellModel]()
//preview的model
lazy var previewPhotosArr = [DDPhotoGridCellModel]()
}
extension DDPhotoPickerSource {
/// 获取缩略图
///
/// - Parameters:
/// - model: model
/// - callBack: 回调
static func imageFromPHImageManager(_ model: DDPhotoGridCellModel?, callBack: @escaping (UIImage?)->()) -> PHImageRequestID {
guard let model = model else {
return 0
}
//之前设置的100 * 100的大小有时候会转换图片失败 解决办法最后一条 http://stackoverflow.com/questions/31037859/phimagemanager-requestimageforasset-returns-nil-sometimes-for-icloud-photos
return DDPhotoImageManager.default().requestTargetImage(for: model.asset, targetSize: CGSize.init(width: 140, height: 140)) { (image, _) in
callBack(image)
}
}
/// 获取预览图
///
/// - Parameters:
/// - model: model
/// - isGIF: 是否是gif
/// - callBack: 回调
/// - Returns: id
static func requestPreviewImage(for model: DDPhotoGridCellModel?, isGIF: Bool? = false, callBack: @escaping (UIImage?)->()) -> PHImageRequestID {
//正常图片获取
return DDPhotoImageManager.default().requestPreviewImage(for: model?.asset,isGIF: model?.isGIF, progressHandler: { (progress: Double, error: Error?, pointer: UnsafeMutablePointer<ObjCBool>, dictionry: Dictionary?) in
//下载进度
}, resultHandler: {(image: UIImage?, dictionry: Dictionary?) in
var downloadFinined = true
if let cancelled = dictionry![PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry![PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry![PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let photoImage = image {
callBack(photoImage)
}
})
}
static func requesetAVPlayerItem(for model: DDPhotoGridCellModel?, callBack: @escaping (AVPlayerItem?)->()) -> PHImageRequestID {
guard let model = model else {
return 0
}
return DDPhotoImageManager.default().requestPlayerItem(forVideo: model.asset, options: nil, resultHandler: { (item, dictionry) in
var downloadFinined = true
if let cancelled = dictionry![PHImageCancelledKey] as? Bool {
downloadFinined = !cancelled
}
if downloadFinined, let error = dictionry![PHImageErrorKey] as? Bool {
downloadFinined = !error
}
if downloadFinined, let resultIsDegraded = dictionry![PHImageResultIsDegradedKey] as? Bool {
downloadFinined = !resultIsDegraded
}
if downloadFinined, let item = item {
callBack(item)
}
})
}
}
extension DDPhotoPickerSource {
/// 初始化previewPhotosArr数组
func getPreviewPhotosArr() {
previewPhotosArr.removeAll()
_ = selectedPhotosArr.map {[weak self] (model) -> Void in
self?.previewPhotosArr.append(model)
}
}
/// 预览时,操作selectedPhotosArr数组
///
/// - Parameter index: 下标
func previewChangSelectedModel(index: Int) {
let model = previewPhotosArr[index]
model.isSelected = !model.isSelected
//selectedPhotosArr删除或添加选中的model
addOrDeleteSelectedModel(model: model)
}
//修改model选中状态
func selectedBtnChangedCellModel(index: Int) {
let model = modelsArr[index]
model.isSelected = !model.isSelected
addOrDeleteSelectedModel(model: model)
}
//添加或删除选中选中的model
func addOrDeleteSelectedModel(model: DDPhotoGridCellModel) {
if selectedModelIsExist(model: model) == true {
//清除下标
model.index = 0
selectedPhotosArr.remove(at: searchSelectedModelIndex(model: model))
} else {
selectedPhotosArr.append(model)
}
//重新将数据中的model排序
sortSelectedPhotosArr()
}
/// 判断当前model是不是在selectedPhotosArr数组中
///
/// - Parameter model: model
/// - Returns: bool
func selectedModelIsExist(model: DDPhotoGridCellModel) -> Bool {
for item in selectedPhotosArr {
if item.localIdentifier == model.localIdentifier {
return true
}
}
return false
}
/// 寻找model在selectedPhotosArr数组中的下标
///
/// - Parameter model: model
/// - Returns: int
func searchSelectedModelIndex(model: DDPhotoGridCellModel) -> Int {
var index = -1
for item in selectedPhotosArr {
index = index + 1
if item.localIdentifier == model.localIdentifier {
return index
}
}
return index
}
/// 将selectedPhotosArr的model重新排序
func sortSelectedPhotosArr() {
for (index, model) in selectedPhotosArr.enumerated() {
model.index = index + 1
}
}
}
<file_sep>//
// Request.swift
// DDRequest
//
// Created by senyuhao on 2018/7/11.
// Copyright © 2018年 dd01. All rights reserved.
//
import Alamofire
import Foundation
import PromiseKit
public protocol HTTPParam { }
extension String: HTTPParam { }
extension Int: HTTPParam { }
extension Float: HTTPParam { }
extension Double: HTTPParam { }
extension Bool: HTTPParam { }
extension Array: HTTPParam { }
extension Dictionary: HTTPParam { }
public class DDRequest {
public static let shared = DDRequest()
// 配置URL信息
public var api: String = ""
// 配置出错ErrorDomain
public var errorDomain: String = ""
// 配置Header
public var header: HTTPHeaders?
// 配置需处理code情况
// eg: [4_003: (EBTool, NSStringFromSelector(#selector(needLogin)))]
public var variableCode: [Int: (target: NSObject, action: String)]?
public class func decode<T: Decodable>(data: Data?, error: Error?) -> (T?, Error?) {
if let data = data {
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let resp = try decoder.decode(T.self, from: data)
return (resp, nil)
} catch {
let err = DDRequest.shared.errorLocal(info: error)
return (nil, err)
}
} else {
let error = DDRequest.shared.errorLocal(info: error)
return (nil, error)
}
}
private func errorLocal(info: Error?) -> Error? {
if let error = info as NSError? {
if let variableCode = DDRequest.shared.variableCode,
let performValue = variableCode[error.code] {
performValue.target.perform(NSSelectorFromString(performValue.action), with: nil)
}
let err = NSError(domain: DDRequest.shared.errorDomain,
code: error.code,
userInfo: [NSLocalizedDescriptionKey: error.localizedDescription])
return err
}
return nil
}
}
// MARK: 泛型解析 直接回调结果
extension DDRequest {
public class func get<T>(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil,
result: @escaping (T?, Error?) -> Void) where T: Decodable {
DDRequest.shared.get(path: path,
params: params,
cache: cache,
handler: handler) { data, error in
let value: (T?, Error?) = decode(data: data, error: error)
result(value.0, value.1)
}
}
public class func post<T>(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil,
result: @escaping(T?, Error?) -> Void) where T: Decodable {
DDRequest.shared.post(path: path,
params: params,
cache: cache,
handler: handler) { data, error in
let value: (T?, Error?) = decode(data: data, error: error)
result(value.0, value.1)
}
}
/// 图片上传
public class func post<T: Decodable>(path: String,
params: [String: HTTPParam],
image: UIImage,
name: String,
handler: ((DataRequest) -> Void)? = nil,
step: @escaping (Double) -> Void,
result: @escaping ((T?, Error?) -> Void)) {
DDRequest.shared.send(path: path,
method: .post,
image: image,
name: name,
params: params,
handler: handler,
step: step) { data, error in
let value: (T?, Error?) = decode(data: data, error: error)
result(value.0, value.1)
}
}
private func get(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil,
result: @escaping(Data?, Error?) -> Void) {
send(path: path,
method: .get,
cache: cache,
params: params,
handler: handler,
result: result)
}
private func post(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil,
result: @escaping(Data?, Error?) -> Void) {
send(path: path,
method: .post,
cache: cache,
params: params,
handler: handler,
result: result)
}
private func send(path: String,
method: HTTPMethod,
cache: Bool? = nil,
params: [String: HTTPParam],
handler: ((DataRequest) -> Void)? = nil,
result: @escaping(Data?, Error?) -> Void) {
let status = cacheStatus(method: method, cache: cache)
let url = "\(DDRequest.shared.api)/\(path)"
let req = request(url,
method: method,
parameters: params.flat(nil),
encoding: URLEncoding.default,
headers: DDRequest.shared.header)
if status, let value = CacheManager.share.objecSync(forKey: cacheKey(url, params)) {
result(value as Data, nil)
}
handler?(req)
req.responseData { response in
if status, let value = response.value {
CacheManager.share.setObject(value, forKey: cacheKey(url, params))
}
self.printData(value: response.value)
result(response.value, response.error)
}
}
private func cacheStatus(method: HTTPMethod, cache: Bool? = nil) -> Bool {
if let cache = cache {
return cache
} else if method == .get {
return true
} else if method == .post {
return false
} else {
return false
}
}
/// 图片上传
private func post(path: String,
params: [String: HTTPParam],
image: UIImage,
name: String,
handler: ((DataRequest) -> Void)? = nil,
step: @escaping (Double) -> Void,
result: @escaping ((Data?, Error?) -> Void)) {
send(path: path,
method: .post,
image: image,
name: name,
params: params,
handler: handler,
step: step,
result: result)
}
private func send(path: String,
method: HTTPMethod,
image: UIImage,
name: String,
params: [String: HTTPParam],
handler: ((DataRequest) -> Void)? = nil,
step: @escaping (Double) -> Void,
result: @escaping (Data?, Error?) -> Void) {
let url = "\(DDRequest.shared.api)/\(path)"
if let imageData = image.jpegData(compressionQuality: 1.0) {
upload(multipartFormData: { formData in
formData.append(imageData,
withName: name,
fileName: Date().timeIntervalSince1970.description + ".jpeg",
mimeType: "image/jpeg")
for(key, value) in params {
if let data = "\(value)".data(using: .utf8) {
formData.append(data, withName: key)
}
}
},
usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold,
to: url,
method: .post,
headers: DDRequest.shared.header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseData { response in
self.printData(value: response.data)
result(response.data, response.error)
}
upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
step(progress.fractionCompleted)
}
case .failure(let encodingError):
result(nil, encodingError)
}
})
}
}
}
// MARK: - 泛型解析 + block回调上次请求结果 + promise
extension DDRequest {
public class func get<T>(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil) -> Promise<T> where T: Decodable {
return DDRequest.shared.get(path: path,
params: params,
cache: cache,
handler: handler)
}
public class func post<T>(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil,
previous: ((T) -> Void)? = nil) -> Promise<T> where T: Decodable {
return DDRequest.shared.post(path: path,
params: params,
cache: cache,
handler: handler,
previous: previous)
}
public class func post<T>(path: String,
params: [String: HTTPParam],
image: UIImage,
name: String,
handler: ((DataRequest) -> Void)? = nil,
step: @escaping(Double) -> Void) -> Promise<T> where T: Decodable {
return DDRequest.shared.post(path: path,
params: params,
image: image,
name: name,
handler: handler,
step: step)
}
/// Get
private func get<T>(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil,
previous: ((T) -> Void)? = nil) -> Promise<T> where T: Decodable {
return send(path: path,
method: .get,
cache: cache,
params: params,
handler: handler,
previous: previous)
}
/// Post
private func post<T>(path: String,
params: [String: HTTPParam],
cache: Bool? = nil,
handler: ((DataRequest) -> Void)? = nil,
previous: ((T) -> Void)? = nil) -> Promise<T> where T: Decodable {
return send(path: path,
method: .post,
cache: cache,
params: params,
handler: handler,
previous: previous)
}
/// 图片上传
public func post<T>(path: String,
params: [String: HTTPParam],
image: UIImage,
name: String,
handler: ((DataRequest) -> Void)? = nil,
step: @escaping(Double) -> Void) -> Promise<T> where T: Decodable {
return send(path: path,
method: .post,
image: image,
name: name,
params: params,
handler: handler,
step: step)
}
private func send<T>(path: String,
method: HTTPMethod,
cache: Bool? = nil,
params: [String: HTTPParam],
handler: ((DataRequest) -> Void)? = nil,
previous: ((T) -> Void)? = nil) -> Promise<T> where T: Decodable {
let url = "\(DDRequest.shared.api)/\(path)"
let status = cacheStatus(method: method, cache: cache)
if status, let value = CacheManager.share.objecSync(forKey: cacheKey(url, params)) {
let result: (T?, Error?) = DDRequest.decode(data: value as Data, error: nil)
if let model = result.0 {
debugPrint("previous model:\(model)")
previous?(model)
}
}
return Promise { seal in
let req = request(url,
method: method,
parameters: params.flat(nil),
encoding: URLEncoding.default,
headers: DDRequest.shared.header)
handler?(req)
req.responseData(completionHandler: { response in
if status, let value = response.value {
CacheManager.share.setObject(value, forKey: cacheKey(url, params))
}
self.printData(value: response.data)
self.decodeResponse(response: response, seal: seal)
})
}
}
// 处理图片上传
private func send<T>(path: String,
method: HTTPMethod,
image: UIImage,
name: String,
params: [String: HTTPParam],
handler: ((DataRequest) -> Void)? = nil,
step: @escaping(Double) -> Void) -> Promise<T> where T: Decodable {
let url = "\(DDRequest.shared.api)/\(path)"
return Promise { seal in
if let imageData = image.jpegData(compressionQuality: 1.0) {
upload(multipartFormData: { formData in
formData.append(imageData,
withName: name,
fileName: Date().timeIntervalSince1970.description + ".jpeg",
mimeType: "image/jpeg")
for(key, value) in params {
if let data = "\(value)".data(using: .utf8) {
formData.append(data, withName: key)
}
}
},
usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold,
to: url,
method: .post,
headers: DDRequest.shared.header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseData { response in
debugPrint("✅" + upload.debugDescription)
self.decodeResponse(response: response, seal: seal)
}
upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
debugPrint("图片上传进度: \(progress.fractionCompleted)")
step(progress.fractionCompleted)
}
case .failure(let encodingError):
debugPrint(encodingError)
}
})
}
}
}
private func decodeResponse<T: Decodable>(response: DataResponse<Data>, seal: Resolver<T>) {
if let value = response.value {
decodeData(data: value, seal: seal)
} else {
let err = DDRequest.shared.errorLocal(info: response.error)
seal.resolve(err, nil)
}
}
private func decodeData<T: Decodable>(data: Data, seal: Resolver<T>) {
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let resp = try decoder.decode(T.self, from: data)
seal.resolve(nil, resp)
} catch {
let err = DDRequest.shared.errorLocal(info: error)
seal.resolve(err, nil)
}
}
// 数据打印
private func printData(value: Data?) {
if let value = value,
let json = try? JSONSerialization.jsonObject(with: value,
options: .allowFragments) as? [String: Any],
let jsonString = json?.description {
debugPrint("======数据请求完成======")
print("\(jsonString)")
} else {
debugPrint("======数据请求失败======")
}
}
}
extension Array {
func mapDictionary<T>(_ transform: (Int, Element) -> T) -> [T: Element] {
var dic = [T: Element]()
for (index, item) in enumerated() {
dic[transform(index, item)] = item
}
return dic
}
}
extension Dictionary {
func mapKeys<T>(_ transform: (Dictionary.Key) -> T) -> [T: Dictionary.Value] {
var dic = [T: Dictionary.Value]()
for (key, value) in self {
dic[transform(key)] = value
}
return dic
}
}
extension Dictionary where Key == String {
func flat(_ rootKey: Key?) -> [Key: Value] {
var dic = [Key: Value]()
var newDic = self
if let rootKey = rootKey {
newDic = mapKeys { "\(rootKey)[\($0)]" }
}
for (key, value) in newDic {
var dicValue = value as? [Key: Value]
if let arrayValue = value as? [Value] {
dicValue = arrayValue.mapDictionary { index, _ in "\(index)" }
}
if let dicValue = dicValue {
dic.merge(dicValue.flat(key)) { value, _ in value }
} else {
dic[key] = value
}
}
return dic
}
}
<file_sep>//
// Action.swift
// MediatorDemo
//
// Created by weiwei.li on 2019/3/19.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
public class Action {
var method = ""
var cls = ""
var parameters: Parameter?
}
public extension Action {
static func action(cls: String, method mtd: String, parameters pa: Parameter?) -> Action {
if cls.isEmpty {
assert(false, "Action----class名不能为空")
}
if cls.isEmpty {
assert(false, "Action----method名不能为空")
}
let act = Action()
act.cls = cls
act.method = mtd
act.parameters = pa
return act
}
}
<file_sep>//
// Extension.swift
// Route
//
// Created by 鞠鹏 on 6/4/2018.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
extension String {
init<T>(_ instance: T) {
self.init(describing: instance)
}
}
/// 通过 T 转成字符串
///
/// Parameter instance: T
/// Return: T 名
public func convertString<T>(_ instance: T) -> String {
return String(instance)
}
<file_sep>source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/aliyun/aliyun-specs.git'
source 'https://github.com/hk01-digital/hk01-ios-uikit-spec.git'
platform :ios, '9.0'
target 'ChainableDemo' do
use_frameworks!
#pod 'DDKit/Chainable'
pod 'RxSwift', '~> 4.0'
pod 'RxCocoa', '~> 4.0'
pod 'SnapKit'
end
<file_sep>
//
// MediatorController.swift
// Example
//
// Created by USER on 2018/12/5.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
class MediatorController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
<file_sep>
//
// DDLandscapeManager.swift
// DDKit
//
// Created by USER on 2018/11/16.
// Copyright © 2018 dd01. All rights reserved.
//
import UIKit
public class DDLandscapeManager: NSObject {
public static let shared = DDLandscapeManager()
public var isForceLandscape:Bool = false //标记是否横屏
}
<file_sep>
//
// UISwitch+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UISwitch {
@discardableResult
func onTintColor(_ color: UIColor?) -> Self {
onTintColor = color
return self
}
@discardableResult
func tintColor(_ color: UIColor) -> Self {
tintColor = color
return self
}
@discardableResult
func thumbTintColor(_ color: UIColor?) -> Self {
thumbTintColor = color
return self
}
@discardableResult
func onImage(_ image: UIImage?) -> Self {
onImage = image
return self
}
@discardableResult
func offImage(_ image: UIImage?) -> Self {
offImage = image
return self
}
@discardableResult
func isOn(_ bool: Bool) -> Self {
isOn = bool
return self
}
}
<file_sep>//
// PageSegmentView.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/18.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
public protocol PageSegmentViewDelegate: NSObjectProtocol {
func segmentView(segmentView: PageSegmentView, didScrollTo index: Int)
}
let kPageSegmentViewCell = "kPageSegmentViewCell"
public class PageSegmentView: UIView {
public var itemWidth: CGFloat = 0.0 {
didSet {
collectionView.reloadData()
}
}
public var itemFont: UIFont = UIFont.systemFont(ofSize: 14) {
didSet {
collectionView.reloadData()
}
}
public var itemTitleNormalColor: UIColor = UIColor(red: 139.0/255.0, green: 142.0/255.0, blue: 147.0/255.0, alpha: 1) {
didSet {
collectionView.reloadData()
}
}
public var itemTitleSelectedColor: UIColor = UIColor(red: 41.0/255.0, green: 41.0/255.0, blue: 41.0/255.0, alpha: 1) {
didSet {
collectionView.reloadData()
}
}
public var itemBackgroudNormalColor: UIColor = UIColor.red {
didSet {
collectionView.reloadData()
}
}
public var itemBackgroudSelectedColor: UIColor = UIColor.white {
didSet {
collectionView.reloadData()
}
}
public var bottomLineWidth: CGFloat = 20 {
didSet {
collectionView.reloadData()
}
}
public var bottomLineHeight: CGFloat = 2.0 {
didSet {
collectionView.reloadData()
}
}
public var bottomLineColor: UIColor = UIColor(red: 67.0/255.0, green: 116.0/255.0, blue: 1, alpha: 1) {
didSet {
collectionView.reloadData()
}
}
public var segmentBackgroudColor: UIColor = UIColor.white {
didSet {
collectionView.backgroundColor = segmentBackgroudColor
}
}
public var itemList: [String]? {
didSet {
collectionView.reloadData()
}
}
public weak var delegate: PageSegmentViewDelegate?
private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flowLayout.scrollDirection = .horizontal
return flowLayout
}()
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewLayout)
collectionView.backgroundColor = UIColor.white
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(PageSegmentViewCell.self, forCellWithReuseIdentifier: kPageSegmentViewCell)
return collectionView
}()
private var currentIndex = 0
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
/// 调整所有item的尺寸,保证item高度和segmentView高度相等
collectionView.frame = bounds
collectionViewLayout.itemSize = CGSize(width: itemWidth, height: frame.height)
collectionView.reloadData()
collectionView.scrollToItem(at: IndexPath(row: currentIndex, section: 0), at: .centeredHorizontally, animated: true)
}
public func scrollToIndex(_ index: Int) {
if currentIndex == index {
return
}
if index >= itemList?.count ?? -1 {
return
}
setSelectIndex(IndexPath(row: index, section: 0))
}
}
extension PageSegmentView: UICollectionViewDataSource, UICollectionViewDelegate {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemList?.count ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPageSegmentViewCell, for: indexPath) as! PageSegmentViewCell
cell.displayCell(title: itemList?[indexPath.row] ?? "",
font: itemFont,
itemTitleSelectedColor: itemTitleSelectedColor,
itemTitleNormalColor: itemTitleNormalColor,
itemBackgroudNormalColor: itemBackgroudNormalColor,
itemBackgroudSelectedColor: itemBackgroudSelectedColor,
bottomLineWidth: bottomLineWidth ,
bottomLineHeight: bottomLineHeight,
bottomLineColor: bottomLineColor,
currentIndex: currentIndex,
indexPath: indexPath)
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
setSelectIndex(indexPath)
}
}
extension PageSegmentView {
private func setSelectIndex(_ indexPath: IndexPath) {
currentIndex = indexPath.row
collectionView.reloadData()
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
delegate?.segmentView(segmentView: self, didScrollTo: currentIndex)
}
}
<file_sep>//
// ViewController.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: ChainableTableView!
override func viewDidLoad() {
super.viewDidLoad()
// 1. removeConstraints
// 2. makeConstraints
// 3. remakeConstraints
// 4. updateConstraints
UILabel()
.add(to: view)
.backgroundColor(UIColor.red)
.removeConstraints()
.makeConstraints { (make) in
make.top.equalTo(100)
make.left.equalTo(100)
make.width.equalTo(100)
make.height.equalTo(100)
}
.remakeConstraints { (make) in
make.top.equalTo(100)
make.left.equalTo(100)
make.width.equalTo(200)
make.height.equalTo(100)
}
.updateConstraints { (make) in
make.height.equalTo(200)
}
//接受通知 。无需再deinit中释放
addNotifiObserver(name: "a") { (notifi) in
print("ViewController接收到: \(notifi.userInfo.debugDescription)")
}
addNotifiObserver(name: "b") { (notifi) in
print("ViewController接收到: \(notifi.userInfo.debugDescription)")
}
let titles = [
"1、UITextField",
"2、UIKit+Chainable(UIView,UILabel, UIButton, UIImageView等.....)",
"3、TableView",
"4、TextView",
"5、ScrollView",
"6、CollectionView",
"7、SearchBar",
"8、Notification",
"9、设置navigationItem & 导航栏渐变"
]
tableView
.register(for: UITableViewCell.self, cellReuseIdentifier: "ChainableVCCell")
.estimatedRowHeight(50)
.estimatedSectionHeaderHeight(0.1)
.estimatedSectionFooterHeight(0.1)
.addNumberOfRowsInSectionBlock { (tab, sec) -> (Int) in
return titles.count
}
.addCellForRowAtIndexPathBlock {[weak self] (tab, indexPath) -> (UITableViewCell) in
if let cell = self?.tableView.dequeueReusableCell(withIdentifier: "ChainableVCCell", for: indexPath) {
cell.textLabel?.text = titles[indexPath.row]
return cell
}
return UITableViewCell()
}
.addDidSelectRowAtIndexPathBlock({[weak self] (tab, indexPath) in
tab.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
let vc = TextFieldVC()
self?.navigationController?.pushViewController(vc, animated: true)
//测试通知使用
self?.postNotification(name: "a", object: nil, userInfo: ["name": "lisi"])
self?.postNotification(name: "b", object: nil, userInfo: ["name": "wangwu"])
return
}
if indexPath.row == 1 {
let vc = UIKitChainableVC()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
if indexPath.row == 2 {
let vc = TableViewVC()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
if indexPath.row == 3 {
let vc = TextViewVC()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
if indexPath.row == 4 {
let vc = ScrollViewVC()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
if indexPath.row == 5 {
let vc = CollectionViewVC()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
if indexPath.row == 6 {
let vc = SearchBarVC()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
if indexPath.row == 7 {
let vc = NotificationVC()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
if indexPath.row == 8 {
let vc = TableViewController()
self?.navigationController?.pushViewController(vc, animated: true)
return
}
})
.reload()
}
}
<file_sep>//
// Sub3ViewController.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/20.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
class Sub3ViewController: UIViewController {
let segmentView = PageSegmentView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
let list = ["列表1", "列表2", "列表3", "列表4", "列表5", "列表6"]
segmentView.itemList = list
segmentView.delegate = self
segmentView.itemWidth = 100
segmentView.bottomLineWidth = 20
segmentView.bottomLineHeight = 2
view.addSubview(segmentView)
//初始化默认选择
segmentView.scrollToIndex(5)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if #available(iOS 11.0, *) {
segmentView.frame = CGRect(x: 0, y: view.safeAreaInsets.top, width: view.bounds.width, height: 44)
} else {
segmentView.frame = CGRect(x: 0, y: 64, width: view.bounds.width, height: 44)
}
}
}
extension Sub3ViewController: PageSegmentViewDelegate {
func segmentView(segmentView: PageSegmentView, didScrollTo index: Int) {
print(index)
}
}
<file_sep>//
// SheetTool.swift
// Sheet
//
// Created by senyuhao on 2018/7/1.
// Copyright © 2018年 dd01. All rights reserved.
//
import SnapKit
import UIKit
public class SheetTool: NSObject {
public static let shared = SheetTool()
public var titlesColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
public var cancelColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
public var destructiveColor = #colorLiteral(red: 0.9316427112, green: 0.1361732781, blue: 0.1165842786, alpha: 1)
public var font = UIFont.systemFont(ofSize: 16)
public var height: CGFloat = 44.0
public var messageFont = UIFont.systemFont(ofSize: 14)
public var titleFont = UIFont.systemFont(ofSize: 16)
public var messageColor = UIColor.lightGray
public func show(value:(title: String?, message: String?, destructive: String?)?,
cancel: String,
titles: [String],
target: UIView,
handler: @escaping(Int) -> Void) {
let sheet = CustomActionSheet(value: value, cancel: cancel, titles: titles) { tag in
handler(tag)
}
let height = CGFloat(titles.count + 1) * (SheetTool.shared.height + 0.5) + 5
var currentHeight: CGFloat = height
if let value = value {
if value.destructive != nil {
currentHeight += SheetTool.shared.height
}
if value.message != nil {
currentHeight += 30
}
if value.title != nil {
currentHeight += 40
}
}
sheet.show(target: target, height: currentHeight)
}
public func show(value:(title: String?, message: String?)? = nil,
cancel: String,
titles: [String],
target: UIView,
handler: @escaping(Int) -> Void) {
SheetTool.shared.show(value: (title: value?.title, message: value?.message, destructive: nil), cancel: cancel, titles: titles, target: target, handler: handler)
}
}
class CustomActionSheet: UIView {
private var sheetBlock: ((Int) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = #colorLiteral(red: 0.9647058824, green: 0.9725490196, blue: 0.9803921569, alpha: 1)
}
convenience init(value:(title: String?, message: String?, destructive: String?)? = nil,
cancel: String,
titles: [String],
handler: @escaping(Int) -> Void) {
self.init(frame: .zero)
sheetBlock = handler
let cancelBtn = createCancelBtn(cancel: cancel)
for (index, value) in titles.enumerated() {
let offset = -(5.0 + (SheetTool.shared.height + 0.5) * CGFloat(index))
let button = configButton(tag: index + 1, title: value, color: SheetTool.shared.titlesColor)
addSubview(button)
button.snp.makeConstraints { make in
make.bottom.equalTo(cancelBtn.snp.top).offset(offset)
make.left.right.equalTo(self)
make.height.equalTo(SheetTool.shared.height)
}
}
if let value = value {
var offset = -(5.0 + (SheetTool.shared.height + 0.5) * CGFloat(titles.count))
if let destructive = value.destructive {
let destructiveBtn = configButton(tag: titles.count + 1, title: destructive, color: SheetTool.shared.destructiveColor)
addSubview(destructiveBtn)
destructiveBtn.snp.makeConstraints { make in
make.bottom.equalTo(cancelBtn.snp.top).offset(offset)
make.left.right.equalTo(self)
make.height.equalTo(SheetTool.shared.height)
}
offset -= SheetTool.shared.height
}
if let message = value.message {
let messageLabel = configLabel(title: message,
font: SheetTool.shared.messageFont,
color: SheetTool.shared.messageColor)
addSubview(messageLabel)
messageLabel.snp.makeConstraints { make in
make.bottom.equalTo(cancelBtn.snp.top).offset(offset)
make.left.right.equalTo(self)
make.height.equalTo(30)
}
offset -= 30
}
if let title = value.title {
let titleLabel = configLabel(title: title,
font: SheetTool.shared.titleFont,
color: SheetTool.shared.titlesColor)
addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.bottom.equalTo(cancelBtn.snp.top).offset(offset)
make.left.right.equalTo(self)
make.height.equalTo(40)
}
}
}
}
private func createCancelBtn(cancel: String) -> UIButton {
let cancelBtn = configButton(tag: 0, title: cancel, color: SheetTool.shared.cancelColor)
addSubview(cancelBtn)
cancelBtn.snp.makeConstraints { make in
make.bottom.equalTo(self)
make.left.right.equalTo(self)
make.height.equalTo(SheetTool.shared.height)
}
return cancelBtn
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func show(target: UIView, height: CGFloat) {
let window = target is UIWindow ? target : target.window
if let window = window {
let groundView = UIView(frame: .zero)
groundView.tag = NSIntegerMax
window.addSubview(groundView)
groundView.snp.makeConstraints { make in
make.top.left.right.equalTo(window)
if #available(iOS 11.0, *) {
make.bottom.equalTo(window.safeAreaLayoutGuide.snp.bottom)
} else {
make.bottom.equalTo(window)
}
}
let maskView = UIView(frame: .zero)
maskView.backgroundColor = #colorLiteral(red: 0.1960784314, green: 0.2, blue: 0.2, alpha: 0.3)
maskView.alpha = 0
groundView.addSubview(maskView)
maskView.snp.makeConstraints { make in
make.top.left.right.bottom.equalTo(groundView)
}
let gesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureAction))
maskView.addGestureRecognizer(gesture)
groundView.addSubview(self)
snp.makeConstraints { make in
make.bottom.left.right.equalTo(groundView)
make.height.equalTo(height)
}
transform = CGAffineTransform(translationX: 0, y: height)
UIView.animate(withDuration: 0.4) { [weak self] in
maskView.alpha = 1
self?.transform = CGAffineTransform(translationX: 0, y: 0)
}
}
}
private func configButton(tag: Int, title: String, color: UIColor) -> UIButton {
let button = UIButton(type: .custom)
button.tag = tag
button.setTitle(title, for: .normal)
button.setTitleColor(color, for: .normal)
button.titleLabel?.font = SheetTool.shared.font
button.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
button.addTarget(self, action: #selector(buttonAction(_ :)), for: .touchUpInside)
return button
}
private func configLabel(title: String, font: UIFont, color: UIColor) -> UILabel {
let label = UILabel(frame: .zero)
label.textColor = color
label.font = font
label.text = title
label.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
label.textAlignment = .center
return label
}
@objc private func buttonAction(_ sender: UIButton) {
sheetBlock?(sender.tag)
dismiss()
}
@objc private func tapGestureAction() {
dismiss()
}
private func dismiss() {
let height = frame.size.height
UIView.animate(withDuration: 0.3,
animations: { [weak self] in
self?.transform = CGAffineTransform(translationX: 0, y: height)
},
completion: { [weak self] finished in
if finished {
if self?.superview?.tag == NSIntegerMax {
self?.superview?.removeFromSuperview()
}
}
})
}
}
<file_sep>
//
// DDVideoPlayer.swift
// mpdemo
//
// Created by leo on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import Foundation
import AVFoundation
import Alamofire
public class DDVideoPlayer: NSObject {
//播放视图
public var displayView : DDVideoPlayerView
//gravity设置
public var gravityMode : DDVideoGravityMode = .resize
//后台播放模式
public var backgroundMode : DDPlayerBackgroundMode = .autoPlayAndPaused
//buffer time
public var bufferInterval : TimeInterval = 2.0
//设置代理回调
public weak var delegate : DDVideoPlayerDelegate?
//文件格式
public var mediaFormat : DDVideoPlayerMediaFormat
//视屏总时长
public var totalDuration : TimeInterval = 0.0
//当前播放时长
public var currentDuration : TimeInterval = 0.0
//当前播放url
public var contentURL : URL?
//网络监测
private let reachabilityManager = NetworkReachabilityManager()
//是否自动触发横屏
public var isEnableLandscape = false
//tableCells竖屏播放是否执行定时器自动隐藏播放界面的底部栏
public var isHiddenCellPlayBottomBar = true
//player
public var player : AVPlayer? {
willSet{
removePlayerObservers()
}
didSet {
addPlayerObservers()
}
}
//是否在缓冲
public var buffering : Bool = false
//监听player时间回调
private var timeObserver: Any?
//playerItem
private var playerItem : AVPlayerItem? {
willSet {
removePlayerItemObservers()
removePlayerNotifations()
}
didSet {
addPlayerItemObservers()
addPlayerNotifications()
}
}
//playerAsset
private var playerAsset : AVURLAsset?
//错误信息
private var error : DDVideoPlayerError
//是否在seek
private var seeking : Bool = false
//当前播放状态
public var state: DDPlayerState = .none {
didSet {
if state != oldValue {
self.displayView.playStateDidChange(state)
self.delegate?.ddPlayer(self, stateDidChange: state)
}
}
}
//当前缓冲状态
public var bufferState : DDPlayerBufferstate = .none {
didSet {
if bufferState != oldValue {
self.displayView.bufferStateDidChange(bufferState)
self.delegate?.ddPlayer(self, bufferStateDidChange: bufferState)
}
}
}
//MARK:- life cycle
public init(URL: URL?, playerView: DDVideoPlayerView?) {
mediaFormat = DDVideoPlayerUtils.decoderVideoFormat(URL)
contentURL = URL
error = DDVideoPlayerError()
if let view = playerView {
displayView = view
} else {
displayView = DDVideoPlayerView()
}
super.init()
if contentURL != nil {
configurationPlayer(contentURL!)
}
//必须要加,否则真机插拔耳机会没声音
if #available(iOS 10.0, *) {
let _ = try?
AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
}
}
public convenience init(URL: URL) {
self.init(URL: URL, playerView: nil)
}
public convenience init(playerView: DDVideoPlayerView) {
self.init(URL: nil, playerView: playerView)
}
public override convenience init() {
self.init(URL: nil, playerView: nil)
}
deinit {
removePlayerNotifations()
cleanPlayer()
displayView.removeFromSuperview()
reachabilityManager?.stopListening()
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - public
extension DDVideoPlayer {
public func replaceVideo(_ URL: URL?) {
guard let url = URL else {
return
}
contentURL = url
reloadPlayer()
mediaFormat = DDVideoPlayerUtils.decoderVideoFormat(url)
configurationPlayer(url)
}
public func play() {
if contentURL == nil { return }
player?.play()
state = .playing
displayView.play()
initializeReachability()
}
public func cleanPlayer() {
player?.pause()
player?.cancelPendingPrerolls()
player?.replaceCurrentItem(with: nil)
player = nil
playerAsset?.cancelLoading()
playerAsset = nil
playerItem?.cancelPendingSeeks()
playerItem = nil
}
public func isPlay() -> Bool {
if player?.rate != 0 {
return true
}
return false
}
public func pause() {
guard state == .paused else {
player?.pause()
state = .paused
displayView.pause()
return
}
}
public func seekTime(_ time: TimeInterval) {
seekTime(time, completion: nil)
}
public func seekTime(_ time: TimeInterval, completion: ((Bool) -> Void)?) {
if time.isNaN || playerItem?.status != .readyToPlay {
if completion != nil {
completion!(false)
}
return
}
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.seeking = true
strongSelf.startPlayerBuffering()
strongSelf.playerItem?.seek(to: CMTimeMakeWithSeconds(time, preferredTimescale: Int32(NSEC_PER_SEC)), completionHandler: { (finished) in
DispatchQueue.main.async {
strongSelf.seeking = false
strongSelf.stopPlayerBuffering()
strongSelf.play()
if completion != nil {
completion!(finished)
}
}
})
}
}
}
//MARK: - private
private extension DDVideoPlayer {
func initializeReachability() {
reachabilityManager?.listener = {[weak self] status in
var statusStr: String = ""
var isWifi = false
switch status {
case .unknown:
statusStr = "未识别的网络"
isWifi = true
break
case .notReachable:
statusStr = "不可用的网络(未连接)"
isWifi = true
case .reachable:
if self?.reachabilityManager?.isReachableOnWWAN == true {
statusStr = "2G,3G,4G...的网络"
isWifi = false
} else if self?.reachabilityManager?.isReachableOnEthernetOrWiFi == true {
statusStr = "wifi的网络";
isWifi = true
}
break
}
if isWifi == false && self?.displayView.isAllowNotWifiPlay == false {
self?.displayView.showNoWifiTipView()
self?.cleanPlayer()
}
print(statusStr)
}
reachabilityManager?.startListening()
}
func configurationPlayer(_ URL: URL?) {
guard let URL = URL else {
return
}
self.displayView.setddPlayer(ddPlayer: self)
self.playerAsset = AVURLAsset(url: URL, options: .none)
let keys = ["tracks", "playable"];
playerItem = AVPlayerItem(asset: playerAsset!, automaticallyLoadedAssetKeys: keys)
player = AVPlayer(playerItem: playerItem)
displayView.reloadPlayerView()
}
func reloadPlayer() {
seeking = false
totalDuration = 0.0
currentDuration = 0.0
error = DDVideoPlayerError()
state = .none
buffering = false
bufferState = .none
cleanPlayer()
}
func startPlayerBuffering() {
pause()
bufferState = .buffering
buffering = true
}
func stopPlayerBuffering() {
bufferState = .stop
buffering = false
}
func collectPlayerErrorLogEvent() {
error.playerItemErrorLogEvent = playerItem?.errorLog()?.events
error.error = playerItem?.error
error.extendedLogData = playerItem?.errorLog()?.extendedLogData()
error.extendedLogDataStringEncoding = playerItem?.errorLog()?.extendedLogDataStringEncoding
}
}
//MARK: - Notifation & KVO
private var playerItemContext = 0
private extension DDVideoPlayer {
// time KVO
func addPlayerObservers() {
timeObserver = player?.addPeriodicTimeObserver(forInterval: .init(value: 1, timescale: 1), queue: DispatchQueue.main, using: { [weak self] time in
guard let strongSelf = self else { return }
if let currentTime = strongSelf.player?.currentTime().seconds, let totalDuration = strongSelf.player?.currentItem?.duration.seconds {
strongSelf.currentDuration = currentTime
strongSelf.delegate?.ddPlayer(strongSelf, playerDurationDidChange: currentTime, totalDuration: totalDuration)
strongSelf.displayView.playerDurationDidChange(currentTime, totalDuration: totalDuration)
}
})
}
func removePlayerObservers() {
player?.removeTimeObserver(timeObserver!)
}
func addPlayerItemObservers() {
let options = NSKeyValueObservingOptions([.new, .initial])
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: options, context: &playerItemContext)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges), options: options, context: &playerItemContext)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.playbackBufferEmpty), options: options, context: &playerItemContext)
}
func addPlayerNotifications() {
NotificationCenter.default.addObserver(self, selector: .playerItemDidPlayToEndTime, name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: .applicationWillEnterForeground, name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: .applicationDidEnterBackground, name: UIApplication.didEnterBackgroundNotification, object: nil)
}
func removePlayerItemObservers() {
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status))
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges))
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.playbackBufferEmpty))
}
func removePlayerNotifations() {
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}
}
//MARK--- Notification callBack
extension DDVideoPlayer {
@objc internal func handleDeviceOrientationChange(_ notification: Notification) {
}
@objc internal func playerItemDidPlayToEnd(_ notification: Notification) {
if state != .playFinished {
state = .playFinished
}
}
@objc internal func applicationWillEnterForeground(_ notification: Notification) {
if let playerLayer = displayView.playerLayer {
playerLayer.player = player
}
switch self.backgroundMode {
case .suspend:
pause()
case .autoPlayAndPaused:
play()
case .proceed:
break
}
}
@objc internal func applicationDidEnterBackground(_ notification: Notification) {
if let playerLayer = displayView.playerLayer {
playerLayer.player = nil
}
switch self.backgroundMode {
case .suspend:
pause()
case .autoPlayAndPaused:
pause()
case .proceed:
play()
break
}
}
}
//MARK ---- KVO回调
extension DDVideoPlayer {
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (context != &playerItemContext) {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItem.Status
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .unknown:
startPlayerBuffering()
case .readyToPlay:
bufferState = .readyToPlay
case .failed:
state = .error
collectPlayerErrorLogEvent()
stopPlayerBuffering()
delegate?.ddPlayer(self, playerFailed: error)
displayView.playFailed(error)
}
return
}
if keyPath == #keyPath(AVPlayerItem.playbackBufferEmpty){
if let playbackBufferEmpty = change?[.newKey] as? Bool {
if playbackBufferEmpty {
startPlayerBuffering()
}
}
return
}
if keyPath == #keyPath(AVPlayerItem.loadedTimeRanges) {
// 计算缓冲
let loadedTimeRanges = player?.currentItem?.loadedTimeRanges
if let bufferTimeRange = loadedTimeRanges?.first?.timeRangeValue {
let star = bufferTimeRange.start.seconds // The start time of the time range.
let duration = bufferTimeRange.duration.seconds // The duration of the time range.
let bufferTime = star + duration
if let itemDuration = playerItem?.duration.seconds {
delegate?.ddPlayer(self, bufferedDidChange: bufferTime, totalDuration: itemDuration)
displayView.bufferedDidChange(bufferTime, totalDuration: itemDuration)
totalDuration = itemDuration
if itemDuration == bufferTime {
bufferState = .bufferFinished
}
}
if let currentTime = playerItem?.currentTime().seconds{
if (bufferTime - currentTime) >= bufferInterval && state != .paused {
play()
}
if (bufferTime - currentTime) < bufferInterval {
bufferState = .buffering
buffering = true
} else {
buffering = false
bufferState = .readyToPlay
}
}
return
}
//播放
play()
}
}
}
// MARK: - Selecter
extension Selector {
static let playerItemDidPlayToEndTime = #selector(DDVideoPlayer.playerItemDidPlayToEnd(_:))
static let applicationWillEnterForeground = #selector(DDVideoPlayer.applicationWillEnterForeground(_:))
static let applicationDidEnterBackground = #selector(DDVideoPlayer.applicationDidEnterBackground(_:))
static let handleDeviceOrientationChange = #selector(DDVideoPlayer.handleDeviceOrientationChange(_:))
}
extension DDVideoPlayer {
/// 通过url获取视屏首帧图片
///
/// - Parameters:
/// - url: url
/// - size: size
/// - Returns: image
public static func firstFrame(videoUrl url: URL?, size: CGSize, completion:@escaping (UIImage?)->()) {
guard let url = url else {
completion(nil)
return
}
DispatchQueue.global().async {
let opts = [AVURLAssetPreferPreciseDurationAndTimingKey: false]
let urlAsset = AVURLAsset(url: url, options: opts)
let genarator = AVAssetImageGenerator(asset: urlAsset)
genarator.appliesPreferredTrackTransform = true
genarator.maximumSize = CGSize(width: size.width, height: size.height)
let img = try? genarator.copyCGImage(at: CMTimeMake(value: 0, timescale: 10), actualTime: nil)
DispatchQueue.main.async(execute: {
if let image = img {
completion(UIImage(cgImage: image))
} else {
completion(nil)
}
})
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
return input.rawValue
}
<file_sep>//
// ToastVC.swift
// Example
//
// Created by leo on 2018/7/26.
// Copyright © 2018年 dd01. All rights reserved.
//
import UIKit
import PKHUD
class ToastVC: UITableViewController {
private var items = ["toast-top", "top-center", "top-bottom", "title + message", "toast + circle", "show Window"]
override init(style: UITableView.Style) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") {
cell.textLabel?.text = items[indexPath.row]
return cell
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
view.showToast(msg: "hello", position: .top, duration: 3)
} else if indexPath.row == 1 {
view.showToast(msg: "1231231231")
} else if indexPath.row == 2 {
view.showToast(msg: "12312313", position: .bottom, duration: 2)
} else if indexPath.row == 3 {
view.showToast(msg: "今日的领取次数已经用完", title: "领取成功")
} else if indexPath.row == 4 {
view.showToast(msg: "123123123", circle: true)
} else if indexPath.row == 5 {
UIApplication.shared.keyWindow?.showToast(msg: "123123123")
}
}
}
<file_sep>//
// TestBController.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/19.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import MJRefresh
class TestBController: PageTabsBaseController {
var dataCount = 20
deinit {
print(self)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "TestBController")
tableView.reloadData()
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
self?.loadData()
})
}
func loadData() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.dataCount += 20
self.tableView.mj_footer.resetNoMoreData()
if self.dataCount >= 100 {
self.tableView.mj_footer.endRefreshingWithNoMoreData()
}
self.tableView.reloadData()
}
}
override func requesetPullData(currentIndex: Int) {
super.requesetPullData(currentIndex: currentIndex)
//若正在刷新的tab不是本tab,就不做任何操作
//currentIndex :从0升序。以viewcontrollerList数组中的位置为准
if currentIndex != 1 {
return
}
//实现下拉刷新业务
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.dataCount = 20
self.tableView.mj_footer.state = .idle
//调用父类方法,发送结束通知
self.endPullData()
self.tableView.reloadData()
}
}
}
extension TestBController: UITableViewDelegate, UITableViewDataSource {
/// 下面两个方法重写即可,禁止调用super
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TestBController", for: indexPath)
cell.textLabel?.text = "列表2-----\(indexPath.row)"
return cell
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.1
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
}
<file_sep>//
// MenuViewController.swift
// EatojoyBiz
//
// Created by 胡峰 on 2017/3/8.
// Copyright © 2018年 dd01. All rights reserved.
//
import Foundation
import UIKit
public struct MenuItem {
let title: String
let image: UIImage?
let isShowRedDot: Bool?
let action: () -> Void
public init(title: String,
image: UIImage? = nil,
isShowRedDot: Bool? = nil,
action: @escaping () -> Void) {
self.title = title
self.image = image
self.isShowRedDot = isShowRedDot
self.action = action
}
}
public class OCMenuItem: NSObject {
let menuItem: MenuItem
public init(title: String, image: UIImage?, isShowRedDot: Bool, action:@escaping () -> Void) {
menuItem = MenuItem(title: title, image: image, isShowRedDot: isShowRedDot, action: action)
super.init()
}
}
class MenuPopoverBackgroundView: UIPopoverBackgroundView {
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.shadowColor = UIColor.clear.cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override static func contentViewInsets() -> UIEdgeInsets {
return UIEdgeInsets(top: -9, left: 0, bottom: 9, right: 0)
}
static override func arrowHeight() -> CGFloat {
return 10
}
override static func arrowBase() -> CGFloat {
return 0
}
override var arrowDirection: UIPopoverArrowDirection {
get {
return .up
}
set {
}
}
override var arrowOffset: CGFloat {
get {
return 30
}
set {
}
}
}
public class MenuViewController: PopViewController {
let items: [MenuItem]
override var style: PopControllerStyle {
return .popover
}
override var cornerRadius: CGFloat {
return 6
}
var menuRowHeight: CGFloat = 45
public init(items: [MenuItem]) {
self.items = items
super.init(nibName: nil, bundle: nil)
}
public init(ocItems: [OCMenuItem]) {
var items = [MenuItem]()
for ocItem in ocItems {
items.append(ocItem.menuItem)
}
self.items = items
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
dimmingView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
self.popoverPresentationController?.backgroundColor = UIColor.clear
self.popoverPresentationController?.popoverBackgroundViewClass = MenuPopoverBackgroundView.self
self.preferredContentSize = CGSize(width: 124, height: 120)
self.layoutViews()
}
deinit {
print("MenuViewController deinit")
}
private func layoutViews() {
let max = CGFloat.greatestFiniteMagnitude
let titleWidths = items.map { (sizeWithText(text: ($0.title as NSString), font: UIFont.systemFont(ofSize: 15), size: CGSize(width: max, height: max))).size.width }
let maxWidth = titleWidths.max() ?? 70
self.preferredContentSize = CGSize(width: maxWidth + 80, height: menuRowHeight * CGFloat(items.count) + 30)
if let path = Bundle(for: MenuViewController.classForCoder()).path(forResource: "CoreBundle", ofType: "bundle"), let bundle = Bundle(path: path) {
let image = UIImage(named: "popupIos", in: bundle, compatibleWith: nil)
let backgroundImage = UIImageView(image: image?.resizableImage(withCapInsets: UIEdgeInsets(top: 69, left: 43, bottom: 69, right: 43), resizingMode: .stretch))
backgroundImage.frame = CGRect(x: 0, y: 8, width: self.preferredContentSize.width, height: self.preferredContentSize.height - 20)
backgroundImage.layer.cornerRadius = 3
backgroundImage.clipsToBounds = true
view.addSubview(backgroundImage)
}
for (offset, item) in items.enumerated() {
let button = UIButton(type: .custom)
// button.setImage(item.image, for: .normal)
button.setTitle(item.title, for: .normal)
button.setTitleColor(UIColor.darkGray, for: .normal)
button.frame = CGRect(x: 0, y: CGFloat(offset) * menuRowHeight + 18, width: self.preferredContentSize.width, height: menuRowHeight)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
button.addTarget(self, action: #selector(self.buttonAction(button:)), for: .touchUpInside)
button.tag = 1_155 + offset
view.addSubview(button)
if item.isShowRedDot == true {
let redDotImgeView = UIImageView(image: #imageLiteral(resourceName: "red_notice_small"))
redDotImgeView.frame = CGRect(x: button.frame.width * 0.25, y: button.frame.height * 0.2, width: 10, height: 10)
button.addSubview(redDotImgeView)
}
// let titleWidth = titleWidths[offset]
// let contentWidth = (item.image?.size.width ?? 0) + titleWidth
// var edge = (self.preferredContentSize.width - contentWidth) / 2 - 20
// button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -edge, bottom: 0, right: edge)
// edge -= 15
// button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -edge, bottom: 0, right: edge)
if offset != items.count - 1 {
let line = UIView(frame: CGRect(x: 20, y: CGFloat(offset + 1) * 44 + 18, width: self.view.frame.size.width - 40, height: 1 / UIScreen.main.scale))
line.autoresizingMask = .flexibleWidth
line.backgroundColor = #colorLiteral(red: 0.9333333333, green: 0.9333333333, blue: 0.9333333333, alpha: 1)
view.addSubview(line)
}
}
}
@objc private func buttonAction(button: UIButton) {
let index = button.tag - 1_155
if items.count > index {
removeDimmingView()
dismiss(animated: true) {
self.items[index].action()
}
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
removeShadow()
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeDimmingView()
}
// MARK: - 移除自带的阴影,添加黑色半透明背景蒙层
let dimmingView = UIView()
/// 移除自带的阴影
func removeShadow() {
if let window = UIApplication.shared.delegate?.window {
let transitionView = window?.subviews.filter { subview -> Bool in
type(of: subview) == NSClassFromComponents("UI", "Transition", "View")
}
let patchView = transitionView?.first?.subviews.filter { subview -> Bool in
type(of: subview) == NSClassFromComponents("_", "UI", "Mirror", "Nine", "PatchView")
}
if let imageViews = patchView?.first?.subviews.filter({ subview -> Bool in
type(of: subview) == UIImageView.self
}) {
for imageView in imageViews {
imageView.isHidden = true
}
}
}
}
/// 使用私有类,避免私有 API 扫描检查二进制包的字串
func NSClassFromComponents(_ components: String...) -> AnyClass? {
return NSClassFromString(components.joined())
}
func sizeWithText(text: NSString, font: UIFont, size: CGSize) -> CGRect {
// let attributes = [NSAttributedStringKey.font: font]
// let option = NSStringDrawingOptions.usesLineFragmentOrigin
// let rect:CGRect = text.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
return text.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
}
private func removeDimmingView() {
UIView.animate(withDuration: 0.1,
animations: {
self.dimmingView.alpha = 0
}, completion: { complete in
if complete {
self.dimmingView.removeFromSuperview()
}
})
}
func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) {
if let presentingViewController = presentingViewController {
dimmingView.frame = presentingViewController.view.bounds
dimmingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
dimmingView.alpha = 0
presentingViewController.view.addSubview(dimmingView)
let transitionCoordinator = presentingViewController.transitionCoordinator
transitionCoordinator?.animate(alongsideTransition: { _ in
self.dimmingView.alpha = 1
}, completion: nil)
}
}
func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
removeDimmingView()
return true
}
}
<file_sep>//
// ChainableDemoUITests.swift
// ChainableDemoUITests
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import XCTest
class ChainableDemoUITests: XCTestCase {
let app = XCUIApplication()
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
testTextField()
// testView()
}
func testTextField() {
app.tables.staticTexts["1、UITextField"].tap()
for i in 0..<100 {
print("第\(i)次")
let input1TextField = app.textFields["我是input1"]
input1TextField.tap()
input1TextField.tap()
input1TextField.typeText("1123")
sleep(1)
app.otherElements.containing(.navigationBar, identifier:"ChainableDemo.TextFieldVC").children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.tap()
// app.navigationBars["ChainableDemo.TextFieldVC"].buttons["Back"].tap()
}
}
func testView() {
app.tables/*@START_MENU_TOKEN@*/.staticTexts["2、UIKit+Chainable(UIView,UILabel, UIButton, UIImageView等.....)"]/*[[".cells.staticTexts[\"2、UIKit+Chainable(UIView,UILabel, UIButton, UIImageView等.....)\"]",".staticTexts[\"2、UIKit+Chainable(UIView,UILabel, UIButton, UIImageView等.....)\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app.sliders["0%"].swipeRight()
let app2 = app
app2/*@START_MENU_TOKEN@*/.buttons["吕布"]/*[[".segmentedControls.buttons[\"吕布\"]",".buttons[\"吕布\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app2/*@START_MENU_TOKEN@*/.buttons["曹操"]/*[[".segmentedControls.buttons[\"曹操\"]",".buttons[\"曹操\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app2/*@START_MENU_TOKEN@*/.buttons["白起"]/*[[".segmentedControls.buttons[\"白起\"]",".buttons[\"白起\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app.buttons["按钮"].tap()
let navIconBackBlackImage = app.images["nav_icon_back_black"]
navIconBackBlackImage.tap()
navIconBackBlackImage.tap()
let element = app.otherElements.containing(.navigationBar, identifier:"ChainableDemo.UIKitChainableVC").children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element
element.tap()
element.tap()
}
}
<file_sep>//
// UIControl+Chainable.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/11.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
public extension UIKitChainable where Self: UIControl {
/// addTargetAction
///
/// - Parameter handler: handler
/// - Returns: self
@discardableResult
func addActionTouchUpInside(_ handler: @escaping (Self) -> Void) -> Self {
action(.touchUpInside, handler)
return self
}
/// 添加点击事件
///
/// - Parameters:
/// - event: UIControlEvents
/// - handler: 回调
/// - Returns: self
@discardableResult
func addAction(events event: UIControl.Event, handler: @escaping (Self) -> Void) -> Self {
action(event, handler)
return self
}
}
<file_sep>//
// CacheManager.swift
// DDRequest
//
// Created by jp on 2018/9/20.
// Copyright © 2018年 dd01. All rights reserved.
//
import Cache
import Foundation
public class CacheManager: NSObject {
public static let share = CacheManager()
private var storage: Storage<Data>?
public override init() {
super.init()
cacheConfig()
}
private func cacheConfig() {
let diskConfig = DiskConfig(name: "RequestCache")
let memoryConfig = MemoryConfig(expiry: .never)
storage = try? Storage(diskConfig: diskConfig,
memoryConfig: memoryConfig,
transformer: TransformerFactory.forCodable(ofType: Data.self))
}
// MARK: 清除全部缓存
public func removeAllCache(completion: @escaping (_ isSuccess: Bool) -> Void) {
storage?.async.removeAll(completion: { result in
DispatchQueue.main.async {
switch result {
case .value: completion(true)
case .error: completion(false)
}
}
})
}
// MARK: 根据key读取缓存
func objecSync(forKey key: String) -> Data? {
do {
return (try storage?.object(forKey: key))
} catch {
return nil
}
}
// MARK: 异步缓存
func setObject(_ object: Data, forKey key: String) {
storage?.async.setObject(object, forKey: key, expiry: nil, completion: { result in
switch result {
case .value:
print("缓存成功")
case .error(let error):
print("缓存失败:\(error)")
}
})
}
// MARK: 根据key删除缓存
func removeObjectCache(_ cacheKey: String, completion: @escaping (_ isSuccess: Bool) -> Void) {
storage?.async.removeObject(forKey: cacheKey, completion: { result in
DispatchQueue.main.async {
switch result {
case .value: completion(true)
case .error: completion(false)
}
}
})
}
}
<file_sep>//
// SubViewController.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/18.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import MJRefresh
class SubViewController: PageTabsContainerController {
deinit {
print(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setConfig()
title = "水电费你就是你发的健康"
// 若需要头部刷新,如下即可
pageContainerView.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
//调用父类方法
self?.requesetPullData()
})
//一定要设置下面属性.否则高度会出错
if #available(iOS 11.0, *) {
pageContainerView.tableView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
//关于导航栏的隐藏,此demo只是提供参考。可任意自己去实现
navigationController?.navigationBar.isTranslucent = true
}
/// 重写父类方法。实现结束刷新
override func endPullData() {
super.endPullData()
pageContainerView.tableView.mj_header.endRefreshing()
}
/// 配置父类信息
func setConfig() {
/// 配置segmentViewItems
segmentViewItems = ["列表1", "列表2", "网页"]
/// 配置segmentView
segmentView.itemWidth = UIScreen.main.bounds.width / CGFloat((segmentViewItems?.count) ?? 1)
segmentView.bottomLineWidth = 20
segmentView.bottomLineHeight = 2
/// 配置headerView
let offset: CGFloat = 0
let imgView = UIImageView()
imgView.image = UIImage(named: "img2.jpg")
imgView.frame = CGRect(x: 0, y: -offset, width: UIScreen.main.bounds.width, height: 200)
let header = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 200-offset))
header.backgroundColor = UIColor.red
header.addSubview(imgView)
headerView = header
/// 配置viewControllerList
var list = [PageTabsBaseController]()
let v1 = TestAController()
list.append(v1)
let v2 = TestBController()
list.append(v2)
let v3 = TestCController()
list.append(v3)
viewControllerList = list
tabsType = .multiWork
/// 初始化默认选择tab
segmentView.scrollToIndex(0)
}
/// 重写滑动监听代理方法,改变导航栏的透明度
///
/// - Parameter scrollView:
override func pageTabsContainerDidScroll(scrollView: UIScrollView) {
super.pageTabsContainerDidScroll(scrollView: scrollView)
// 监听容器的滚动,来设置NavigationBar的透明度
if tabsType == .segmented {
return
}
let offset = scrollView.contentOffset.y
let canScrollHeight = pageContainerView.heightForContainerCanScroll()
setNavigationBackgroundAlpha(offset/canScrollHeight)
}
func setNavigationBackgroundAlpha(_ alpha: CGFloat) {
var alpha = alpha
alpha = alpha > 1 ? 1 : alpha
alpha = alpha < 0 ? 0 : alpha
if alpha == 0.0 {
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
} else {
navigationController?.navigationBar.setBackgroundImage(imageFromColor(color: UIColor.white), for: .default)
}
}
func imageFromColor(color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
<file_sep>//
// CHButton.swift
// CHLog
//
// Created by wanggw on 2018/5/28.
// Copyright © 2018年 UnionInfo. All rights reserved.
//
import UIKit
/// 自定义 UIButton
class CHButton: UIButton {
private var moveEnable: Bool = true //是否可以移动
private var isMoving: Bool = true //设置正在移动的标志
private var beginpoint: CGPoint?
}
extension CHButton {
// MARK: touch event
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isMoving = false
super.touchesBegan(touches, with: event)
if !moveEnable {
return
}
let touch = touches.first
beginpoint = touch?.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
isMoving = true
if !moveEnable {
return
}
let touch = touches.first
let currentPosition: CGPoint? = touch?.location(in: self)
//偏移量
let offsetX = Float((currentPosition?.x ?? 0.0) - (beginpoint?.x ?? 0.0))
let offsetY = Float((currentPosition?.y ?? 0.0) - (beginpoint?.y ?? 0.0))
//移动后的中心坐标
center = CGPoint(x: CGFloat(center.x + CGFloat(offsetX)), y: CGFloat(center.y + CGFloat(offsetY)))
//x轴左右极限坐标
if let superview = superview,
center.x > (superview.frame.size.width - frame.size.width / 2) {
let x: CGFloat = superview.frame.size.width - frame.size.width / 2
center = CGPoint(x: x, y: CGFloat(center.y + CGFloat(offsetY)))
} else if center.x < frame.size.width / 2 {
let x: CGFloat = frame.size.width / 2
center = CGPoint(x: x, y: CGFloat(center.y + CGFloat(offsetY)))
}
//y轴上下极限坐标
if let superview = superview,
center.y > (superview.frame.size.height - frame.size.height / 2) {
let x: CGFloat = center.x
let y: CGFloat = superview.frame.size.height - frame.size.height / 2
center = CGPoint(x: x, y: y)
} else if center.y <= frame.size.height / 2 {
let x: CGFloat = center.x
let y: CGFloat = frame.size.height / 2
center = CGPoint(x: x, y: y)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isMoving = false
if !moveEnable {
return
}
updatePosition()
//不加此句话,UIButton将一直处于按下状态
super.touchesEnded(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
updatePosition()
}
// MARK: update position
private func updatePosition() {
if let superview = superview,
center.x >= superview.frame.size.width / 2 {
UIView.beginAnimations("move", context: nil)
UIView.setAnimationDuration(0.35)
UIView.setAnimationDelegate(self)
frame = CGRect(x: superview.frame.size.width - 60 - 10, y: center.y - 30, width: 60.0, height: 60.0)
UIView.commitAnimations()
} else {
UIView.beginAnimations("move", context: nil)
UIView.setAnimationDuration(0.35)
UIView.setAnimationDelegate(self)
frame = CGRect(x: 0.0 + 10, y: center.y - 30, width: 60.0, height: 60.0)
UIView.commitAnimations()
}
}
}
<file_sep># Chainable - 扩展UIView及其子类,支持链式语法调用
[demo地址](https://github.com/weiweilidd01/Chainable)
目前支持UIView中所有常见的子类,将其可写属性添加链式语法。
支持的UIView及其子类有:
* UIView本身
* UILabel
* UIButton
* UIImageView
* UISlider
* UIProgressView
* UISwitch
* UISegmentedControl
* UITextField
* UITableView -- 替换成ChainableTableView,解决和UIPickerView代理冲突
* UITextView
* UIScrollView
* UICollectionView
* UISearchBar
* Notification
* UIViewController+NavigationBarItem 一行代码给导航栏添加barItem,新增渐变导航栏的透明度
* UIViewController+TopViewController 获得当前app最上层的viewController
* Timer+Block 封装Timer block回调
**除添加系统所有属性外,几大重点关注点:**
* **1、将UIVIew及其子类可直接通过点语法添加单击,双击,长按等手势,还有移除所有子类等常见操作方法。**
* **2、将UIControl中事件加入链式语法**
* **3、将上述所列UIView中有代理属性的类,全部支持链式回调**
* **4、UITextField支持最大字数限制属性**
* **5、UITextView支持最大字数限制属性,支持设置placeholder属性**
* **6、所有的NSObject对象支持一键添加通知,无需removeObserver。**
* **7、集成Snapkit**
### 1.Snapkit布局 --- Example
```
// 1. removeConstraints
// 2. makeConstraints
// 3. remakeConstraints
// 4. updateConstraints
UILabel()
.add(to: view)
.backgroundColor(UIColor.red)
.removeConstraints()
.makeConstraints { (make) in
make.top.equalTo(100)
make.left.equalTo(100)
make.width.equalTo(100)
make.height.equalTo(100)
}
.remakeConstraints { (make) in
make.top.equalTo(100)
make.left.equalTo(100)
make.width.equalTo(200)
make.height.equalTo(100)
}
.updateConstraints { (make) in
make.height.equalTo(200)
}
```
### 2.UIView --- Example
```
//UIView 扩展了单击,双击,长按手势
UIView()
.frame(CGRect(x: 50, y: 400, width: 50, height: 50))
.backgroundColor(UIColor.black)
.sizeFit()
.isUserInteractionEnabled(true)
.addTapGesture { (v, tap) in
print("单击")
}
.addDoubleGesture { (v, tap) in
print("双击")
}
.addLongGesture { (v, long) in
print("长按")
}
.add(to: view)
```
### 3.UILabel --- Example
```
lab.backgroundColor(UIColor.red)
.alpha(0.4)
.border(UIColor.black, 1)
.textAlignment(.center)
.numberOfLines(0)
.font(12)
.frame(CGRect(x: 50, y: 200, width: 200, height: 100))
.text("收到货方式来开发框架地方sdfkhjjhsjfdkh是否点击康师傅")
.textColor(UIColor.green)
.shadowColor(UIColor.black)
.shadowOffset(CGSize(width: 1, height: 2))
.lineBreakMode(.byCharWrapping)
.attributedText(NSAttributedString(string: "是打飞机了就开始发动机"))
.highlightedTextColor(UIColor.purple)
.isHighlighted(true)
.isUserInteractionEnabled(true)
.isEnabled(true)
.adjustsFontSizeToFitWidth(true)
.minimumScaleFactor(10)
```
### 4.UIButton --- Example
```
//Button扩展新功能
//imagePosition 任意切换文字和图片混合button的位置
// 提供TargetAction点击事件。目前只提供.touchUpInside
UIButton(type: .system)
.frame(CGRect(x: 150, y: 400, width: 50, height: 50))
.setTitle("按钮", state: .normal)
.setImage(UIImage(named: "nav_icon_back_black"), state: .normal)
.setTitleColor(UIColor.red, state: .normal)
.add(to: view)
.addActionTouchUpInside({ (btn) in
print("按钮")
})
.font(18)
.imagePosition(.top, space: 10)
```
### 5.UIImageView --- Example
```
UIImageView()
.frame(CGRect(x: 250, y: 400, width: 50, height: 50))
.addTapGesture { (v, tap) in
print("图片")
}
.image(UIImage(named: "nav_icon_back_black"))
.add(to: view)
```
### 6.UISlider --- Example
```
slider
.maximumValue(1.0)
.minimumValue(0)
.value(0)
.maximumTrackTintColor(UIColor.red)
.minimumTrackTintColor(UIColor.blue)
.addAction(events: .valueChanged) {[weak self] (sender) in
print("slider---\(sender.value)")
self?.progressView.setProgress(sender.value, animated: true)
}
```
### 7.UIProgressView --- Example
```
progressView
.progress(0)
.progressViewStyle(.bar)
.progressTintColor(UIColor.green)
.trackTintColor(UIColor.yellow)
```
### 8.UISwitch --- Example
```
switchView
.onTintColor(UIColor.red)
.thumbTintColor(UIColor.black)
.isOn(false)
.addAction(events: .valueChanged) { (s) in
print("switch的值:\(s.isOn)")
}
```
### 9.UISegmentedControl --- Example
```
UISegmentedControl(items: ["吕布", "曹操", "白起","程咬金"])
.frame(CGRect(x: 50, y: 320, width: 200, height: 30))
.tintColor(UIColor.red)
.apportionsSegmentWidthsByContent(true)
.selectedSegmentIndex(1)
.addAction(events: .valueChanged) { (sender) in
print("选中了: \(sender.selectedSegmentIndex)")
}
.add(to: view)
```
### 910.UITextField --- Example
```
// input1 不需要设置代理
//支持最大长度限制
// 支持所有代理协议回调
// 支持输入抖动动画
//通过系统方法设置代理,只走协议方法
//不会走链式block回调
input1.placeholder("我是input1")
.addShouldBegindEditingBlock { (field) -> (Bool) in
return true
}
.addShouldChangeCharactersInRangeBlock { (field, range, text) -> (Bool) in
print("input1: \(text)")
return true
}
.maxLength(5)
.shake(true)
```
### 11.UIScrollView --- Example
```
//支持所有代理回调
scrollView.frame(CGRect(x: 0, y: 100, width: w, height: 200))
.backgroundColor(UIColor.green)
.isPagingEnabled(true)
.bounces(true)
.add(subView: lab1)
.add(subView: lab2)
.add(subView: lab3)
.contentSize(CGSize(width: w * 3, height: 200))
.add(to: view)
.addScrollViewDidScrollBlock { (scroll) in
print(scroll.contentOffset)
}
```
### 12.UITableView(已经替换成ChainableTableView,解决和UIPickerView代理冲突) --- Example
```
// TODO: --
//若用此链式添加UITableViewDelegate代理方法,请注意:
//1、若需要实现自动估值计算。请实现链式中属性方法进行设置,UITableViewDelegate代理方法中的估值方法不再提供接口
//2. 若通过链式获取代理回调,请不要通过系统方法设置代理,tableVie.delegate = self, tableVie.dataSource = self,否则会无效。
//3. 若链式代理无法满足需求。请设置tableVie.delegate = self, tableVie.dataSource = self再自行实现代理
//扩展全部UITableViewDatasource协议
//扩展了90%协议,未扩展协议为冷门协议,对日常使用无影响
tableView
.register(for: UITableViewCell.self, cellReuseIdentifier: "cell")
.register(for: UITableViewHeaderFooterView.self, headerFooterViewReuseIdentifier: "UITableViewHeaderFooterView")
// .estimatedRowHeight(200)
// .estimatedSectionHeaderHeight(100)
// .estimatedSectionFooterHeight(0.1)
.addNumberOfSectionsBlock { (tab) -> (Int) in
return 5
}
.addNumberOfRowsInSectionBlock { (tab, sec) -> (Int) in
return 10
}
.addHeightForRowAtIndexPathBlock({ (tab, indexPath) -> (CGFloat) in
return 100
})
.addHeightForHeaderInSectionBlock({ (tab, section) -> (CGFloat) in
return 50
})
.addViewForHeaderInSectionBlock({ (tab, section) -> (UIView?) in
if let header = tab.dequeueReusableHeaderFooterView(withIdentifier: "UITableViewHeaderFooterView") {
header.textLabel?
.text("我是第\(section)组")
.font(18)
.textColor(UIColor.red)
return header
}
return UIView()
})
.addViewForFooterInSectionBlock({ (tab, section) -> (UIView?) in
return UIView()
})
.addCellForRowAtIndexPathBlock {[weak self] (tab, indexPath) -> (UITableViewCell) in
if let cell = self?.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) {
cell.textLabel?.text = "\(indexPath.section)组" + "-- \(indexPath.row)行"
return cell
}
return UITableViewCell()
}
.addDidSelectRowAtIndexPathBlock({ (tab, indexPath) in
tab.deselectRow(at: indexPath, animated: true)
print("点击了第\(indexPath.section)组,第\(indexPath.row)行")
})
.addScrollViewDidScrollBlock({ (scrollView) in
print(scrollView.contentOffset)
})
.reload()
```
### 13.UITextView --- Example
```
// TODO: 注意
// 若同时初始化 text 和 placeholder,一定要注意先后顺序,placeholder在前,text在后。否则会有点小bug,是系统的问题
//支持最大字数限制
//支持设置placeholder
textView.textColor(UIColor.red)
.addShouldBegindEditingBlock { (t) -> (Bool) in
print("addShouldBegindEditingBlock")
return true
}
.addDidChangeBlock { (t) in
print("addDidChangeBlock")
}
.addShouldChangeTextInRangeReplacementTextBlock { (t, range, text) -> (Bool) in
print(text)
return true
}
.maxLength(5)
.placeholder("我是是否带回家sdfsdf")
// .text("qwqweqew")
```
### 14.UICollectionView --- Example
```
flowLayout.scrollDirection = .vertical
//将所有90%的delegate代理方法支持回调
//所有的datasource支持回调
//所有的UICollectionViewDelegateFlowLayout支持回调
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: w, height: h), collectionViewLayout: flowLayout)
.isPagingEnabled(false)
.registerCell(UICollectionViewCell.self, ReuseIdentifier: "UICollectionViewCell")
.registerSupplementaryView(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, ReuseIdentifier: "UICollectionReusableView")
.addNumberOfSectionsBlock({ (collection) -> (Int) in
return 10
})
.addNumberOfItemsInSectionBlock({ (collection, section) -> (Int) in
return 10
})
.addLayoutCollectionViewLayoutSizeForItemAtIndexPathBlock({[weak self] (collection, layout, indexPath) -> (CGSize) in
return CGSize(width: self?.w ?? 0, height: 200)
})
.addLayoutCollectionViewLayoutReferenceSizeForHeaderInSectionSectionBlock({[weak self] (collection, layout, section) -> (CGSize) in
return CGSize(width: self?.w ?? 0, height: 130)
})
.addCellForItemAtIndexPathBlock({[weak self] (collection, indexPath) -> (UICollectionViewCell) in
if let cell = self?.collectionView?.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath) {
let lab = UILabel(frame: cell.bounds)
.text("\(indexPath.section) : \(indexPath.row)")
.textAlignment(.center)
.font(20)
.backgroundColor(UIColor.green)
cell.contentView
.removeAllSubViews()
.add(subView: lab)
return cell
}
return UICollectionViewCell()
})
.addViewForSupplementaryElementOfKindAtIndexPathBlock({ (collection, kind, indexPath) -> (UICollectionReusableView) in
if kind == UICollectionElementKindSectionHeader {
let header = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "UICollectionReusableView", for: indexPath)
let lab = UILabel()
.frame(header.bounds)
.text("我是第\(indexPath.section)组")
.textColor(UIColor.red)
.font(18)
.textAlignment(.center)
header.removeAllSubViews()
.add(subView: lab)
return header
}
return UICollectionReusableView()
})
.addDidSelectItemAtIndexPathBlock({ (collection, indexPath) in
print("\(indexPath.section): \(indexPath.row)")
})
.backgroundColor(UIColor.white)
.addLongGesture({[weak self](collection, longPress) in
let point = longPress.location(in: collection)
let indexPath = collection.indexPathForItem(at: point)
switch longPress.state {
case .began:
if let index = indexPath {
//开始移动
self?.collectionView?.beginInteractiveMovementForItem(at: index)
}
print("began")
case .changed:
//更新位置坐标
self?.collectionView?.updateInteractiveMovementTargetPosition(point)
print("changed")
case .ended:
//停止移动调用此方法
self?.collectionView?.endInteractiveMovement()
print("end")
default:
//取消移动
self?.collectionView?.cancelInteractiveMovement()
print("default")
break
}
})
.addCanMoveItemAtIndexPathBlock({ (collection, indexPath) -> (Bool) in
return true
})
.addMoveItemAtSourceIndexPathToDestinationIndexPathBlock({ (collection, sourceIndexPath, targetIndexPath) in
print("source: \(sourceIndexPath.section): \(sourceIndexPath.row)")
print("target: \(targetIndexPath.section): \(targetIndexPath.row)")
})
.add(to: view)
.reload()
```
### 15.UISearchBar --- Example
```
//支持所有delegate回调
searchBar
.placeholder("点击我输入")
.tintColor(UIColor.orange)
.addSearchBarShouldBeginEditingBlock { (bar) -> (Bool) in
return true
}
.addSearchBarTextDidBeginEditingBlock({ (bar) in
bar.setShowsCancelButton(true, animated: true)
})
.addSearchBarTextShouldChangeTextInRangeReplacementTextBlock { (bar, text) -> (Bool) in
print(text)
return true
}
.addSearchBarTextDidEndEditingBlock { (bar) in
bar.setShowsCancelButton(false, animated: true)
}
```
### 16.Notification --- Example
```
//接受通知 。无需再deinit中释放
addNotifiObserver(name: "a") { (notifi) in
print("NotificationVC接收到: \(notifi.userInfo.debugDescription)")
}
```
```
//发送通知
self?.postNotification(name: "a", object: nil, userInfo: ["name": "lisi"])
```
## 17.UIViewController+NavigationBarItem
* 用途: 一行代码给导航栏添加barItem
<br/>
1.添加带文字的右边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-b280fa9fa4cc2b27.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
setRightButtonItem(title: "关闭") { (btn) in
//点击事件回调
}
```
2.添加带图片的右边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-e36acc101d6fcd8e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
setRightButtonItem(image: UIImage(named: "icon_follow")) { (btn) in
//点击事件回调
}
```
3.添加自定义图片的右边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-e36acc101d6fcd8e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 12, width: 20, height: 20)
imageView.image = UIImage(named: "icon_follow")
setRightButtonItem(customView: imageView) { (view, tap) in
//点击事件回调
}
```
4.添加多个标题的右边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-e66a00e5803cb245.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
setRightButtonItem(titles: ["关闭", "上传", "取消"]) { (btn) in
//点击事件回调
}
```
5.添加多个图片的右边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-c4084f89ba792794.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
let items = [UIImage(named: "icon_follow"),UIImage(named: "icon_follow")]
setRightButtonItem(images: items) { (btn) in
//点击事件回调
}
```
6.添加带标题的左边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-9b9071a9803b471f.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
setLeftButtonItem(title: "返回") { (btn) in
//点击事件回调
}
```
7.添加带图片的左边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-d31b067e6bf3547e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
setLeftButtonItem(image: UIImage(named: "icon_follow")) { (btn) in
//点击事件回调
}
```
8.添加带图片数组的左边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-08d7f1691e959c4a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
setLeftButtonItem(images: [UIImage(named: "icon_follow"),UIImage(named: "icon_follow")]) { (btn) in
//点击事件回调
}
```
9.添加带标题数组的左边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-8296155c3ff54a90.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
setLeftButtonItem(titles: ["关闭", "上传", "取消"]) { (btn) in
//点击事件回调
}
```
10.添加自定义视图的左边按钮
<img src="https://upload-images.jianshu.io/upload_images/2026287-d31b067e6bf3547e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width=200 height=100 />
```
let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 12, width: 20, height: 20)
imageView.image = UIImage(named: "icon_follow")
setLeftButtonItem(customView: imageView) { (view, tap) in
//点击事件回调
}
```
11.新增渐变导航栏的透明度
```
基本使用说明
第一步
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//此方法必须在willAppear中设置
navigationController?.navigationBar.isTranslucent = true
//进来默认显示透明色
changeNavBackgroundImageWithAlpha(alpha: 0)
}
//滑动监听
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let value = scrollView.contentOffset.y
let alpha = value / 64
changeNavBackgroundImageWithAlpha(alpha: alpha)
}
```
方法说明
```
/// 改变导航栏透明度
///
/// - Parameters:
/// - alpha: 透明值
/// - backgroundColor: 非透明时背景颜色
/// - shadowColor: 非透明是shadow阴影颜色
public func changeNavBackgroundImageWithAlpha(alpha: CGFloat, backgroundColor: UIColor = .white, shadowColor: UIColor = #colorLiteral(red: 0.9311618209, green: 0.9279686809, blue: 0.9307579994, alpha: 1))
```
<file_sep>//
// DDVideoPlayerView.swift
// mpdemo
//
// Created by leo on 2018/10/30.
// Copyright © 2018年 dd01.leo. All rights reserved.
//
import UIKit
import MediaPlayer
import SnapKit
//屏幕旋转动画时长
private let duration = 0.25
open class DDVideoPlayerView: UIView {
weak public var ddPlayer : DDVideoPlayer?
//控制视图显示时长
private var controlViewDuration : TimeInterval = 5.0 /// default 5.0
//player Layer
public var playerLayer : AVPlayerLayer?
//是否全屏
public var isFullScreen : Bool = false {
didSet {
if isFullScreen == false {
removaPanGesture()
} else {
addPanGesture()
}
}
}
//是否拖拽进度条
private var isTimeSliding : Bool = false
//是否允许非wifi播放
public var isAllowNotWifiPlay : Bool = false
//是否显示控制视图
public var isDisplayControl : Bool = true {
didSet {
if isDisplayControl != oldValue {
delegate?.ddPlayerView(didDisplayControl: self)
}
}
}
//播放视图delegate
public weak var delegate : DDPlayerViewDelegate?
// top view
lazy private var topView : UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
return view
}()
//titleLabel
lazy public var titleLabel : UILabel = {
let label = UILabel()
label.textAlignment = .left
label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
label.font = UIFont.boldSystemFont(ofSize: 16.0)
return label
}()
//返回按钮
lazy private var closeButton : UIButton = {
let button = UIButton(type: .custom)
return button
}()
// bottom view
lazy private var bottomView : UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
return view
}()
//亮度显示
lazy private var brightnessView: DDPlayerBrightnessView = {
let brightnessView = DDPlayerBrightnessView()
return brightnessView
}()
//时间lable
private var timeLabel : UILabel = {
let timeLabel = UILabel()
timeLabel.textAlignment = .center
timeLabel.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
timeLabel.font = UIFont.systemFont(ofSize: 12.0)
timeLabel.text = "00:00"
return timeLabel
}()
private var currentLab : UILabel = {
let currentLab = UILabel()
currentLab.textAlignment = .center
currentLab.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
currentLab.font = UIFont.systemFont(ofSize: 12.0)
currentLab.text = "00:00"
return currentLab
}()
//加载失败按钮
lazy private var failedButton: UIButton = {
let button = UIButton(type: .custom)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
button.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
button.isHidden = true
button.setTitle("加载失败,点击重试", for: .normal)
return button
}()
//非wifi提示视图
lazy private var wifiTipsView = DDVideoPlayerTipsView()
//进度条slider
lazy private var timeSlider = DDVideoPlayerSlider ()
//加载显示圈
private var loadingIndicator = DDVideoPlayerLoadingIndicator()
//全屏按钮
private var fullscreenButton : UIButton = UIButton(type: .custom)
//播放按钮
private var playButtion : UIButton = UIButton(type: .custom)
//中间播放按钮
private var centerPlayButtion : UIButton = UIButton(type: .custom)
//声音控制显示图
private var volumeSlider : UISlider!
//重新播放按钮
private var replayButton : UIButton = UIButton(type: .custom)
//手势
private var panGestureDirection : DDPlayerViewPanGestureDirection = .horizontal
//是否是调节声音,false为亮度调节
private var isVolume : Bool = false
//进度条滑动值
private var sliderSeekTimeValue : TimeInterval = .nan
//定时器
private var timer : Timer = {
let time = Timer()
return time
}()
//父视图
private weak var parentView : UIView?
//父视图frame
private var viewFrame = CGRect.zero
// GestureRecognizer
private var singleTapGesture = UITapGestureRecognizer()
private var doubleTapGesture = UITapGestureRecognizer()
private var panGesture: UIPanGestureRecognizer? = UIPanGestureRecognizer()
//MARK:- life cycle
public override init(frame: CGRect) {
self.playerLayer = AVPlayerLayer(player: nil)
super.init(frame: frame)
viewFrame = frame
addDeviceOrientationNotifications()
addGestureRecognizer()
configurationVolumeSlider()
configurationUI()
}
public convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
timer.invalidate()
playerLayer?.removeFromSuperlayer()
NotificationCenter.default.removeObserver(self)
brightnessView.removeFromSuperview()
print(self)
}
open override func layoutSubviews() {
super.layoutSubviews()
playerLayer?.frame = self.bounds
setupSubViewsFrame()
// if isFullScreen && DDVPIsiPhoneX.isIphonex() == true {
// }
}
}
private extension DDVideoPlayerView {
/// 添加屏幕旋转通知
func addDeviceOrientationNotifications() {
//开启和监听 设备旋转的通知
if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
}
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
}
}
//MARK --- 屏幕旋转处理方法集合
extension DDVideoPlayerView {
@objc internal func deviceOrientationDidChange(_ sender: Notification) {
//如果为空,禁止旋转, 如果是tablecell播放,不触发横屏
if ddPlayer?.player == nil || ddPlayer?.isEnableLandscape == false {
return
}
//没有缓冲好就不旋转屏幕
if ddPlayer?.bufferState == .none || ddPlayer?.bufferState == .buffering || ddPlayer?.bufferState == .stop {
return
}
let orientation = UIDevice.current.orientation
//状态栏方向为竖直时,记录父视图及frame
setParentViewAndFrame()
switch orientation {
case .unknown:
break
case .faceDown:
break
case .faceUp:
break
case .landscapeLeft:
onDeviceOrientation(true, orientation: .landscapeLeft)
case .landscapeRight:
onDeviceOrientation(true, orientation: .landscapeRight)
case .portrait:
exitFullscreen()
case .portraitUpsideDown:
break
}
}
private func onDeviceOrientation(_ fullScreen: Bool, orientation: UIInterfaceOrientation) {
if orientation == .landscapeLeft || orientation == .landscapeRight {
let rectInWindow = convert(bounds, to: UIApplication.shared.keyWindow)
self.frame = rectInWindow
UIApplication.shared.keyWindow?.addSubview(self)
brightnessView.removeFromSuperview()
UIApplication.shared.keyWindow?.addSubview(brightnessView)
UIApplication.shared.keyWindow?.bringSubviewToFront(brightnessView)
//执行动画
UIView.animate(withDuration: duration, animations: {
self.transform = self.getTransformRotationAngle(orientation: orientation)
self.brightnessView.transform = self.getTransformRotationAngle(orientation: orientation)
self.bounds = CGRect(x: 0, y: 0, width: self.superview?.bounds.height ?? 0.0, height: self.superview?.bounds.width ?? 0.0)
self.center = CGPoint(x: self.superview?.bounds.midX ?? 0.0, y: self.superview?.bounds.midY ?? 0.0)
self.playerLayer?.frame = self.bounds
self.setupSubViewsFrame()
}) { (finished) in
self.fullscreenButton.isSelected = fullScreen
self.isFullScreen = fullScreen
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
if isDisplayControl == true {
topView.isHidden = false
}
if orientation == .landscapeLeft {
UIApplication.shared.setStatusBarOrientation(.landscapeRight, animated: false)
} else {
UIApplication.shared.setStatusBarOrientation(.landscapeLeft, animated: false)
}
self.delegate?.ddPlayerView(self, willFullscreen: self.isFullScreen, orientation: orientation)
if ddPlayer?.isHiddenCellPlayBottomBar == false {
setupTimer()
}
}
//退出全屏
func exitFullscreen() {
let rectInWindow = parentView?.convert(viewFrame, to: UIApplication.shared.keyWindow)
UIApplication.shared.keyWindow?.addSubview(self)
//执行动画
UIView.animate(withDuration: duration, animations: {
self.transform = self.getTransformRotationAngle(orientation: .portrait)
self.brightnessView.transform = self.getTransformRotationAngle(orientation: .portrait)
self.frame = rectInWindow ?? CGRect.zero
self.playerLayer?.frame = self.bounds
self.setupSubViewsFrame()
}) { (finished) in
self.removeFromSuperview()
self.frame = self.viewFrame
self.playerLayer?.frame = self.bounds
self.parentView?.addSubview(self)
self.fullscreenButton.isSelected = false
self.isFullScreen = false
self.setNeedsLayout()
self.layoutIfNeeded()
}
if isDisplayControl == true {
topView.isHidden = true
}
UIApplication.shared.setStatusBarOrientation(.portrait, animated: false)
self.delegate?.ddPlayerView(self, willFullscreen: self.isFullScreen, orientation: .portrait)
if ddPlayer?.isHiddenCellPlayBottomBar == false {
setupTimer()
}
}
private func getTransformRotationAngle(orientation: UIInterfaceOrientation) -> CGAffineTransform {
if orientation == .portrait {
return .identity
}
if orientation == .landscapeLeft {
return CGAffineTransform(rotationAngle: .pi/2.0)
}
if orientation == .landscapeRight {
return CGAffineTransform(rotationAngle: -(.pi/2.0))
}
return .identity
}
}
//MARK -- public method
extension DDVideoPlayerView {
public func setddPlayer(ddPlayer: DDVideoPlayer) {
self.ddPlayer = ddPlayer
}
public func reloadPlayerLayer() {
playerLayer = AVPlayerLayer(player: self.ddPlayer?.player)
guard let pLayer = playerLayer else {
return
}
layer.insertSublayer(pLayer, at: 0)
timeSlider.isUserInteractionEnabled = ddPlayer?.mediaFormat != .m3u8
pLayer.frame = bounds
reloadGravity()
}
/// play state did change
public func playStateDidChange(_ state: DDPlayerState) {
playButtion.isSelected = state == .playing
centerPlayButtion.isHidden = true
replayButton.isHidden = !(state == .playFinished)
replayButton.isHidden = !(state == .playFinished)
if state == .playing || state == .playFinished {
setupTimer()
}
if state == .playFinished {
loadingIndicator.isHidden = true
}
}
/// buffer state change
public func bufferStateDidChange(_ state: DDPlayerBufferstate) {
centerPlayButtion.isHidden = true
if state == .buffering {
loadingIndicator.isHidden = false
loadingIndicator.startAnimating()
} else {
loadingIndicator.isHidden = true
loadingIndicator.stopAnimating()
//如果视频一直没播放,就显示
if ddPlayer?.isPlay() == false {
centerPlayButtion.isHidden = false
}
}
var current = formatSecondsToString((ddPlayer?.currentDuration)!)
if (ddPlayer?.totalDuration.isNaN)! { // HLS
current = "00:00"
}
if state == .readyToPlay && !isTimeSliding {
timeLabel.text = formatSecondsToString(ddPlayer?.totalDuration ?? 0)
currentLab.text = current
}
}
/// buffer duration
public func bufferedDidChange(_ bufferedDuration: TimeInterval, totalDuration: TimeInterval) {
timeSlider.setProgress(Float(bufferedDuration / totalDuration), animated: true)
}
/// player duration
public func playerDurationDidChange(_ currentDuration: TimeInterval, totalDuration: TimeInterval) {
var current = formatSecondsToString(currentDuration)
if totalDuration.isNaN { // HLS
current = "00:00"
}
if !isTimeSliding {
timeLabel.text = formatSecondsToString(totalDuration)
currentLab.text = current
let value = Float(currentDuration / totalDuration)
timeSlider.value = value
}
}
public func configurationUI() {
backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
//添加屏幕亮度视图
addSubview(brightnessView)
configurationTopView()
configurationBottomView()
configurationReplayButton()
configurationFailedButton()
configurationNotWifiTipView()
configurationCenterplayButton()
}
public func reloadPlayerView() {
playerLayer = AVPlayerLayer(player: nil)
timeSlider.value = Float(0)
timeSlider.setProgress(0, animated: false)
replayButton.isHidden = true
failedButton.isHidden = true
isTimeSliding = false
loadingIndicator.isHidden = false
loadingIndicator.startAnimating()
timeLabel.text = "00:00"
currentLab.text = "00:00"
reloadPlayerLayer()
}
/// control view display
public func displayControlView(_ isDisplay:Bool) {
if isDisplay {
displayControlAnimation()
} else {
hiddenControlAnimation()
}
}
/// play failed
public func playFailed(_ error: DDVideoPlayerError) {
// error
failedButton.isHidden = false
}
}
// MARK: - privite method
private extension DDVideoPlayerView {
func setParentViewAndFrame() {
//状态栏方向为竖直时,记录父视图及frame
let statusBarOrientation = UIApplication.shared.statusBarOrientation
if statusBarOrientation == .portrait {
//记录父视图及frame
parentView = superview
viewFrame = frame
}
}
func reloadGravity() {
if ddPlayer != nil {
switch ddPlayer!.gravityMode {
case .resize:
playerLayer?.videoGravity = .resize
case .resizeAspect:
playerLayer?.videoGravity = .resizeAspect
case .resizeAspectFill:
playerLayer?.videoGravity = .resizeAspectFill
}
}
}
func enterFullscreen() {
//状态栏方向为竖直时,记录父视图及frame
setParentViewAndFrame()
onDeviceOrientation(true, orientation: .landscapeLeft)
}
func formatSecondsToString(_ seconds: TimeInterval) -> String {
if seconds.isNaN{
return "00:00"
}
let interval = Int(seconds)
let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
let min = interval / 60
return String(format: "%02d:%02d", min, sec)
}
}
// MARK: - public method
extension DDVideoPlayerView {
public func play() {
playButtion.isSelected = true
centerPlayButtion.isHidden = true
}
public func pause() {
playButtion.isSelected = false
centerPlayButtion.isHidden = false
}
public func displayControlAnimation() {
if ddPlayer?.isHiddenCellPlayBottomBar == false && isFullScreen == false {
bottomView.isHidden = false
bottomView.alpha = 1
return
}
if isFullScreen == false {
topView.isHidden = true
} else {
topView.isHidden = false
}
bottomView.isHidden = false
isDisplayControl = true
UIView.animate(withDuration: 0.5, animations: {
self.bottomView.alpha = 1
self.topView.alpha = 1
}) { (completion) in
self.setupTimer()
}
}
public func hiddenControlAnimation() {
if ddPlayer?.isHiddenCellPlayBottomBar == false && isFullScreen == false {
bottomView.isHidden = false
bottomView.alpha = 1
return
}
timer.invalidate()
isDisplayControl = false
UIView.animate(withDuration: 0.5, animations: {
self.bottomView.alpha = 0
self.topView.alpha = 0
}) { (completion) in
self.bottomView.isHidden = true
self.topView.isHidden = true
}
}
public func setupTimer() {
timer.invalidate()
if ddPlayer?.isHiddenCellPlayBottomBar == false && isFullScreen == false {
bottomView.isHidden = false
bottomView.alpha = 1
return
}
timer = Timer.ddPlayer_scheduledTimerWithTimeInterval(self.controlViewDuration, block: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.displayControlView(false)
}, repeats: false)
}
public func configurationVolumeSlider() {
let volumeView = MPVolumeView()
if let view = volumeView.subviews.first as? UISlider {
volumeSlider = view
}
}
public func showNoWifiTipView() {
loadingIndicator.isHidden = true
wifiTipsView.isHidden = false
}
}
// MARK: - GestureRecognizer
private extension DDVideoPlayerView {
func addGestureRecognizer() {
singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onSingleTapGesture(_:)))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.numberOfTouchesRequired = 1
singleTapGesture.delegate = self
addGestureRecognizer(singleTapGesture)
doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onDoubleTapGesture(_:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.numberOfTouchesRequired = 1
doubleTapGesture.delegate = self
addGestureRecognizer(doubleTapGesture)
singleTapGesture.require(toFail: doubleTapGesture)
}
func addPanGesture() {
removaPanGesture()
panGesture = UIPanGestureRecognizer(target: self, action: #selector(onPanGesture(_:)))
panGesture?.delegate = self
if let pan = panGesture {
addGestureRecognizer(pan)
}
}
func removaPanGesture() {
if let pan = panGesture {
removeGestureRecognizer(pan)
}
}
}
// MARK: - UIGestureRecognizerDelegate
extension DDVideoPlayerView: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if (touch.view as? DDVideoPlayerView != nil) {
return true
}
return false
}
}
// MARK: - Event
extension DDVideoPlayerView {
func timeSliderTouchMoved() {
isTimeSliding = true
timer.invalidate()
if let duration = ddPlayer?.totalDuration {
let currentTime = Double(timeSlider.value) * duration
ddPlayer?.seekTime(currentTime, completion: { [weak self] (finished) in
guard let strongSelf = self else { return }
if finished {
strongSelf.isTimeSliding = false
strongSelf.setupTimer()
}
})
timeLabel.text = (formatSecondsToString(duration))
currentLab.text = formatSecondsToString(currentTime)
}
}
@objc internal func timeSliderValueChanged(_ sender: DDVideoPlayerSlider) {
isTimeSliding = true
if let duration = ddPlayer?.totalDuration {
let currentTime = Double(sender.value) * duration
timeLabel.text = formatSecondsToString(duration)
currentLab.text = formatSecondsToString(currentTime)
}
}
@objc internal func onPlayerButton(_ sender: UIButton) {
if !sender.isSelected {
ddPlayer?.play()
} else {
ddPlayer?.pause()
}
}
@objc internal func onFullscreen(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
isFullScreen = sender.isSelected
if isFullScreen {
enterFullscreen()
} else {
exitFullscreen()
}
}
/// Single Tap Event
@objc open func onSingleTapGesture(_ gesture: UITapGestureRecognizer) {
isDisplayControl = !isDisplayControl
displayControlView(isDisplayControl)
}
/// Double Tap Event
@objc open func onDoubleTapGesture(_ gesture: UITapGestureRecognizer) {
guard ddPlayer == nil else {
switch ddPlayer!.state {
case .playFinished:
break
case .playing:
ddPlayer?.pause()
case .paused:
ddPlayer?.play()
case .none:
break
case .error:
break
}
return
}
}
/// Pan Event
@objc open func onPanGesture(_ gesture: UIPanGestureRecognizer) {
let translation = gesture.translation(in: self)
let location = gesture.location(in: self)
let velocity = gesture.velocity(in: self)
switch gesture.state {
case .began:
let x = abs(translation.x)
let y = abs(translation.y)
if x < y {
panGestureDirection = .vertical
if location.x > bounds.width / 2 {
isVolume = true
} else {
isVolume = false
}
} else if x > y{
guard ddPlayer?.mediaFormat == .m3u8 else {
panGestureDirection = .horizontal
return
}
}
case .changed:
switch panGestureDirection {
case .horizontal:
if ddPlayer?.currentDuration == 0 { break }
sliderSeekTimeValue = panGestureHorizontal(velocity.x)
case .vertical:
panGestureVertical(velocity.y)
}
case .ended:
switch panGestureDirection{
case .horizontal:
if sliderSeekTimeValue.isNaN { return }
self.ddPlayer?.seekTime(sliderSeekTimeValue, completion: { [weak self] (finished) in
guard let strongSelf = self else { return }
if finished {
strongSelf.isTimeSliding = false
strongSelf.setupTimer()
}
})
case .vertical:
isVolume = false
}
default:
break
}
}
func panGestureHorizontal(_ velocityX: CGFloat) -> TimeInterval {
displayControlView(true)
isTimeSliding = true
timer.invalidate()
let value = timeSlider.value
if let _ = ddPlayer?.currentDuration ,let totalDuration = ddPlayer?.totalDuration {
let sliderValue = (TimeInterval(value) * totalDuration) + TimeInterval(velocityX) / 100.0 * (TimeInterval(totalDuration) / 400)
timeSlider.setValue(Float(sliderValue/totalDuration), animated: true)
return sliderValue
} else {
return TimeInterval.nan
}
}
func panGestureVertical(_ velocityY: CGFloat) {
if isFullScreen == false {
return
}
isVolume ? (volumeSlider.value -= Float(velocityY / 10000)) : (UIScreen.main.brightness -= velocityY / 10000)
}
@objc internal func onCloseView(_ sender: UIButton) {
exitFullscreen()
delegate?.ddPlayerView(didTappedClose: self)
}
@objc internal func onReplay(_ sender: UIButton) {
ddPlayer?.replaceVideo((ddPlayer?.contentURL)!)
ddPlayer?.play()
}
@objc internal func onFailed(_ sender: UIButton) {
ddPlayer?.replaceVideo((ddPlayer?.contentURL)!)
ddPlayer?.play()
}
}
//MARK: - UI autoLayout
private extension DDVideoPlayerView {
func configurationCenterplayButton() {
addSubview(centerPlayButtion)
if let path = Bundle(for: DDVideoPlayerView.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let playImage = UIImage(named: "video_btn_play_two", in: bundle, compatibleWith: nil) {
centerPlayButtion.setImage(playImage, for: .normal)
}
centerPlayButtion.addTarget(self, action: #selector(onPlayerButton(_:)), for: .touchUpInside)
centerPlayButtion.isHidden = true
}
func configurationNotWifiTipView () {
addSubview(wifiTipsView)
wifiTipsView.continuePlayBtnCallBack = { [weak self] in
self?.isAllowNotWifiPlay = true
self?.ddPlayer?.replaceVideo(self?.ddPlayer?.contentURL)
self?.ddPlayer?.play()
}
wifiTipsView.isHidden = true
}
func configurationFailedButton() {
addSubview(failedButton)
failedButton.addTarget(self, action: #selector(onFailed(_:)), for: .touchUpInside)
}
func configurationReplayButton() {
addSubview(self.replayButton)
if let path = Bundle(for: DDVideoPlayerView.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let replayImage = UIImage(named: "ic_replay", in: bundle, compatibleWith: nil) {
replayButton.setImage(DDVideoPlayerUtils.imageSize(image: replayImage, scaledToSize: CGSize(width: 30, height: 30)), for: .normal)
}
replayButton.addTarget(self, action: #selector(onReplay(_:)), for: .touchUpInside)
replayButton.isHidden = true
}
func configurationTopView() {
addSubview(topView)
topView.isHidden = true
titleLabel.text = "this is a title."
topView.addSubview(titleLabel)
if let path = Bundle(for: DDVideoPlayerView.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let closeImage = UIImage(named: "VGPlayer_ic_nav_back", in: bundle, compatibleWith: nil) {
closeButton.setImage(DDVideoPlayerUtils.imageSize(image: closeImage, scaledToSize: CGSize(width: 15, height: 20)), for: .normal)
}
closeButton.addTarget(self, action: #selector(onCloseView(_:)), for: .touchUpInside)
topView.addSubview(closeButton)
}
func configurationBottomView() {
addSubview(bottomView)
timeSlider.addTarget(self, action: #selector(timeSliderValueChanged(_:)),
for: .valueChanged)
// timeSlider.addTarget(self, action: #selector(timeSliderTouchUpInside(_:)), for: .touchUpInside)
// timeSlider.addTarget(self, action: #selector(timeSliderTouchDown(_:)), for: .touchDown)
timeSlider.touchChangedCallBack = {[weak self] value in
self?.timeSliderTouchMoved()
}
// loadingIndicator.lineWidth = 1.0
loadingIndicator.isHidden = false
loadingIndicator.startAnimating()
addSubview(loadingIndicator)
bottomView.addSubview(timeSlider)
if let path = Bundle(for: DDVideoPlayerView.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let playImage = UIImage(named: "video_btn_play", in: bundle, compatibleWith: nil),
let pauseImage = UIImage(named: "video_btn_stop", in: bundle, compatibleWith: nil){
playButtion.setImage(DDVideoPlayerUtils.imageSize(image: playImage, scaledToSize: CGSize(width: 15, height: 15)), for: .normal)
playButtion.setImage(DDVideoPlayerUtils.imageSize(image: pauseImage, scaledToSize: CGSize(width: 15, height: 15)), for: .selected)
}
playButtion.addTarget(self, action: #selector(onPlayerButton(_:)), for: .touchUpInside)
bottomView.addSubview(playButtion)
bottomView.addSubview(timeLabel)
bottomView.addSubview(currentLab)
if let path = Bundle(for: DDVideoPlayerView.classForCoder()).path(forResource: "DDVideoPlayer", ofType: "bundle"),
let bundle = Bundle(path: path),
let enlargeImage = UIImage(named: "ic_fullscreen", in: bundle, compatibleWith: nil),
let narrowImage = UIImage(named: "ic_fullscreen_exit", in: bundle, compatibleWith: nil){
fullscreenButton.setImage(DDVideoPlayerUtils.imageSize(image: enlargeImage, scaledToSize: CGSize(width: 15, height: 15)), for: .normal)
fullscreenButton.setImage(DDVideoPlayerUtils.imageSize(image: narrowImage, scaledToSize: CGSize(width: 15, height: 15)), for: .selected)
}
fullscreenButton.addTarget(self, action: #selector(onFullscreen(_:)), for: .touchUpInside)
bottomView.addSubview(fullscreenButton)
}
func setupSubViewsFrame() {
let sWidth = bounds.width
let sHeight = bounds.height
//适用横屏v布局
var leftMargin: CGFloat = 0
if isFullScreen && DDVPIsiPhoneX.isIphonex() == true {
leftMargin = 30
}
let viewCenter = CGPoint(x: sWidth / 2, y: sHeight / 2)
//wifiTipsView
wifiTipsView.frame = CGRect(x: 0, y: 0, width: 200, height: 80)
wifiTipsView.center = viewCenter
//failedButton
failedButton.frame = CGRect(x: 0, y: 0, width: 150, height: 30)
failedButton.center = viewCenter
//replayButton
replayButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
replayButton.center = viewCenter
// top view layout
let topViewCenterY: CGFloat = (44 - 25) / 2
topView.frame = CGRect(x: 0 , y: 0, width: sWidth, height: 44)
closeButton.frame = CGRect(x: 10 + leftMargin, y: topViewCenterY, width: 30, height: 30)
titleLabel.frame = CGRect(x: 10 + leftMargin + 30 + 20, y: topViewCenterY, width: sWidth - 10 - 30 - 20 - 12 - leftMargin * 2, height: 30)
// bottom view layout
let bottmHeight: CGFloat = 44
let bottomCenterY: CGFloat = (bottmHeight - 25) / 2
bottomView.frame = CGRect(x: 0, y: sHeight - bottmHeight, width: sWidth, height: bottmHeight)
playButtion.frame = CGRect(x: 10 + leftMargin, y: bottomCenterY + 2, width: 25, height: 25)
currentLab.frame = CGRect(x: 10 + leftMargin + 10 + 25, y: bottomCenterY, width: 50, height: 30)
fullscreenButton.frame = CGRect(x: sWidth - leftMargin - 10 - 30 - 10, y: bottomCenterY, width: 30, height: 30)
timeLabel.frame = CGRect(x: sWidth - leftMargin - 10 - 30 - 10 - 50, y: bottomCenterY, width: 50, height: 30)
let w = sWidth - leftMargin - 10 - 30 - 10 - 50 - 10 - 10 - leftMargin - 10 - 25 - 10 - 50
timeSlider.frame = CGRect(x: 10 + leftMargin + 10 + 25 + 50 + 10, y: bottomCenterY + 2, width: w, height: 25)
//loadingIndicator
loadingIndicator.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
loadingIndicator.center = viewCenter
centerPlayButtion.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
centerPlayButtion.center = viewCenter
}
}
extension DDVideoPlayerView {
func getAppTopViewController() -> (UIViewController?) {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
if rootViewController?.isKind(of: UITabBarController.self) == true {
let tabBarController: UITabBarController = rootViewController as! UITabBarController
return tabBarController.selectedViewController
} else if rootViewController?.isKind(of: UINavigationController.self) == true {
let navigationController: UINavigationController = rootViewController as! UINavigationController
return navigationController.visibleViewController
} else if let presentVC = rootViewController?.presentedViewController {
return presentVC
}
return rootViewController
}
}
<file_sep>#
# Be sure to run `pod lib lint DDKit.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'DDKit'
s.version = '1.0.3'
s.summary = 'private extensions for uikit in swift.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
hk01 private uikit frameworks in swift.
DESC
s.homepage = 'https://github.com/hk01-digital'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => './LICENSE' }
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<NAME>' => '<EMAIL>' }
s.source = { :git => 'https://github.com/hk01-digital/dd01-ios-ui-kit.git', :tag => s.version.to_s, :submodules => true }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
s.swift_version = '4.2'
s.default_subspec = 'Core'
s.subspec 'Core' do |ss|
ss.source_files = 'DDKit/Core/*'
# ss.resources = 'Core/**/Assets/*.png'
#ss.dependency 'DDKit/Chainable'
end
s.subspec 'Pop' do |ss|
ss.source_files = 'DDKit/Pop/Classes/*'
ss.resources = 'DDKit/Pop/Assets/*'
end
s.subspec 'Refresh' do |ss|
ss.source_files = 'DDKit/Refresh/*'
ss.dependency 'MJRefresh'
end
s.subspec 'Hud' do |ss|
ss.source_files = 'DDKit/Hud/*'
ss.dependency 'MBProgressHUD'
ss.dependency 'PKHUD'
ss.dependency 'SnapKit'
end
s.subspec 'Request' do |ss|
ss.source_files = 'DDKit/Request/*'
ss.dependency 'Alamofire'
ss.dependency 'PromiseKit'
ss.dependency 'Cache'
end
s.subspec 'Codable' do |ss|
ss.source_files = 'DDKit/Codable/*'
end
s.subspec 'WebJS' do |ss|
ss.source_files = 'DDKit/WebJS/*'
end
s.subspec 'VideoPlayer' do |ss|
ss.source_files = 'DDKit/VideoPlayer/Class/*'
ss.resources = 'DDKit/VideoPlayer/Asset/*'
ss.dependency 'SnapKit'
ss.dependency 'Alamofire'
end
s.subspec 'PhotoBrowser' do |ss|
ss.source_files = 'DDKit/PhotoBrowser/Classes/*'
ss.resources = 'DDKit/PhotoBrowser/Assets/*'
ss.dependency 'Kingfisher'
end
s.subspec 'CustomCamera' do |ss|
ss.source_files = 'DDKit/CustomCamera/Classes/*'
ss.resources = 'DDKit/CustomCamera/Assets/*'
ss.dependency 'SnapKit'
ss.dependency 'DDKit/Hud'
end
s.subspec 'Scan' do |ss|
ss.source_files = 'DDKit/Scan/Classes/*'
ss.resources = 'DDKit/Scan/Assets/*'
ss.dependency 'SnapKit'
end
s.subspec 'Mediator' do |ss|
ss.source_files = 'DDKit/Mediator/*'
end
s.subspec 'Router' do |ss|
ss.source_files = 'DDKit/Router/*'
end
s.subspec 'MagicTextField' do |ss|
ss.source_files = 'DDKit/MagicTextField/*'
end
s.subspec 'EmptyDataView' do |ss|
ss.source_files = 'DDKit/EmptyDataView/Classes/*'
ss.dependency 'SnapKit'
end
s.subspec 'DevelopConfig' do |ss|
ss.source_files = 'DDKit/DevelopConfig/*'
ss.dependency 'SnapKit'
ss.dependency 'AFNetworking/Reachability'
end
s.subspec 'PageTabsController' do |ss|
ss.source_files = 'DDKit/PageTabsController/*'
end
s.subspec 'Picker' do |ss|
ss.source_files = 'DDKit/Picker/*'
ss.dependency 'ActionSheetPicker-3.0'
end
s.subspec 'CityList' do |ss|
ss.source_files = 'DDKit/CityList/Classes/*'
ss.resources = 'DDKit/CityList/Asset/*'
end
s.subspec 'NumberSelect' do |ss|
ss.source_files = 'DDKit/NumberSelect/Classes/*'
ss.resources = 'DDKit/NumberSelect/Asset/*'
end
s.subspec 'Chainable' do |ss|
ss.source_files = 'DDKit/Chainable/*'
#ss.resources = 'DDKit/NumberSelect/Asset/*'
ss.dependency 'RxSwift'
ss.dependency 'RxCocoa'
ss.dependency 'SnapKit'
end
s.subspec 'Debug' do |ss|
ss.source_files = 'DDKit/Debug/*'
end
# s.resource_bundles = {
# 'DDKit' => ['DDKit/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
<file_sep>Welcome to the Swift-UI-Kit
[Chainable 扩展UIView及其子类,支持链式语法调用](https://github.com/MrAntu/Swift-UI-Kit/wiki/Chainable---%E6%89%A9%E5%B1%95UIView%E5%8F%8A%E5%85%B6%E5%AD%90%E7%B1%BB%EF%BC%8C%E6%94%AF%E6%8C%81%E9%93%BE%E5%BC%8F%E8%AF%AD%E6%B3%95%E8%B0%83%E7%94%A8)
[CityList 使用指南](https://github.com/MrAntu/Swift-UI-Kit/wiki/CityList-%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[DDCustomCamera 使用指南](https://github.com/MrAntu/Swift-UI-Kit/wiki/DDCustomCamera-%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[DDMediator 模块(业务)间通信中间者](https://github.com/MrAntu/Swift-UI-Kit/wiki/DDMediator---%E6%A8%A1%E5%9D%97(%E4%B8%9A%E5%8A%A1)%E9%97%B4%E9%80%9A%E4%BF%A1%E4%B8%AD%E9%97%B4%E8%80%85)
[DDPhotoBrowser 使用指南](https://github.com/MrAntu/Swift-UI-Kit/wiki/DDPhotoBrowser-%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[DDPhotoPicker( 图片选择器)使用指南](https://github.com/MrAntu/Swift-UI-Kit/wiki/DDPhotoPicker%EF%BC%88-%E5%9B%BE%E7%89%87%E9%80%89%E6%8B%A9%E5%99%A8%EF%BC%89%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[DDScan 使用指南](https://github.com/MrAntu/Swift-UI-Kit/wiki/DDScan-%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[DDVideoPlayer使用指南](https://github.com/MrAntu/Swift-UI-Kit/wiki/DDVideoPlayer%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[EmptyDataView网络请求返回后空白页占位图 使用指南](https://github.com/MrAntu/Swift-UI-Kit/wiki/EmptyDataView%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E8%BF%94%E5%9B%9E%E5%90%8E%E7%A9%BA%E7%99%BD%E9%A1%B5%E5%8D%A0%E4%BD%8D%E5%9B%BE--%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[MagicTextField(聚焦时placeholder动画上移) 使用说明](https://github.com/MrAntu/Swift-UI-Kit/wiki/MagicTextField(%E8%81%9A%E7%84%A6%E6%97%B6placeholder%E5%8A%A8%E7%94%BB%E4%B8%8A%E7%A7%BB)---%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E)
[PageTabsController 使用说明](https://github.com/MrAntu/Swift-UI-Kit/wiki/PageTabsController%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
[Toast & Hud 使用说明](https://github.com/MrAntu/Swift-UI-Kit/wiki/Toast-&&-Hud%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
<file_sep>//
// HudVC.swift
// Example
//
// Created by leo on 2018/7/18.
// Copyright © 2018年 dd01. All rights reserved.
//
import MBProgressHUD
import UIKit
class HudVC: UITableViewController {
var items = ["hud-show",
"hud-title-show",
"hud-title-mode",
"hud-annularDeterminate",
"hud-circle-determinate",
"hud-determinateHorizontalBar",
"hud-bgcolor",
"hud-clear",
"hud- window"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//隐藏hud
NSObject.dispathTimer(timeInterval: 5) {[weak self] (timer) in
self?.view.hiddenHud()
UIApplication.shared.keyWindow?.hiddenHud()
}
}
public func load(add: Bool) {
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
view.showHud(backgroundColor: UIColor.red)
} else if indexPath.row == 1 {
view.showHud(title: "加载中...")
} else if indexPath.row == 2 {
view.showHud(title: "加载中...", mode: .indeterminate)
} else if indexPath.row == 3 {
let hud = view.showHud(mode:.annularDeterminate)
var progress: Float = 0
NSObject.dispathTimer {[weak self] (timer) in
progress += 0.2
hud?.progress = progress
if progress == 1.0 {
timer?.cancel()
self?.view.hiddenHud()
}
}
} else if indexPath.row == 4 {
let hud = view.showHud(mode: .determinate)
var progress: Float = 0
NSObject.dispathTimer {[weak self] (timer) in
progress += 0.2
hud?.progress = progress
if progress == 1.0 {
timer?.cancel()
self?.view.hiddenHud()
}
}
} else if indexPath.row == 5 {
let hud = view.showHud(mode:.determinateHorizontalBar)
var progress: Float = 0
NSObject.dispathTimer {[weak self] (timer) in
progress += 0.2
hud?.progress = progress
if progress == 1.0 {
timer?.cancel()
self?.view.hiddenHud()
}
}
} else if indexPath.row == 6 {
view.showHud(backgroundColor: UIColor.red)
} else if indexPath.row == 7 {
view.showHud(backgroundColor: .clear, style: .solidColor)
} else if indexPath.row == 8 {
//不允许用户做任何操作,可使用此方法
UIApplication.shared.keyWindow?.showHud(title: "加载中...")
}
}
}
<file_sep>//
// UILabel+Chainable.swift
// CoreDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UILabel
public extension UIKitChainable where Self: UILabel {
/// 设置文字水平方向对齐方式 `textAlignment`
///
/// - Parameter alignment: 对齐方式
/// - Returns: 返回 self,支持链式调用
@discardableResult
func textAlignment(_ alignment: NSTextAlignment) -> Self {
textAlignment = alignment
return self
}
/// 设置最多显示行数 `numberOfLines`
///
/// - Parameter lines: 最多显示行数,0 为任意行数
/// - Returns: 返回 self,支持链式调用
@discardableResult
func numberOfLines(_ lines: Int) -> Self {
numberOfLines = lines
return self
}
/// 设置字体大小
///
/// - Parameter font: `UIFontType`
/// - Returns: self
@discardableResult
func font(_ font: UIFontType) -> Self {
self.font = font.font
return self
}
/// 设置文字
///
/// - Parameter text: `text`
/// - Returns: self
@discardableResult
func text(_ text: String?) -> Self {
self.text = text
return self
}
/// 设置字体颜色
///
/// - Parameter color: color
/// - Returns: self
@discardableResult
func textColor(_ color: UIColor) -> Self {
textColor = color
return self
}
/// 设置shadowColor
///
/// - Parameter color: color
/// - Returns: self
@discardableResult
func shadowColor(_ color: UIColor?) -> Self {
shadowColor = color
return self
}
/// 设置阴影偏移量
///
/// - Parameter offset: offset
/// - Returns: self
@discardableResult
func shadowOffset(_ offset: CGSize) -> Self {
shadowOffset = offset
return self
}
/// 设置lineBreakMode
///
/// - Parameter mode: mode
/// - Returns: self
@discardableResult
func lineBreakMode(_ mode: NSLineBreakMode) -> Self {
lineBreakMode = mode
return self
}
/// 设置富文本
///
/// - Parameter attributedtext: attributedtext
/// - Returns: self
@discardableResult
func attributedText(_ attributedtext: NSAttributedString?) -> Self {
attributedText = attributedtext
return self
}
/// 设置高亮字体颜色
///
/// - Parameter color: color
/// - Returns: self
@discardableResult
func highlightedTextColor(_ color: UIColor?) -> Self {
highlightedTextColor = color
return self
}
/// 是否高亮
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func isHighlighted(_ lighted: Bool) -> Self {
isHighlighted = lighted
return self
}
/// 是否允许交互
///
/// - Parameter enabled: enabled
/// - Returns: self
@discardableResult
func isUserInteractionEnabled(_ enabled: Bool) -> Self {
isUserInteractionEnabled = enabled
return self
}
/// 是否可用
///
/// - Parameter enabled: enabled
/// - Returns: self
@discardableResult
func isEnabled(_ enabled: Bool) -> Self {
isEnabled = enabled
return self
}
/// 是否自动调整字体大小
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func adjustsFontSizeToFitWidth(_ bool: Bool) -> Self {
adjustsFontSizeToFitWidth = bool
return self
}
/// minimumScaleFactor
///
/// - Parameter factor: factor
/// - Returns: self
@discardableResult
func minimumScaleFactor(_ factor: CGFloat) -> Self {
minimumScaleFactor = factor
return self
}
/// allowsDefaultTighteningForTruncation
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func allowsDefaultTighteningForTruncation(_ bool: Bool) -> Self {
allowsDefaultTighteningForTruncation = bool
return self
}
/// preferredMaxLayoutWidth
///
/// - Parameter width: width
/// - Returns: self
@discardableResult
func preferredMaxLayoutWidth(_ width: CGFloat) -> Self {
preferredMaxLayoutWidth = width
return self
}
/// clipsToBounds
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func clipsToBounds(_ bool: Bool) -> Self {
clipsToBounds = bool
return self
}
/// isOpaque
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func isOpaque(_ bool: Bool) -> Self {
isOpaque = bool
return self
}
/// clearsContextBeforeDrawing
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func clearsContextBeforeDrawing(_ bool: Bool) -> Self {
clearsContextBeforeDrawing = bool
return self
}
/// isHidden
///
/// - Parameter bool: bool
/// - Returns: self
@discardableResult
func isHidden(_ bool: Bool) -> Self {
isHidden = bool
return self
}
/// mask
///
/// - Parameter view: view
/// - Returns: self
@discardableResult
func mask(_ view: UIView?) -> Self {
mask = view
return self
}
/// tintColor
///
/// - Parameter color: color
/// - Returns: self
@discardableResult
func tintColor(_ color: UIColor) -> Self {
tintColor = color
return self
}
/// tintAdjustmentMode
///
/// - Parameter mode: mode
/// - Returns: self
@discardableResult
func tintAdjustmentMode(_ mode: UIView.TintAdjustmentMode) -> Self {
tintAdjustmentMode = mode
return self
}
}
<file_sep># Uncomment the next line to define a global platform for your project
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/aliyun/aliyun-specs.git'
source 'https://github.com/hk01-digital/hk01-ios-uikit-spec.git'
platform :ios, '9.0'
target 'DDRouterDemo' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
pod 'DDKit/DDScan'
end
<file_sep>//
// TextViewVC.swift
// ChainableDemo
//
// Created by weiwei.li on 2019/1/10.
// Copyright © 2019 dd01.leo. All rights reserved.
//
import UIKit
class TextViewVC: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//
// TODO: 注意
// 若同时初始化 text 和 placeholder,一定要注意先后顺序,placeholder在前,text在后。否则会有点小bug,是系统的问题
//支持最大字数限制
//支持设置placeholder
textView.textColor(UIColor.red)
.backgroundColor(UIColor.gray)
.addShouldBegindEditingBlock { (t) -> (Bool) in
print("addShouldBegindEditingBlock")
return true
}
.addDidChangeBlock { (t) in
print("addDidChangeBlock")
}
.addShouldChangeTextInRangeReplacementTextBlock { (t, range, text) -> (Bool) in
print(text)
return true
}
.maxLength(5)
.placeholder("我是是否带回家sdfsdf")
// .text("qwqweqew")
// 不提供设置代理方法。若需要直接调用系统设置代理。链式回调就不在返回
}
deinit {
print(self)
}
}
<file_sep>//
// PageTabsBaseTableView.swift
// PageTabsControllerDemo
//
// Created by USER on 2018/12/18.
// Copyright © 2018 dd01.leo. All rights reserved.
//
import UIKit
import WebKit
public class PageTabsBaseTableView: UITableView {
public var allowGestureEventPassViews: [UIView]?
override public init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
comonInit()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTabsBaseTableView {
private func comonInit() {
// 在某些情况下,contentView中的点击事件会被panGestureRecognizer拦截,导致不能响应,
// 这里设置cancelsTouchesInView表示不拦截
panGestureRecognizer.cancelsTouchesInView = false
}
}
extension PageTabsBaseTableView: UIGestureRecognizerDelegate {
// 返回true表示可以继续传递触摸事件,这样两个嵌套的scrollView才能同时滚动
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| d0de9136b16fc6d8a726323b4b970aed756ae948 | [
"Swift",
"Ruby",
"Markdown",
"Shell"
] | 220 | Swift | MrAntu/Swift-UI-Kit | 3558870799d76ff5cbbd7f80342b6a743db1d6b8 | 0dac42cac4f50d887f584a54ec1aeaf856a116a8 |
refs/heads/master | <file_sep>package codekata.models;
public class AddressType {
int code;
String name ="";
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "AddressType [code=" + code + ", name=" + name + "]";
}
}
<file_sep>package stringkata;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
public class CalculatorTest {
@Test
public void shouldReturnZeroOnEmptyString() {
assertEquals(0, Calculator.Add(""));
}
@Test
public void shouldReturnSingleNumber() {
assertEquals(1, Calculator.Add("1"));
}
@Test
public void shouldReturnSumOfTwoNumbersCommaDelimited() {
assertEquals(3, Calculator.Add("1,2"));
}
@Test
public void shouldReturnSumOfMultipleCommaDelimited() {
assertEquals(6, Calculator.Add("1,2,3"));
}
@Test
public void shouldAcceptNewLineAsSeparotor() {
assertEquals(10, Calculator.Add("1,2,3\n4"));
}
@Test
public void shouldAcceptCustomSepartors() {
assertEquals(3, Calculator.Add("//#\n1#2"));
}
@Test
public void shouldThrowErrorOnNegativeNumbers() {
try {
Calculator.Add("1,-2,-3");
fail("Error must be thrown");
}catch(RuntimeException ex) {
}
}
@Test
public void errorContainsNumber() {
try {
Calculator.Add("1,-2,-3");
fail("Error must be thrown");
}catch(RuntimeException ex) {
assertEquals("Negative Numbers Not Allowed: -2,-3", ex.getMessage());
}
}
}
| 4d0c2182329c5919f2ffe4e222806b591b90db2c | [
"Java"
] | 2 | Java | thapeloMotene/code-kata | 6f4a681be87bb76a3b53d1dd85c5a6026a6be59e | aff519a1962511e21aa303cd367ffee76812fbad |
refs/heads/master | <file_sep>#ifndef _PUBLIC_H
#define _PUBLIC_H
#include <opencv2/opencv.hpp>
/** 求两直线的的焦点 p0, p1代表第一条直线。 p2, p3代表第二条直线 返回交点*/
cv::Point2f getLineIntersection(cv::Point2f p0, cv::Point2f p1, cv::Point2f p2, cv::Point2f p3);
#endif // _PUBLIC_H
| 78054925b5e715be434e55e95c6e995138110d80 | [
"C"
] | 1 | C | 463243109/Eu_test | 601e5129572226d53e60e19602031a1319106cdc | c8fd11884c0acde73543aae09afa0f3713c5f526 |
refs/heads/master | <file_sep>//
// Created by <NAME> on 10/29/15.
//
#ifndef CLUSTERING_CLUSTERINGTESTS_H
#define CLUSTERING_CLUSTERINGTESTS_H
#include "ErrorContext.h"
using namespace Testing;
// - - - - - - - - - Tests: class Point - - - - - - - - - -
// Smoketest: constructor, copy constructor, destructor
void test_point_smoketest(ErrorContext &ec);
// id
void test_point_id(ErrorContext &ec, unsigned int numRuns);
// setValue, getValue, operator[]
void test_point_getsetelem(ErrorContext &ec, unsigned int numRuns);
// Copy constructor
void test_point_copying(ErrorContext &ec, unsigned int numRuns);
// operator=
void test_point_assignment(ErrorContext &ec, unsigned int numRuns);
// operator==, operator!=
void test_point_equality(ErrorContext &ec, unsigned int numRuns);
// operator<, operator<=, operator>, operator>=
// (pseudo-lexicographic comparison)
void test_point_comparison(ErrorContext &ec, unsigned int numRuns);
// operator+=, operator-=, operator*=, operator/=
void test_point_CAO(ErrorContext &ec, unsigned int numRuns);
// operator+, operator-, operator*, operator/
void test_point_SAO(ErrorContext &ec, unsigned int numRuns);
// distanceTo
void test_point_distance(ErrorContext &ec, unsigned int numRuns);
// operator>>, operator<< (incl. exceptions)
void test_point_IO(ErrorContext &ec, unsigned int numRuns);
// - - - - - - - - - Tests: class Cluster - - - - - - - - - -
// Smoketest: constructor, copy constructor, destructor
void test_cluster_smoketest(ErrorContext &ec);
// add, remove
void test_cluster_addremove(ErrorContext &ec, unsigned int numRuns);
// Containment
void test_cluster_contain(ErrorContext &ec, unsigned int numRuns);
// Copy constructor
void test_cluster_copying(ErrorContext &ec, unsigned int numRuns);
// operator=
void test_cluster_assignment(ErrorContext &ec, unsigned int numRuns);
// subscript (operator[])
void test_cluster_subscript(ErrorContext &ec, unsigned int numRuns);
// operator==, operator!=
void test_cluster_equality(ErrorContext &ec, unsigned int numRuns);
// ascending pseudo-lexicographic order
void test_cluster_order(ErrorContext &ec, unsigned int numRuns);
// operator+=, operator-=, different rhs
void test_cluster_CAO(ErrorContext &ec, unsigned int numRuns);
// operator+, operator-, different rhs
void test_cluster_SAO(ErrorContext &ec, unsigned int numRuns);
// operator>>, operator<<
void test_cluster_IO(ErrorContext &ec, unsigned int numRuns);
#endif //CLUSTERING_CLUSTERINGTESTS_H
<file_sep>## CSCI 2312: Programming Assignment 2
_operator overloading and linked data structures_
* * *
### Goals
1. Practice class design with the Point and Cluster classes, which feature dynamic memory management.
2. Learn to overload operators for your own classes/types.
3. Learn to work with linked lists, one of the most basic and ubiquitous data structures.
4. Practice input/output within the streams abstraction.
5. Continue using git and Github.
6. Develop good coding style.
### Synopsis
PA2 asks you to update your 3D Point class from [PA1](https://github.com/ivogeorg/ucd-csci2312-pa1) to an arbitrary number of "dimensions", and to create a Cluster class which will hold a big number of Point objects. The Point objects held in a Cluster have to be sorted in pseudo-lexicographic order at all times. You have to write two files, <tt>Point.cpp</tt> and <tt>Cluster.cpp</tt>. See the [Detailed Instructions](https://github.com/ivogeorg/ucd-csci2312-pa2/blob/master/README.md#detailed-instructions) at the bottom of this file.
PA2 is in the test-driven-development (TDD) style, just like [PA1](https://github.com/ivogeorg/ucd-csci2312-pa1). It has 204 tests that your implementation should pass for full points. Start by creating the two files <tt>Point.cpp</tt> and <tt>Cluster.cpp</tt> so CMake will stop complaining. (Remember to <tt>git add</tt> them to your local repository.) Then start implementing the Point class incrementally. You can comment out all but the first test (<tt>test_point_smoketest(ec);</tt>) in <tt>main.cpp</tt>. When you pass this test, uncomment the next one, and so on.
PA2 is a much larger assignment than PA1. You should expect to write about 500 lines of code and spend about 30 hours on it. Therefore, it is advisable that you start early and do it in stages. If you get stuck on anything for more than **one hour**, seek help.
### Submission
You don't need to submit anything. Once you fork the repository (this is your **remote** repository on Github, aka **origin**), you will clone it to your development machine (this is your local repository), and start work on it. Commit your changes to your local repository often and push them up to the remote repository occasionally. Make sure you push at least once before the due date. At the due date, your remote repository will be cloned and tested automatically by the grading script. _**Note:** Your code should be in the **master** branch of your remote repository._
### Grading
An autograding script will run the test suite against your files. Your grade will be based on the number of tests passed. (E.g. if your code passes 3 out of 6 test cases, your score will be 50% and the grade will be the corresponding letter grade in the course's grading scale). The test suite for PA2 has __204__ tests. **Note:** The testing and grading will be done with fresh original copies of all the provided files. In the course of development, you can modify them, if you need to, but your changes will not be used. Only your <tt>Point.cpp</tt> and <tt>Cluster.cpp</tt> files will be used.
### Compiler
Your program should run on **GCC 4.9.0** or later, or **Clang 3.3** or later. No other compilers are supported.
### Due Date
The assignment is due on **Wed, Mar 2, at 23:59 Mountain time**. The last commit to your PA2 repository before the deadline will be graded.
### Honor Code
Free Github repositories are public so you can look at each other's code. Please, don't do that. You can discuss any programming topics and the assignments in general but sharing of solutions diminishes the individual learning experience of many people. Assignments might be randomly checked for plagiarism and a plagiarism claim may be raised against you.
### Use of libraries
For this assignment, no external libraries should be used, except for the Standard Library minus the Standard Template Library (STL). The implementation of the linked list should be your own. We will use the STL in PA4-PA5.
### Coding style
Familiarize yourself with and start following [coding style guidelines](http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cppstyle.html). There are others on the Web. Pick one and be consistent. _**Note:** If you stumble on the Google C++ Style Guide, be advised that it has been heavily criticized by many leading C++ programmers. I don't advise you to follow it, especially the more advanced features. This Guide is for entry-level coders at Google who need to be able to work with their legacy code. It is not advisable for new projects and novice programmers._
### References
Operator overloading [guidelines](http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html).
A very good [C++ tutorial](http://www.learncpp.com/), including many topics we are covering.
Two websites with C++ Reference, [here](http://en.cppreference.com/w/) and [here](http://www.cplusplus.com/).
### Detailed Instructions
#### Point class
1. The `Point` class represents a point in multidimensional Euclidean space, represented by `double` values. The number of dimensions is an argument to the `Point` constructor. The values of the point should be held in a private _dynamically allocated_ array of `double`s. To handle dynamic memory properly, you have to implement the one-argument constructor, the copy constructor, the assignment operator, and the destructor (the last three are aka _the big three_).
2. The _optional_ second constructor, which takes a number of dimensions and an array of `double`s, is not tested by the test suite. It might be useful for your own testing & debugging needs.
3. Every `Point` should have a unique _id_. The easiest way to achieve this is to use a `static` variable that holds the value of the next _id_. (A `static` variable belongs to the class, not the objects, so there is only one such variable, no matter how many objects of the class are created.) The `Point` constructor should get the current value to assign to the current point, and increment the value for the next point.
**Note:** The `static` variable has to be defined and initialized in the <tt>Point.cpp</tt> file as follows:
```C++
unsigned int Point::__idGen = 0; // id generator
```
4. For the proper operation of the `Point` and `Cluster` classes, the `Point` _copy constructor_ and _assignment operator_ implementations should **copy** the _id_ of the argument, and not generate a new one like the constructor(s).
5. Modify the `distanceTo()` function to work for points of arbitrary number of dimensions. Remember that the dimensionality of the `Point` is held in a private variable.
6. Implement the overloaded member `operator*=` and `operator/=` with a single `double` argument. These operators are known as _compound assignment_.
**Usage:** Each dimension of the current `Point` is multiplied or divided by a factor as follows:
```C++
p1 *= 6.3;
p2 /= 2.5;
```
7. Implement the overloaded simple arithmetic member `operator*` and `operator/` with a single `double` argument.
**Usage:** A new `Point` is created and returned with dimensions like the current `Point` but multiplied or divided by a factor as follows:
```C++
p1 = p * 6.3;
p2 = p * 2.5;
```
**Note:** The implementation of these operators is straightforward if the corresponding _compound assignment_ operators are used.
8. Implement the overloaded non-`const` _subscript_ member `operator[]`.
**Usage:** Read/write access to each of a `Point`'s values:
```C++
p[4] = 7.001;
p[5] = p[1] * 1.5;
```
9. Implement the overloaded `friend` _compound assignment_ arithmetic `operator+=` and `operator-=` with two `const Point &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Dimension-wise addition/substraction of the right-hand `Point` from the left-hand `Point`:
```C++
p1 += p2;
p3 -= p1;
```
**Note:** Notice that the first (or left-hand) argument is not `const`. The operators modify that `Point` and return a reference to it.
10. Implement the overloaded `friend` simple arithmetic `operator+` and `operator-` with two `const Point &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Dimension-wise addition/substraction of the right-hand `Point` from the left-hand `Point` and the creation and returning of a new `const Point` with the dimension-wise sum/difference of their values:
```C++
p1 = p2 + p3;
p3 = p1 - p4;
```
**Note:** The implementation of these operators is straightforward if the corresponding _compound assignment_ operators are used.
**Note:** The return type is a `const` to prevent silly statements like the following:
```C++
(p1 + p3) = p5; // assigns p5 to the temporary new Point object returned by operator+
```
11. Implement the overloaded `friend` `operator==` and `operator!=` with two `const Point &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Test two `Point`s for equality or inequality:
```C++
if (p1 == p2) {
// ...
}
if (p3 != p4) {
// ...
}
```
**Note:** Two `Point`s are equal **iff** all values are equal dimension-wise, **and** the _id-s_ are also equal.
**Note:** The implementation of `operator!=` is straightforward with the use of `operator==`.
12. Implement the overloaded `friend` `operator<`, `operator>`, `operator<=`, and `operator>=` with two `const Point &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Compare two `Point`s:
```C++
if (p1 < p2) {
// ...
}
if (p3 >= p4) {
// ...
}
```
**Note:** One `Point` is _smaller_ than another **iff**, for a given dimension position, the value of the first point is **less** than the value of the second point, and all the values on the left, if any, are all equal. The values on the right don't matter. For example, `Point` (5.0, 5.0, 4.5, 10.1, **13.4**, 151.3) is _smaller_ than (5.0, 5.0, 4.5, 10.1, **13.5**, 15.9).
**Note:** Implement `operator<`, then use it to implement `operator>` and `operator>=`. Finally, use `operator>` to implement `operator<=`.
13. Implement the overloaded `friend` insertion `operator<<` with a `std::ostream` and a `const Point &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Right out (intert) a `Point` to an output stream:
```C++
cout << p2 << endl;
```
**Note:** A `Point` should write itself out as follows (note the _space_ after each comma):
```
1.2, 4.5, 6.7, 90.12, 34.54, 0.01
```
14. Implement the overloaded `friend` extraction `operator>>` with a `std::istream` and a non-`const` `Point &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Read in (extract) a `Point` from an input stream:
```C++
std::string pointString("1.2, 4.5, 6.7, 90.12, 34.54, 0.01");
std::stringstream inputStringStream(pointString);
Point p(6);
inputStringStream >> p;
```
**Note:** Notice that the `Point` created to be read has exactly the dimensionality that is necessary to hold the values read out from the input stream.
#### Cluster class
1. The `Cluster` class represents a collection of `Point` objects. It uses a singly-linked list to hold them in **ascending pseudo-lexicographic order**. The list is composed of linked `LNode` objects defined as simple structures, each one pointing to the next one, if any, and the last one holding a `nullptr`, signifying the end of the list:
```C++
typedef struct LNode *LNodePtr;
struct LNode {
Point point;
LNodePtr next;
LNode(const Point &p, LNodePtr n);
};
```
2. A `Cluster` can have `Point`s added and removed. During these operations, two conditions have to be maintained:
1. The `Point`s should **always** be in the correct _ascending pseudo-lexicographic_ order.
2. The `size` parameter of the `Cluster` should **always** be in sync with the true number of `Points`.
3. It is helpful to employ the following two techniques in the implementation of the linked-list manipulation methods:
1. Handle separately and in this order the cases of
* Empty list
* The first element of the list
* All the rest of the elements
2. When traversing the list keep track of two variables
* A pointer to the current element (e.g. `curr`)
* A poitner to the previous element (e.g. `prev`)
4. A linked list is dynamically allocated data structure, so you need to implement _the big three_ (_cpy ctor_, _oper=_, and _dtor_) to manage it correctly. In PA2, `Cluster` has a default constructor, which initializes an _empty_ list.
5. The _optional_ private helper methods
```C++
void __del();
void __cpy(LNodePtr pts);
bool __in(const Point &p) const;
```
can be used to reuse code. `__del` is used in the destructor and overloaded assignment operator `operator=`, `__cpy` is used in the copy constructor and `operator=`, while `__in` can be helpful for testing, debugging, and even some method implementations.
6. Implement the members `add` and `remove` to add `Point`s to and remove `Point`s from a `Cluster`. Notice the `const Point &` arguments and return value for `remove`. The latter allows for a `Point` to be moved from one `Cluster` to another in one line of code, as follows:
```C++
c5.add(c3.remove(p23));
```
**Note:** `add` should create a new `Point` using the copy constructor and not add the argument directly, since it cannot have knowledge about the allocation of the referenced object. If that object is destroyed as its scope is exited, the added object will become invalid after the addition.
7. Implement the member `contains` to return `true` or `false` if the `Cluster` contains a `Point` equal (by `Point::operator==`) to the object referenced in the argument.
8. Implement the `const` member subscript `operator[]` to return a `const` reference to a particular `Point` in the ordered linked-list. The `Point` cannot be modified.
**Note:** Don't overuse this operator, because it is very inefficient for a singly-linked list.
9. Implement the _compound assignment_ member `operator+=` and `operator-=` with a `const Point &` argument.
**Usage:** Add a `Point` to or remove one from the `Cluster`:
```C++
c5 += p56;
c2 -= p98;
```
**Note:** Implementation is straightforward through the use of `add` and `remove`.
10. Implement the simple arithmetic `friend` `operator+` and `operator-` with one `const Cluster &` and one `const Point &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Create and return a new `Cluster` with the argument `Point` added to or removed one from the argument `Cluster`:
```C++
c7 = c5 + p56;
c9 = c2 - p98;
```
**Note:** Implementation is straightforward through the use of `operator+=` and `remove-=`.
11. Implement the _compound assignment_ member `operator+=` and `operator-=` with a `const Cluster &` argument. The addition of two `Cluster`s results in a **union** of the two, which contains all the unique points contained in either `Cluster`. For example, if `c5` contains `p12, p45, p78` and `c6` contains `p23, p45, p90`, then then the _union_ of `c5` and `c6` would contain `p12, p23, p45, p78, p90`. The subtraction of two `Cluster`s results in an **asymmetric difference** of the two. For example, if `c5` contains `p12, p45, p78` and `c6` contains `p23, p45, p90`, then then the **left** _assymetric difference_ of `c5` and `c6` (that is, `c5 - c6`) would contain `p12, p78`, while the **right** _assymetric difference_ of `c5` and `c6` (that is, `c6 - c5`) would contain `p23, p90`.
**Usage:** Make the calling `Cluster` object the union or assymetric difference of itself and the argument `Cluster` object:
```C++
c5 += c6;
c2 -= c8;
```
12. Implement the simple arithmetic `friend` `operator+` and `operator-` with two `const Cluster &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Create and return a new `Cluster` object that is the union or assymetric difference of the the two argument `Cluster` objects:
```C++
c10 = c5 + c6;
c11 = c2 - c8;
```
**Note:** Implementation is straighforward through the use of `operator+=` and `operator-=`.
13. Implement the equality and inequality comparison `friend` `operator==` and `operator!=` with two `const Cluster &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Check if two `Cluster`s are equal or unequal:
```C++
if (c3 == c5) {
// ...
}
if (c3 != c4) {
// ...
}
```
**Note:** Two `Cluster`s are _equal_ **iff** they contain the same `Point`s (by `Point::operator==`).
14. Implement the overloaded `friend` insertion `operator<<` with a `std::ostream` and a `const Cluster &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Right out (intert) a `Cluster` to an output stream:
```C++
cout << c7 << endl;
```
**Note:** A `Cluster` should write itself by writing its `Point`s in order, each on a separate line, as follows (note the _space_ after each comma):
```
1.2, 4.5, 6.7, 90.12, 34.54, 0.01
2.2, 4.5, 6.7, 90.12, 34.54, 0.01
3.2, 4.5, 6.8, 91.02, 34.04, 0.11
```
14. Implement the overloaded `friend` extraction `operator>>` with a `std::istream` and a non-`const` `Cluster &` arguments. A `friend` operator is a _non-member_ function with **private** access to the class where it is declared.
**Usage:** Read in (extract) a `Cluster` from an input stream:
```C++
std::ifstream csv("points.csv");
Cluster c;
if (csv.is_open()) {
csv >> c;
csv.close();
}
```
where the file <tt>points.csv</tt> contains
```
00002.3,5.6,0,5.6,7.9
1.3, 4.3, 0, 5.6, 7.9
2.4 , 5.6 , 0, 6.6 , 7.1
4.1,5.6,5,1.6,7.9
```
**Note:** The `Cluster` reads the input stream line-by-line, creates a `Point` with the right dimensionality for each line, and then delegates the reading of the line to the `operator<<` for `Point`.
**Note:** You might find the [std::count](http://en.cppreference.com/w/cpp/algorithm/count) function useful in determining the dimensionality of the Point you need to pass an input line to.
#### Clustering namespace
1. The `Point` and `Cluster` classes are created inside a `namespace`, as follows:
```C++
namespace Clustering {
class Point {
};
}
```
2. Both the class declarations and the method implementations have to wrapped with the `namespace Clustering {}` blocks.
3. When using the `Point` and `Cluster` classes, the namespace has to be specified, as follows:
```C++
#include "Point.h"
#include "Cluster.h"
using Clustering::Point;
using Clustering::Cluster;
int main() {
Point p1(10);
Cluster c1;
// ...
return 0;
}
```
or
```C++
#include "Point.h"
#include "Cluster.h"
using namespace Clustering;
int main() {
Point p1(10);
Cluster c1;
// ...
return 0;
}
```
or
```C++
#include "Point.h"
#include "Cluster.h"
int main() {
Clustering::Point p1(10);
Clustering::PCluster c1;
// ...
return 0;
}
```
<file_sep>// main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "ErrorContext.h"
#include "ClusteringTests.h"
using std::cout;
using std::endl;
using namespace Testing;
int main() {
const int NumIters = 3;
cout << endl << "Testing PA2!!" << endl << endl;
cout << "NOTE: If you see any memory errors, you MUST fix them!" << endl;
cout << " Tests intentionally invoke destructors after they complete,"
<< endl;
cout << " so if you see a seg-fault after a passed test, it is"
<< endl;
cout << " probably a bug in your destructor." << endl;
cout << endl;
ErrorContext ec(cout);
// point tests
test_point_smoketest(ec);
test_point_id(ec, NumIters);
test_point_getsetelem(ec, NumIters);
test_point_copying(ec, NumIters);
test_point_assignment(ec, NumIters);
test_point_equality(ec, NumIters);
test_point_comparison(ec, NumIters);
test_point_CAO(ec, NumIters);
test_point_SAO(ec, NumIters);
test_point_distance(ec, NumIters);
test_point_IO(ec, NumIters);
// cluster tests
test_cluster_smoketest(ec);
test_cluster_subscript(ec, NumIters);
test_cluster_equality(ec, NumIters);
test_cluster_order(ec, NumIters);
test_cluster_addremove(ec, NumIters);
test_cluster_contain(ec, NumIters);
test_cluster_copying(ec, NumIters);
test_cluster_assignment(ec, NumIters);
test_cluster_CAO(ec, NumIters);
test_cluster_SAO(ec, NumIters);
test_cluster_IO(ec, NumIters);
return 0;
}
<file_sep>#ifndef CLUSTERING_CLUSTER_H
#define CLUSTERING_CLUSTER_H
#include "Point.h"
namespace Clustering {
typedef struct LNode *LNodePtr;
struct LNode {
Point point;
LNodePtr next;
LNode(const Point &p, LNodePtr n);
};
class Cluster {
int __size;
LNodePtr __points;
void __del();
void __cpy(LNodePtr pts);
bool __in(const Point &p) const;
public:
Cluster();
// The big three: cpy ctor, overloaded operator=, dtor
Cluster(const Cluster &);
Cluster &operator=(const Cluster &);
~Cluster();
// Getters/setters
int getSize() const; // TODO add to the requirements
// Set functions: They allow calling c1.add(c2.remove(p));
void add(const Point &); // TODO add asc order to the requirements
const Point &remove(const Point &);
bool contains(const Point &);
// Overloaded operators
// Members: Subscript
const Point &operator[](unsigned int index) const; // notice: const
// Members: Compound assignment (Point argument)
Cluster &operator+=(const Point &);
Cluster &operator-=(const Point &);
// Members: Compound assignment (Cluster argument)
Cluster &operator+=(const Cluster &); // union
Cluster &operator-=(const Cluster &); // (asymmetric) difference
// Friends: IO
friend std::ostream &operator<<(std::ostream &, const Cluster &);
friend std::istream &operator>>(std::istream &, Cluster &);
// Friends: Comparison
friend bool operator==(const Cluster &, const Cluster &);
friend bool operator!=(const Cluster &, const Cluster &);
// Friends: Arithmetic (Cluster and Point)
friend const Cluster operator+(const Cluster &, const Point &);
friend const Cluster operator-(const Cluster &, const Point &);
// Friends: Arithmetic (two Clusters)
friend const Cluster operator+(const Cluster &, const Cluster &); // union
friend const Cluster operator-(const Cluster &, const Cluster &); // (asymmetric) difference
};
}
#endif //CLUSTERING_CLUSTER_H
<file_sep>cmake_minimum_required(VERSION 3.3)
project(ucd-csci2312-pa2)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp Point.cpp Point.h Cluster.cpp Cluster.h
ErrorContext.cpp ErrorContext.h ClusteringTests.cpp ClusteringTests.h)
add_executable(ucd-csci2312-pa2 ${SOURCE_FILES})<file_sep>// ClusteringTests.cpp
//
// Created by <NAME> on 10/29/15.
//
#include <iostream>
#include <cassert>
#include <iomanip>
#include <fstream>
#include "ClusteringTests.h"
#include "Point.h"
#include "Cluster.h"
using namespace Clustering;
using namespace Testing;
#define DESC(x) desc(x, __LINE__) // ugly hack, but saves some time
// - - - - - - - - - - helper functions - - - - - - - - - -
const Point point_in_and_out(const Point p) { return Point(p); }
// - - - - - - - - - - T E S T S - - - - - - - - - -
// - - - - - - - - - - P O I N T - - - - - - - - - -
// Smoketest: constructor, copy constructor, destructor
void test_point_smoketest(ErrorContext &ec) {
bool pass;
ec.DESC("--- Test - Point - Smoketest ---");
ec.DESC("constructor, dimensionality, destructor");
pass = true;
for (int i = 0; i < 10; i ++) {
// Construct a Point
// At the end of the block, destructor will be called
Point p(10);
pass = (p.getDims() == 10);
if (!pass) break;
}
ec.result(pass);
ec.DESC("constructor, large size");
pass = true;
for (int i = 0; i < 10; i ++) {
// Construct a Point
// At the end of the block, destructor will be called
Point p(1000000);
pass = (p.getDims() == 1000000);
if (!pass) break;
}
ec.result(pass);
ec.DESC("copy constructor");
pass = true;
for (int i = 0; i < 10; i ++) {
// Construct a Point
// At the end of the block, destructor will be called
Point p1(10);
Point p2(p1);
pass = (p1.getDims() == 10 && p2.getDims() == 10);
if (!pass) break;
}
ec.result(pass);
}
// id
void test_point_id(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Point ID ---");
for (int run = 0; run < numRuns; run ++)
{
ec.DESC("get a point's id");
{
Point p(15);
pass = (p.getId() >= 0);
ec.result(pass);
}
ec.DESC("sequential id-s");
{
Point **points = new Point*[100];
for (int i=0; i<100; i++)
points[i] = new Point(15);
pass = true;
int firstId = points[0]->getId();
for (int i=0; i<100; i++)
pass = pass && (points[i]->getId() == (firstId + i));
for (int i=0; i<100; i++)
delete points[i];
delete [] points;
ec.result(pass);
}
}
}
// setValue, getValue, operator[]
void test_point_getsetelem(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Get/set element ---");
for (int run = 0; run < numRuns; run ++)
{
ec.DESC("values default to zero");
{
Point p(50);
// Check zeros
pass = true;
for (int i = 0; i < 50; i ++) {
pass = pass &&
(p.getValue(i) == 0.0) &&
(p[i] == 0.0);
}
ec.result(pass);
}
ec.DESC("setValue, getValue (0-indexed)");
{
Point p(20);
// Set values
for (int i = 0; i < 20; i ++)
p.setValue(i, 13.43 * i * i + 4.567 * i + 1.234567);
// Check values
pass = true;
for (int i = 0; i < 20; i ++)
pass = pass &&
(p.getValue(i) == (13.43 * i * i + 4.567 * i + 1.234567)) &&
(p[i] == (13.43 * i * i + 4.567 * i + 1.234567));
ec.result(pass);
}
ec.DESC("operator[] (0-indexed)");
{
Point p(5);
// Set values
for (int i = 0; i < 5; i ++)
p[i] = 1000000.43 * i * i + 400000.567 * i + 10000.234567;
// Check values
pass = true;
for (int i = 0; i < 5; i ++)
pass = pass &&
(p.getValue(i) == (1000000.43 * i * i + 400000.567 * i + 10000.234567)) &&
(p[i] == (1000000.43 * i * i + 400000.567 * i + 10000.234567));
ec.result(pass);
}
}
}
// Copy constructor
void test_point_copying(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Copy ---");
for (int run = 0; run < numRuns; run ++) {
ec.DESC("simple copy");
{
Point p1(50);
for (int i = 0; i < 50; i ++)
p1[i] = 44.56 * i * i + 23.45 * i + 12.34;
Point p2(p1);
pass = true;
for (int i = 0; i < 50; i ++)
pass = pass && (p1[i] == p2[i]);
ec.result(pass);
}
ec.DESC("pass and return by value");
{
Point p1(50);
for (int i = 0; i < 50; i ++)
p1[i] = 44.56 * i * i + 23.45 * i + 12.34;
Point p2 = point_in_and_out(p1);
pass = true;
for (int i = 0; i < 50; i ++)
pass = pass && (p1[i] == p2[i]);
ec.result(pass);
}
}
}
// operator=
void test_point_assignment(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Assign ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("simple assignment");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 44.56 * i * i + 23.45 * i + 12.34;
Point p2 = p1;
pass = true;
for (int i = 0; i < 50; i++)
pass = pass && (p1[i] == p2[i]);
ec.result(pass);
}
ec.DESC("chained assignment");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 44.56 * i * i + 23.45 * i + 12.34;
Point p2(50), p3(50), p4(50), p5(50);
p2 = p3 = p4 = p5 = p1;
pass = true;
for (int i = 0; i < 50; i++)
pass = pass && (p1[i] == p2[i]);
ec.result(pass);
}
}
}
// operator==, operator!=
void test_point_equality(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Equal ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("compare equal");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 44.56 * i * i + 23.45 * i + 12.34;
Point p2(p1);
pass = (p2 == p1);
ec.result(pass);
}
ec.DESC("ensure operator== is not a dummy");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 44.56 * i * i + 23.45 * i + 12.34;
Point p2(p1);
p2[1] = p2[1] + 1.0;
pass = !(p2 == p1);
ec.result(pass);
}
ec.DESC("compare not equal");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 44.56 * i * i + 23.45 * i + 12.34;
Point p2(p1);
p1[49] = p1[49] + 100.0;
pass = (p2 != p1);
ec.result(pass);
}
}
}
// operator<, operator<=, operator>, operator>=
// (pseudo-lexicographic comparison)
void test_point_comparison(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Compare ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("compare pseudo-lexicographic order");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = i;
p2[i] = i + 1.0;
p3[i] = i + 2.0;
}
pass = (p1 < p2) &&
(p2 < p3) &&
(p1 < p3);
ec.result(pass);
}
ec.DESC("less than, one different value, leading");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
p2[1] = p1[1] + std::numeric_limits<double>::epsilon();
p3[1] = p2[1] + std::numeric_limits<double>::epsilon();
pass = (p1 < p2) &&
(p2 < p3) &&
(p1 < p3);
ec.result(pass);
}
ec.DESC("less than, one different value, middle");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
p2[30] = p1[30] + 0.00000001;
p3[30] = p2[30] + 0.00000001;
pass = (p1 < p2) &&
(p2 < p3) &&
(p1 < p3);
ec.result(pass);
}
ec.DESC("less than, one different value, trailing");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
p2[49] = p1[49] + 0.00000001;
p3[49] = p2[49] + 0.00000001;
pass = (p1 < p2) &&
(p2 < p3) &&
(p1 < p3);
ec.result(pass);
}
ec.DESC("less than or equal, equal values");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
pass = (p1 <= p2) &&
(p2 <= p3) &&
(p1 <= p3);
ec.result(pass);
}
ec.DESC("less than or equal, one different value, trailing");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
p2[49] = p1[49] + 0.00000001;
p3[49] = p2[49] + 0.00000001;
pass = (p1 <= p2) &&
(p2 <= p3) &&
(p1 <= p3);
ec.result(pass);
}
ec.DESC("more than or equal, equal values");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
pass = (p1 >= p2) &&
(p2 >= p3) &&
(p1 >= p3);
ec.result(pass);
}
ec.DESC("more than or equal, one different value, middle");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
p2[30] = p3[30] + 0.00000001;
p1[30] = p2[30] + 0.00000001;
pass = (p1 >= p2) &&
(p2 >= p3) &&
(p1 >= p3);
ec.result(pass);
}
ec.DESC("more than, one different value, middle");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i ++) {
p1[i] = p2[i] = p3[i] = i;
}
p2[30] = p3[30] + 0.00000001;
p1[30] = p2[30] + 0.00000001;
pass = (p1 > p2) &&
(p2 > p3) &&
(p1 > p3);
ec.result(pass);
}
}
}
// operator+=, operator-=, operator*=, operator/=
void test_point_CAO(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Compound arithmetic ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("plus equals (two points)");
{
Point p1(50), p2(50);
for (int i = 0; i < 50; i++) {
p1[i] = i;
p2[i] = i + 1;
}
Point p3(50);
p3 += p1 += p2;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p3[i] == 2 * i + 1);
}
ec.result(pass);
}
ec.DESC("minus equals (two points)");
{
Point p1(50), p2(50), p3(50);
for (int i = 0; i < 50; i++) {
p1[i] = i;
p2[i] = i + 1;
p3[i] = 3 * i + 1;
}
p3 -= p2 -= p1;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p3[i] == 3 * i);
}
ec.result(pass);
}
ec.DESC("times equals (point and double)");
{
Point p1(50);
for (int i = 0; i < 50; i++) {
p1[i] = i;
}
p1 *= 3.14;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p1[i] == 3.14 * i);
}
ec.result(pass);
}
ec.DESC("divide equals (point and double)");
{
Point p1(50);
for (int i = 0; i < 50; i++) {
p1[i] = 100.0 * i;
}
p1 /= 3.14;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p1[i] == 100.0 * i / 3.14);
}
ec.result(pass);
}
}
}
// operator+, operator-, operator*, operator/
void test_point_SAO(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Simple arithmetic ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("plus (two points)");
{
Point p1(50), p2(50);
for (int i = 0; i < 50; i++) {
p1[i] = i;
p2[i] = i + 1;
}
Point p3 = p1 + p2;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p3[i] == 2 * i + 1);
}
ec.result(pass);
}
ec.DESC("minus (two points)");
{
Point p1(50), p2(50);
for (int i = 0; i < 50; i++) {
p1[i] = i + 1;
p2[i] = 2 * i - 1;
}
Point p3 = p2 - p1;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p3[i] == i - 2);
}
ec.result(pass);
}
ec.DESC("times (point and double)");
{
Point p1(50);
for (int i = 0; i < 50; i++) {
p1[i] = i;
}
Point p2 = p1 * 3.14;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p2[i] == 3.14 * i);
}
ec.result(pass);
}
ec.DESC("divide (point and double)");
{
Point p1(50);
for (int i = 0; i < 50; i++) {
p1[i] = 100.0 * i;
}
Point p2 = p1 / 3.14;
pass = true;
for (int i = 0; i < 50; i++) {
pass = pass && (p2[i] == 100.0 * i / 3.14);
}
ec.result(pass);
}
}
}
// distanceTo
void test_point_distance(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Distance ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("same point");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 2.4 * i * i + 1.3 * i + 6.7;
Point p2(p1);
pass = (p1.distanceTo(p2) == 0);
ec.result(pass);
}
ec.DESC("5 units away");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = i;
Point p2(p1);
p2[1] += 5;
pass = (p1.distanceTo(p2) == 5);
if (!pass) std::cout << p1.distanceTo(p2) << " ";
ec.result(pass);
}
// Integer sequence A180442
ec.DESC("distance 1612 from origin");
{
Point p1(169); // 198 - 29
unsigned int start = 30;
for (int i = 0; i < 169; i++) {
p1[i] = start;
start++;
}
Point origin(169); // relies on initialization to zeros
pass = (p1.distanceTo(origin) == 1612);
if (!pass) std::cout << p1.distanceTo(origin) << " ";
ec.result(pass);
}
}
}
// operator>>, operator<< (incl. exceptions)
void test_point_IO(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Point - Stream IO ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("stream between two points");
{
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 6.12 * i * i + 5.17 * i + 4.19;
Point p2(50);
std::stringstream iostr;
iostr << std::setprecision(20) << p1; // Avoid truncation
iostr >> p2;
pass = true;
for (int i = 0; i < 50; i++)
pass = pass && (p2[i] == p1[i]);
if (!pass) {
std::cout << p1 << std::endl;
std::cout << p2 << std::endl;
}
ec.result(pass);
}
}
}
// - - - - - - - - - - C L U S T E R - - - - - - - - - -
// Smoketest: constructor, copy constructor, destructor
void test_cluster_smoketest(ErrorContext &ec) {
bool pass;
ec.DESC("--- Test - Cluster - Smoketest ---");
ec.DESC("constructor, destructor");
pass = true;
for (int i = 0; i < 10; i ++) {
Cluster c;
}
ec.result(pass);
ec.DESC("size getter - implement if you haven't");
pass = true;
for (int i = 0; i < 10; i ++) {
// Construct a Point
// At the end of the block, destructor will be called
Cluster c;
pass = (c.getSize() == 0);
if (!pass) break;
}
ec.result(pass);
ec.DESC("copy constructor");
pass = true;
for (int i = 0; i < 10; i ++) {
Cluster c1, c2(c1);
pass = (c1 == c2);
if (!pass) break;
}
ec.result(pass);
}
// add, remove
void test_cluster_addremove(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Add/remove points ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("add and check with size getter");
{
Cluster c1;
c1.add(Point(50));
c1.add(Point(50));
c1.add(Point(50));
pass = (c1.getSize() == 3);
ec.result(pass);
} // by default, points will get released here
ec.DESC("add, remove, and check with size getter");
{
Point p1(10),
p2(10),
p3(10);
Cluster c1;
c1.add(p1); c1.add(p2); c1.add(p3);
c1.remove(p1); c1.remove(p2); c1.remove(p3);
pass = (c1.getSize() == 0);
if (!pass) {
std::cout << std::endl;
std::cout << c1 << std::endl;
std::cout << std::endl;
}
ec.result(pass);
} // by default, points will get released here
ec.DESC("add, check with cluster equality, remove");
{
Point p1(10),
p2(10),
p3(10);
Cluster c1, c2;
c1.add(p1); c1.add(p2); c1.add(p3);
c2.add(p1); c2.add(p2); c2.add(p3);
pass = (c1 == c2);
// don't forget to remove the points from one
// of the clusters to avoid the "double delete"
c2.remove(p1); c2.remove(p2); c2.remove(p3);
ec.result(pass);
}
ec.DESC("check point after add and remove");
{
Point p1(10);
for (int i = 0; i < 10; i++)
p1[i] = 5.4 * i * i + 3.4 * i + 1.6;
Cluster c1;
c1.add(p1);
Point p2 = c1.remove(p1);
pass = (p1 == p2);
ec.result(pass);
}
}
}
// Containment
void test_cluster_contain(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Containment ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("cluster with one point");
{
Point p(10);
p[0] = p[2] = p[4] = p[8] = 6.705;
Cluster c;
c.add(p);
pass = c.contains(p);
ec.result(pass);
}
ec.DESC("cluster with several points");
{
Point p(10);
p[0] = p[2] = p[4] = p[8] = 6.705;
Cluster c;
for (int i = 0; i < 10; i ++) {
Point pp(10);
for (int j = 0; j < 10; j ++) {
pp[i] = 3.4 + i * 2.1 + i * i;
}
c.add(pp);
}
c.add(p);
pass = c.contains(p);
ec.result(pass);
}
}
}
// Copy constructor
void test_cluster_copying(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Copy ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("simple copy");
{
Point p1(10),
p2(10),
p3(10);
Cluster c1;
c1.add(p1); c1.add(p2); c1.add(p3);
Cluster c2(c1);
pass = (c1 == c2);
ec.result(pass);
}
ec.DESC("chained copy");
{
Point p1(10),
p2(10),
p3(10);
Cluster c1;
c1.add(p1); c1.add(p2); c1.add(p3);
Cluster c2(c1), c3(c2), c4(c3);
pass = (c1 == c4);
ec.result(pass);
}
}
}
// operator=
void test_cluster_assignment(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Assign ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("simple assignment");
{
Point p1(10),
p2(10),
p3(10);
Cluster c1;
c1.add(p1); c1.add(p2); c1.add(p3);
Cluster c2 = c1;
pass = (c1 == c2);
ec.result(pass);
}
ec.DESC("assignment causing deletion");
{
Point p1(10),
p2(10),
p3(10);
Cluster c1;
c1.add(p1); c1.add(p2); c1.add(p3);
Cluster c2;
// add some other points
c2.add(Point(10));
c2.add(Point(10));
c2.add(Point(10));
c2 = c1;
pass = (c1 == c2);
ec.result(pass);
}
ec.DESC("chained assignment");
{
Point p1(10),
p2(10),
p3(10);
Cluster c1;
c1.add(p1); c1.add(p2); c1.add(p3);
Cluster c2 = c1;
Cluster c3 = c2;
Cluster c4 = c3;
pass = (c1 == c4);
ec.result(pass);
}
}
}
// subscript (operator[])
void test_cluster_subscript(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Subscript ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("cluster with one point");
{
Cluster c;
Point p(10);
p[5] = 3.14;
c.add(p);
Point p1 = c[0];
pass = p1[5] == 3.14;
ec.result(pass);
}
ec.DESC("cluster with several points");
{
Cluster c;
for (int i = 0; i < 10; i ++) {
Point p(10);
p[5] = 3.14;
c.add(p);
}
pass = true;
for (int i = 0; i < 10; i ++) {
Point p1 = c[i];
pass = pass && (p1[5] == 3.14);
}
ec.result(pass);
}
}
}
// operator==, operator!=
void test_cluster_equality(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Equal ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("check operator== is not a dummy");
{
// The requirements don't provide for many other methods that
// can be used for testing, so operator== is checked first
Cluster c1, c2;
c1.add(Point(100));
pass = !(c1 == c2);
ec.result(pass);
}
ec.DESC("check inequality");
{
// The requirements don't provide for many other methods that
// can be used for testing, so operator== is checked first
Cluster c1, c2;
c1.add(Point(100));
pass = (c1 != c2);
ec.result(pass);
}
}
}
// ascending pseudo-lexicographic order
void test_cluster_order(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Order ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("points in a cluster are sorted");
{
Point p1(5), p2(5), p3(5), p4(5), p5(5);
p1[0] = 1;
p2[1] = 1;
p3[2] = 1;
p4[3] = 1;
p5[4] = 1;
Cluster c;
c.add(p1);
c.add(p2);
c.add(p4);
c.add(p3);
c.add(p5);
pass = (c[0] == p5)
&& (c[1] == p4)
&& (c[2] == p3)
&& (c[3] == p2)
&& (c[4] == p1);
if (!pass) {
std::cout << std::endl;
std::cout << c << std::endl;
std::cout << std::endl;
}
ec.result(pass);
}
ec.DESC("ascending pseudo-lexicographic order");
{
Point p1(5), p2(5), p3(5), p4(5), p5(5);
p1[0] = 1;
p2[1] = 1;
p3[2] = -1;
p4[3] = 1;
p5[4] = -1;
Cluster c;
c.add(p1);
c.add(p2);
c.add(p4);
c.add(p3);
c.add(p5);
pass = (c[0] == p3)
&& (c[1] == p5)
&& (c[2] == p4)
&& (c[3] == p2)
&& (c[4] == p1);
if (!pass) {
std::cout << std::endl;
std::cout << c << std::endl;
std::cout << std::endl;
}
ec.result(pass);
}
}
}
// operator+=, operator-=, different rhs
void test_cluster_CAO(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Compound arithmetic ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("plus equals (Cluster and Point) check with non-equality");
{
Cluster c1, c2;
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 6.75 * i * i + 5.45 * i + 1.15;
c1 += p1;
pass = !(c1 == c2);
ec.result(pass);
}
ec.DESC("plus equals (Cluster and Point) check with size getter");
{
Cluster c1;
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 6.75 * i * i + 5.45 * i + 1.15;
c1 += p1;
pass = (c1.getSize() == 1);
ec.result(pass);
}
ec.DESC("minus equals (Cluster and Point) check with non-equality");
{
Cluster c1, c2;
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 6.75 * i * i + 5.45 * i + 1.15;
c1 += p1;
pass = !(c1 == c2);
c1 -= p1;
pass = (c1 == c2);
ec.result(pass);
}
ec.DESC("minus equals (Cluster and Point) check with size getter");
{
Cluster c1;
Point p1(50);
for (int i = 0; i < 50; i++)
p1[i] = 6.75 * i * i + 5.45 * i + 1.15;
c1 += p1;
pass = (c1.getSize() == 1);
c1 -= p1;
pass = (c1.getSize() == 0);
ec.result(pass);
}
ec.DESC("plus equals (Cluster union) no common points");
{
Cluster c1, c2, c3;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3);
c2.add(p4); c2.add(p5);
// create a union to compare to
c3.add(p1); c3.add(p2); c3.add(p3);
c3.add(p4); c3.add(p5);
c1 += c2;
pass = (c1 == c3);
ec.result(pass);
}
ec.DESC("plus equals (Cluster union) one common point");
{
Cluster c1, c2, c3;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3);
c2.add(p3); c2.add(p4); c2.add(p5);
// create a union to compare to
c3.add(p1); c3.add(p2); c3.add(p3);
c3.add(p4); c3.add(p5);
c1 += c2;
pass = (c1 == c3);
ec.result(pass);
}
ec.DESC("plus equals (Cluster union) two equal clusters");
{
Cluster c1, c2;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3); c1.add(p4); c1.add(p5);
c2.add(p1); c2.add(p2); c2.add(p3); c2.add(p4); c2.add(p5);
c1 += c2;
pass = (c1 == c2);
ec.result(pass);
}
ec.DESC("minus equals (asymmetric Cluster difference) no common points");
{
Cluster c1, c2, c3;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3);
c2.add(p4); c2.add(p5);
c3 = c1;
c1 -= c2;
pass = (c1 == c3);
ec.result(pass);
}
ec.DESC("minus equals (asymmetric Cluster difference) one common point");
{
Cluster c1, c2, c3;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3);
c2.add(p3); c2.add(p4); c2.add(p5);
// Prepare a difference to compare to
c3.add(p1); c3.add(p2);
c1 -= c2;
pass = (c1 == c3);
ec.result(pass);
}
ec.DESC("minus equals (asymmetric Cluster difference) two equal clusters");
{
Cluster c1, c2, c3;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3); c1.add(p4); c1.add(p5);
c2.add(p1); c2.add(p2); c2.add(p3); c2.add(p4); c2.add(p5);
c1 -= c2;
pass = (c1 == c3); // c1 should be empty
ec.result(pass);
}
}
}
// operator+, operator-, different rhs
void test_cluster_SAO(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Simple arithmetic ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("plus (Cluster and Point)");
{
Cluster c1, c2;
Point p1(50),
p2(50),
p3(50),
p4(50);
c1.add(p1); c1.add(p2); c1.add(p3);
c2 = c1; c2.add(p4);
Cluster c3 = c1 + p4;
pass = (c3 == c2);
ec.result(pass);
}
ec.DESC("minus (Cluster and Point)");
{
Cluster c1, c2;
Point p1(50),
p2(50),
p3(50),
p4(50);
c1.add(p1); c1.add(p2); c1.add(p3); c1.add(p4);
c2 = c1; c2.remove(p4);
Cluster c3 = c1 - p4;
pass = (c3 == c2);
ec.result(pass);
}
ec.DESC("plus (Cluster union)");
{
Cluster c1, c2;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3);
c2.add(p4); c2.add(p5);
Cluster c3;
c3.add(p1); c3.add(p2); c3.add(p3); c3.add(p4); c3.add(p5);
Cluster c4 = c1 + c2;
pass = (c4 == c3);
ec.result(pass);
}
ec.DESC("minus (Cluster difference)");
{
Cluster c1, c2;
Point p1(50),
p2(50),
p3(50),
p4(50),
p5(50);
c1.add(p1); c1.add(p2); c1.add(p3);
c2.add(p3); c2.add(p4); c2.add(p5);
Cluster c3;
c3.add(p1); c3.add(p2);
Cluster c4 = c1 - c2;
pass = (c4 == c3);
ec.result(pass);
}
}
}
// operator>>, operator<<
void test_cluster_IO(ErrorContext &ec, unsigned int numRuns) {
bool pass;
// Run at least once!!
assert(numRuns > 0);
ec.DESC("--- Test - Cluster - Stream IO ---");
for (int run = 0; run < numRuns; run++) {
ec.DESC("read from a file");
{
std::ifstream csv("points.csv");
Cluster c;
if (csv.is_open()) {
csv >> c;
csv.close();
}
pass = (c.getSize() == 4);
ec.result(pass);
}
ec.DESC("read, write, and read again");
{
std::ifstream csv("points.csv");
Cluster c;
if (csv.is_open()) {
csv >> c;
csv.close();
}
pass = (c.getSize() == 4);
// add a point
c.add(Point(5));
std::ofstream csv1("points1.csv", std::ofstream::out);
csv1 << c;
csv1.close();
std::ifstream csv2("points1.csv");
Cluster c2;
if (csv2.is_open()) {
csv2 >> c2;
csv2.close();
}
pass = pass && (c2.getSize() == 5);
ec.result(pass);
}
}
}
| 8fe242ee888c7b5de997ec9a8bb7bf5c5792b7af | [
"Markdown",
"CMake",
"C++"
] | 6 | C++ | ivogeorg/ucd-csci2312-pa2 | d278acff9cb10cbd897bff8c5b245bf80ac26d8d | 28f381d266c6ef1af889295ba504cb892e71b68d |
refs/heads/master | <file_sep>// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// 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 (
"os"
"path"
"github.com/fatih/color"
"github.com/paulsevere/rmds/walker"
)
func main() {
args := os.Args[1:]
// spew.Dump(args[0])
dir, err := os.Getwd()
if err != nil {
println(err.Error())
return
}
var target_dir string
var target_rm string
if len(args) == 1 {
target_dir = path.Join(dir, args[0])
target_rm = ".DS_Store"
} else if len(args) == 2 {
target_dir = path.Join(dir, args[1])
target_rm = args[0]
} else {
target_dir = dir
}
if pathIsDir(target_dir) {
walker.Walk(target_rm, target_dir)
} else {
color.Red("Please enter a valid directory path")
}
// walker.Walk(dir)
}
func pathIsDir(path string) bool {
if stat, err := os.Stat(path); err == nil && stat.IsDir() {
return true
}
return false
}
<file_sep># RMDS
##### A simple tool for recursively removing .DS_Store files
#### Installation
```bash
go get -u github.com/paulsevere/rmds
```
#### Usage
```bash
rmds <directory/file name?> <path?>
```
<div style="padding:0px 50px;">
<p>
If you enter a relative path name, rmds will begin its recursive search from that path. Otherwise, it will use the current directory.
</p>
</div>
<file_sep>package walker
import (
"fmt"
"os"
"github.com/fatih/color"
"github.com/michaelTJones/walk"
)
var count = 0
func Walk(target string, path string) {
walk.Walk(path, createWalker(target))
colorPrint(count)
}
func createWalker(target string) func(string, os.FileInfo, error) error {
return func(path string, info os.FileInfo, err error) error {
if info.Name() == target {
// spew.Dump(path)
delerr := os.Remove(path)
if delerr != nil {
return delerr
} else {
count++
// println("Removed DS_Store in " + path)
}
}
// spew.Dump(path, info.IsDir())
return err
}
}
func walker(path string, info os.FileInfo, err error) error {
if info.Name() == ".DS_Store" {
// spew.Dump(path)
delerr := os.Remove(path)
if delerr != nil {
return delerr
} else {
count++
// println("Removed DS_Store in " + path)
}
}
// spew.Dump(path, info.IsDir())
return err
}
func colorPrint(i interface{}) {
yellow := color.New(color.FgGreen).SprintFunc()
fmt.Printf("Removed %v items", yellow(i))
}
| 79b8c5409b15384b459bfc62d55a55833b7aed65 | [
"Markdown",
"Go"
] | 3 | Go | paulsevere/rmds | 1c2c775b598662d2857b2e94d81328d1d5dd30f7 | 0e1859a057cf28f9c31aa6b5da27f66a975884fb |
refs/heads/master | <repo_name>yy19941102/LSLogAnalystic<file_sep>/src/main/java/com/qianfeng/etl/util/LogUtil.java
package com.qianfeng.etl.util;
import com.qianfeng.common.EventLogConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 每一行的日志解析工具
*/
public class LogUtil {
private static Logger logger = Logger.getLogger(LogUtil.class);
/**
* 单行日志解析
*
* @param log 192.168.216.1^A1256798789.123^A192.168.216.111^1.png?en=e_l&ver=1&u_ud=679f-dfsa-u789-dfaa
* @return
*/
//单行日志的解析
public static Map<String, String> handleLog(String log) {
Map<String, String> info = new ConcurrentHashMap<String, String>();
// 判断log是否为空
if (StringUtils.isNotEmpty(log.trim())) {
//拆分单行日志
String[] fields = log.split(EventLogConstants.LOG_SPARTOR); // 采用"^A"进行切分
if (fields.length == 4) {
//存储数据到info中
info.put(EventLogConstants.EVENT_COLUMN_NAME_IP, fields[0]);
info.put(EventLogConstants.EVENT_COLUMN_NAME_SERVER_TIME,
fields[1].replaceAll("\\.", "")); // 时间戳解析
// 将参数列表中的k-v解析存储到info
// 获取?之后的参数列表
int index = fields[3].indexOf("?");
//处理参数列表
handleParams(info, fields[3]);
//处理ip
handleIp(info);
//处理useragent
handleUserAgent(info);
} else {
info.clear();
}
}
return info;
}
/**
* 处理useragent
*/
private static void handleUserAgent(Map<String, String> info) {
if (info.containsKey(EventLogConstants.EVENT_COLUMN_NAME_USERAGENT)) {
UserAgentUtil.UserAgentInfo ua = UserAgentUtil.parseUserAgent(info.get(EventLogConstants.EVENT_COLUMN_NAME_USERAGENT));
if (ua != null) {
info.put(EventLogConstants.EVENT_COLUMN_NAME_BROWSER_NAME, ua.getBrowserName());
info.put(EventLogConstants.EVENT_COLUMN_NAME_BROWSER_VERSION, ua.getBrowserVersion());
info.put(EventLogConstants.EVENT_COLUMN_NAME_OS_NAME, ua.getOsName());
info.put(EventLogConstants.EVENT_COLUMN_NAME_OS_VERSION, ua.getOsVersion());
}
}
}
/**
* 解析ip后存储到info中
* @param info
*/
private static void handleIp(Map<String, String> info) {
String ip = info.get(EventLogConstants.EVENT_COLUMN_NAME_IP);
if (StringUtils.isNotEmpty(ip)){
IPParserUtil.RegionInfo regionInfo = new IPParserUtil().parserIp(ip);
if (regionInfo!=null){
info.put(EventLogConstants.EVENT_COLUMN_NAME_COUNTRY,regionInfo.getCountry());
info.put(EventLogConstants.EVENT_COLUMN_NAME_PROVINCE,regionInfo.getProvince());
info.put(EventLogConstants.EVENT_COLUMN_NAME_CITY,regionInfo.getCity());
}
}
}
/**
* 处理参数
*
* @param info
* @param field
*/
private static void handleParams(Map<String, String> info, String field) {
if (StringUtils.isNotEmpty(field)) {
int index = field.indexOf("?");
if (index > 0) {
String fields = field.substring(index + 1);
String[] params = fields.split("&");
for (String param : params) {
try {
String[] kvs = param.split("=");
String k = URLDecoder.decode(kvs[0], "utf-8");
String v = URLDecoder.decode(kvs[1], "utf-8");
if (StringUtils.isNotEmpty(k) && StringUtils.isNotEmpty(v)) {
info.put(k, v);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
<file_sep>/src/main/java/com/qianfeng/analystic/mr/nu/TableMapper.java
package com.qianfeng.analystic.mr.nu;
/**
* Created by MaoMao on 2018/8/20 15:58
* ctrl + O:重写方法
* @Description:
*/
public class TableMapper {
}
<file_sep>/src/main/java/com/qianfeng/util/TimeUtil.java
package com.qianfeng.util;
import com.qianfeng.common.DateEnum;
import org.apache.commons.lang3.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @DESCRIPTION 全局的时间工具类
*/
public class TimeUtil {
private static final String DEFAULT_DATA_FORMAT = "yyyy-MM-dd"; // 默认时间格式
/**
* 判断时间是否有效,返回true:有效
*
* @param date
* @return
*/
public static boolean isValidateData(String date) {
Matcher matcher = null;
Boolean res = false;
String regexp = "^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}";
if (StringUtils.isNotEmpty(date)) {
Pattern pattern = Pattern.compile(regexp);
matcher = pattern.matcher(date);
}
return false;
}
/**
* 获取昨天默认格式的日期
*
* @return
*/
public static String getYesterday() {
return getYesterday(DEFAULT_DATA_FORMAT);
}
/**
* 获取昨天指定格式的日期
*
* @param pattern
* @return
*/
public static String getYesterday(String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, -1);
return sdf.format(calendar.getTime());
}
/**
* 将时间戳转化为指定格式的日期
*
* @param time 15289878934549
* @return 2018-07-05
*/
public static String parseLong2String(long time) {
return parseLong2String(time, DEFAULT_DATA_FORMAT);
}
public static String parseLong2String(long time, String pattern) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
return new SimpleDateFormat(pattern).format(calendar.getTime());
}
/**
* 将默认的日期格式转化为时间戳
*
* @param date
* @return
*/
public static long parseLong2String(String date) {
return parseString2Long(date, DEFAULT_DATA_FORMAT);
}
public static long parseString2Long(String date, String pattern) {
Date dt = null;
try {
dt = new SimpleDateFormat(pattern).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dt == null ? 0 : dt.getTime();
}
/**
* 根据时间戳和type来获取对应值
* @param time
* @param type
* @return
*/
public static int getDataInfo(long time, DateEnum type) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
if (DateEnum.YEAR.equals(type)) {
return calendar.get(Calendar.YEAR);
}
if (DateEnum.SEASON.equals(type)) {
int month = calendar.get(Calendar.MONTH) + 1;
// 123 1 ; 456 2 ; 789 3 ;10,11,12 4
if (month % 3 == 0) {
return month / 3;
}
return month / 3 + 1;
}
if (DateEnum.MONTH.equals(type)){
int month=calendar.get(Calendar.MONTH)+1;
return month;
}
if (DateEnum.WEEK.equals(type)){
return calendar.get(Calendar.WEEK_OF_YEAR);
}
if (DateEnum.DAY.equals(type)){
return calendar.get(Calendar.DAY_OF_MONTH);
}
if (DateEnum.HOUR.equals(type)){
return calendar.get(Calendar.HOUR_OF_DAY);
}
throw new RuntimeException("该类型暂不支持时间信息获取.type:"+type.typeName);
}
/**
* 根据时间戳获取当天所在周的第一天
* @param time
* @return
*/
public static long getFirstDayOfWeek(long time){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
calendar.set(Calendar.DAY_OF_WEEK,1);
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
return calendar.getTimeInMillis();
}
public static void main(String[] args) {
System.out.println(getDataInfo(1530720000000l,DateEnum.DAY));
System.out.println(getDataInfo(1530720000000l,DateEnum.SEASON));
System.out.println(getDataInfo(1530720000000l,DateEnum.MONTH));
System.out.println(getFirstDayOfWeek(1530720000000l));
}
}
<file_sep>/src/main/java/com/qianfeng/analystic/model/dim/value/reduce/BaseStatusValueWritable.java
package com.qianfeng.analystic.model.dim.value.reduce;
import com.qianfeng.common.KpiType;
import org.apache.hadoop.io.Writable;
/**
* Created by MaoMao on 2018/8/20 19:27
*
* @Description:输出的valueleix的顶级父类
*/
public abstract class BaseStatusValueWritable implements Writable {
// 获取Kpi的类型
public abstract KpiType getKpi();
}
<file_sep>/src/main/java/com/qianfeng/analystic/model/dim/value/reduce/LocationReduceOutputWritable.java
package com.qianfeng.analystic.model.dim.value.reduce;
import com.qianfeng.common.KpiType;
import org.apache.hadoop.io.WritableUtils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Created by MaoMao on 2018/8/20 23:19
*
* @Description:地域模块下reduce阶段输出的value类型
*/
public class LocationReduceOutputWritable extends BaseStatusValueWritable {
private KpiType kpi;
private int activeUsers; // 地域维度活跃用户个数
private int sessions; // 地域维度的会话个数
private int bouceSessions; // 地域维度的跳出会话个数
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(this.activeUsers);
out.writeInt(this.sessions);
out.writeInt(this.bouceSessions);
WritableUtils.writeEnum(out,this.kpi);
}
@Override
public void readFields(DataInput in) throws IOException {
this.activeUsers=in.readInt();
this.sessions=in.readInt();
this.bouceSessions=in.readInt();
WritableUtils.readEnum(in,KpiType.class);
}
@Override
public KpiType getKpi() {
return this.kpi;
}
public void setKpi(KpiType kpi) {
this.kpi = kpi;
}
public int getActiveUsers() {
return activeUsers;
}
public void setActiveUsers(int activeUsers) {
this.activeUsers = activeUsers;
}
public int getSessions() {
return sessions;
}
public void setSessions(int sessions) {
this.sessions = sessions;
}
public int getBouceSessions() {
return bouceSessions;
}
public void setBouceSessions(int bouceSessions) {
this.bouceSessions = bouceSessions;
}
}
<file_sep>/README.md
# LSLogAnalystic
hadoop项目阶段
| ae77899d7f681e0a3fa5c8939b3fb997819c8b08 | [
"Markdown",
"Java"
] | 6 | Java | yy19941102/LSLogAnalystic | a7d1dfa808debab79d5c6a98e5fefc60e6e71fd9 | 4d8700a9a7350a352fefc71b21a19022e1643215 |
refs/heads/master | <file_sep>const homeBtn = document.querySelector('.nav__home');
const myLibraryBtn = document.querySelector('.nav__library');
const myLibrary = document.querySelector('.js-library-page');
const detailsPage = document.querySelector('.js-details-page');
const homePage = document.querySelector('.js-home-page');
const headerLogo = document.querySelector('.header__logo');
const card = document.querySelector('.card__container');
homeBtn.addEventListener('click', activeHomePage);
myLibraryBtn.addEventListener('click', activeLibraryPage);
headerLogo.addEventListener('click', activeHomePage);
activeHomePage()
function activeLibraryPage() {
homePage.classList.add('visually-hidden');
myLibrary.classList.remove('visually-hidden');
detailsPage.classList.add('visually-hidden');
}
function activeHomePage() {
homePage.classList.remove('visually-hidden');
myLibrary.classList.add('visually-hidden');
detailsPage.classList.add('visually-hidden');
}
function activeDetailsPage(id, isHome) {
homePage.classList.add('visually-hidden');
myLibrary.classList.add('visually-hidden');
detailsPage.classList.remove('visually-hidden');
renderDetailsPage(id, isHome);
}
<file_sep>'use strict';
let renderFilms = [];
let genres = [];
let pageNumber = 1;
const list = document.querySelector('.cards__container');
function createCardFunc({ backdrop_path, title, id, vote_average }) {
const li = document.createElement('li');
li.className = 'card__container';
const divMark = document.createElement('div');
divMark.className = 'card__mark';
divMark.innerHTML = vote_average!==0?vote_average:'--';
const divTitle = document.createElement('div');
divTitle.className = 'card__title';
divTitle.innerHTML = title;
const img = document.createElement('img');
img.className = 'card__img';
let imgSrc = backdrop_path!==null?`https://image.tmdb.org/t/p/w500/${backdrop_path}`:"https://image.tmdb.org/t/p/w500//gkuyOdCeuKLdOlwQIUF44SHsYCq.jpg";
img.setAttribute('src', imgSrc);
img.setAttribute('alt', title);
li.append(divMark, divTitle, img);
list.appendChild(li);
li.addEventListener('click', () => activeDetailsPage(id, false));
return li;
}
function fetchPopularMoviesList() {
const fragment = document.createDocumentFragment();
fetch(
`https://api.themoviedb.org/3/movie/popular?api_key=56d683041d5d1a0178e72b4a2ffc8e86&language=en-US&page=${pageNumber}`,
)
.then(res => res.json())
.then(data => data.results)
.then(res => {
res.map(film => {
renderFilms.push(film);
fragment.append(createCardFunc(film));
});
list.innerHTML = '';
list.append(fragment);
});
}
function fetchGenres() {
fetch(
`https://api.themoviedb.org/3/genre/movie/list?api_key=56d683041d5d1a0178e72b4a2ffc8e86&language=en-US`,
)
.then(res => res.json())
.then(data => data.genres)
.then(res => {
res.map(film => {
genres.push(film);
});
});
}
fetchPopularMoviesList();
fetchGenres();
<file_sep>
const libraryCards = document.querySelector('.cards__wrapper');
const createCardLibrary = function ({ backdrop_path, title, id, vote_average }) {
const li = document.createElement('li');
li.className = 'card__container';
const divMark = document.createElement('div');
divMark.className = 'card__mark';
divMark.innerHTML = vote_average !== 0 ? vote_average : '--';
const divTitle = document.createElement('div');
divTitle.className = 'card__title';
divTitle.innerHTML = title;
const img = document.createElement('img');
img.className = 'card__img';
let imgSrc = backdrop_path !== null ? `https://image.tmdb.org/t/p/w500/${backdrop_path}` : "https://image.tmdb.org/t/p/w500//gkuyOdCeuKLdOlwQIUF44SHsYCq.jpg";
img.setAttribute('src', imgSrc);
img.setAttribute('alt', title);
li.append(divMark, divTitle, img);
libraryCards.appendChild(li);
li.addEventListener('click', () => activeDetailsPage(id, false));
}
const librarySpinWatchd = document.querySelector('.library__spin__list-item-watched');
const librarySpinQueue = document.querySelector('.library__spin__list-item-queue');
let libraryCardsWatched = localStorage.getItem('watched') ? JSON.parse(localStorage.getItem('watched')) : [];//запишемо дані з лок.стор в змінну
if (libraryCardsWatched.length == 0) {
libraryCards.innerHTML = 'Your movies for watching will be here ';
} else {
libraryCardsWatched.forEach(film => {
createCardLibrary(film)
});
}
librarySpinWatchd.addEventListener('click', () => {
libraryCardsWatched = localStorage.getItem('watched') ? JSON.parse(localStorage.getItem('watched')) : [];
if (libraryCardsWatched.length === 0) {
libraryCards.innerHTML = 'Your movies for watching will be here ';
} else {
libraryCards.innerHTML = '';
libraryCardsWatched.forEach(film => {
createCardLibrary(film)
});
}
librarySpinWatchd.classList.add('library__spin__list-item-active');
librarySpinQueue.classList.remove('library__spin__list-item-active');
});
librarySpinQueue.addEventListener('click', () => {
let libraryCardsQueue = localStorage.getItem('queue') ? JSON.parse(localStorage.getItem('queue')) : [];
if (libraryCardsQueue.length === 0) {
libraryCards.innerHTML = 'Your movies in queue will be here';
} else {
libraryCards.innerHTML = '';
libraryCardsQueue.forEach(film => {
createCardLibrary(film)
});
}
librarySpinQueue.classList.add('library__spin__list-item-active');
librarySpinWatchd.classList.remove('library__spin__list-item-active');
})
<file_sep>let inputValue = document.querySelector('.card__search_input');
const form = document.querySelector('#js-form');
const error = document.querySelector('.error');
const buttonBar = document.querySelector('.switching-bar_content');
const buttonBarPrev = document.querySelector('.switching-bar_prev');
const barSpan = document.querySelector('.switching-bar_span');
form.addEventListener('submit', hundleSubmit);
function hundleSubmit(evt) {
evt.preventDefault();
searchFilms();
}
function searchFilms() {
fetchFilms(inputValue.value, pageNumber).then(results => {
const fragment = document.createDocumentFragment();
if (results !== undefined) {
results.map(film => {
renderFilms.push(film);
fragment.append(createCardFunc(film));
});
list.innerHTML = '';
list.append(fragment);
}
});
}
function fetchFilms(inputValue, pageNumber) {
return fetch(
`https://api.themoviedb.org/3/search/movie?api_key=56d683041d5d1a0178e72b4a2ffc8e86&language=en-US&page=${pageNumber}&query=${inputValue}`,
)
.then(res => res.json())
.then(result => {
if (result.results.length === 0) {
error.innerHTML = 'Nothing has been found :(';
} else {
error.innerHTML = '';
return result.results;
}
});
}
buttonBar.addEventListener('click', plaginationNavigation);
function plaginationNavigation(event) {
if (event.target.dataset.id === 'prev' && pageNumber !== 1) {
pageNumber -= 1;
barSpan.innerHTML = pageNumber;
if (pageNumber === 1)
event.target.classList.remove('switching-bar_btn__active');
}
if (event.target.dataset.id === 'next') {
pageNumber += 1;
barSpan.innerHTML = pageNumber;
if (pageNumber === 2) {
buttonBar.firstChild.classList.add('switching-bar_btn__active');
}
}
if (inputValue.value === '') {
fetchPopularMoviesList();
} else {
searchFilms();
}
}
<file_sep>'use strict';
var renderFilms = [];
var genres = [];
var pageNumber = 1;
var list = document.querySelector('.cards__container');
function createCardFunc(_ref) {
var backdrop_path = _ref.backdrop_path,
title = _ref.title,
id = _ref.id,
vote_average = _ref.vote_average;
var li = document.createElement('li');
li.className = 'card__container';
var divMark = document.createElement('div');
divMark.className = 'card__mark';
divMark.innerHTML = vote_average !== 0 ? vote_average : '--';
var divTitle = document.createElement('div');
divTitle.className = 'card__title';
divTitle.innerHTML = title;
var img = document.createElement('img');
img.className = 'card__img';
var imgSrc = backdrop_path !== null ? "https://image.tmdb.org/t/p/w500/".concat(backdrop_path) : "https://image.tmdb.org/t/p/w500//gkuyOdCeuKLdOlwQIUF44SHsYCq.jpg";
img.setAttribute('src', imgSrc);
img.setAttribute('alt', title);
li.append(divMark, divTitle, img);
list.appendChild(li);
li.addEventListener('click', function () {
return activeDetailsPage(id, false);
});
return li;
}
function fetchPopularMoviesList() {
var fragment = document.createDocumentFragment();
fetch("https://api.themoviedb.org/3/movie/popular?api_key=56d683041d5d1a0178e72b4a2ffc8e86&language=en-US&page=".concat(pageNumber)).then(function (res) {
return res.json();
}).then(function (data) {
return data.results;
}).then(function (res) {
res.map(function (film) {
renderFilms.push(film);
fragment.append(createCardFunc(film));
});
list.innerHTML = '';
list.append(fragment);
});
}
function fetchGenres() {
fetch("https://api.themoviedb.org/3/genre/movie/list?api_key=56d683041d5d1a0178e72b4a2ffc8e86&language=en-US").then(function (res) {
return res.json();
}).then(function (data) {
return data.genres;
}).then(function (res) {
res.map(function (film) {
genres.push(film);
});
});
}
fetchPopularMoviesList();
fetchGenres();
"use strict";
var inputValue = document.querySelector('.card__search_input');
var form = document.querySelector('#js-form');
var error = document.querySelector('.error');
var buttonBar = document.querySelector('.switching-bar_content');
var buttonBarPrev = document.querySelector('.switching-bar_prev');
var barSpan = document.querySelector('.switching-bar_span');
form.addEventListener('submit', hundleSubmit);
function hundleSubmit(evt) {
evt.preventDefault();
searchFilms();
}
function searchFilms() {
fetchFilms(inputValue.value, pageNumber).then(function (results) {
var fragment = document.createDocumentFragment();
if (results !== undefined) {
results.map(function (film) {
renderFilms.push(film);
fragment.append(createCardFunc(film));
});
list.innerHTML = '';
list.append(fragment);
}
});
}
function fetchFilms(inputValue, pageNumber) {
return fetch("https://api.themoviedb.org/3/search/movie?api_key=56d683041d5d1a0178e72b4a2ffc8e86&language=en-US&page=".concat(pageNumber, "&query=").concat(inputValue)).then(function (res) {
return res.json();
}).then(function (result) {
if (result.results.length === 0) {
error.innerHTML = 'Nothing has been found :(';
} else {
error.innerHTML = '';
return result.results;
}
});
}
buttonBar.addEventListener('click', plaginationNavigation);
function plaginationNavigation(event) {
if (event.target.dataset.id === 'prev' && pageNumber !== 1) {
pageNumber -= 1;
barSpan.innerHTML = pageNumber;
if (pageNumber === 1) event.target.classList.remove('switching-bar_btn__active');
}
if (event.target.dataset.id === 'next') {
pageNumber += 1;
barSpan.innerHTML = pageNumber;
if (pageNumber === 2) {
buttonBar.firstChild.classList.add('switching-bar_btn__active');
}
}
if (inputValue.value === '') {
fetchPopularMoviesList();
} else {
searchFilms();
}
}
"use strict";
var homeBtn = document.querySelector('.nav__home');
var myLibraryBtn = document.querySelector('.nav__library');
var myLibrary = document.querySelector('.js-library-page');
var detailsPage = document.querySelector('.js-details-page');
var homePage = document.querySelector('.js-home-page');
var headerLogo = document.querySelector('.header__logo');
var card = document.querySelector('.card__container');
homeBtn.addEventListener('click', activeHomePage);
myLibraryBtn.addEventListener('click', activeLibraryPage);
headerLogo.addEventListener('click', activeHomePage);
activeHomePage();
function activeLibraryPage() {
homePage.classList.add('visually-hidden');
myLibrary.classList.remove('visually-hidden');
detailsPage.classList.add('visually-hidden');
}
function activeHomePage() {
homePage.classList.remove('visually-hidden');
myLibrary.classList.add('visually-hidden');
detailsPage.classList.add('visually-hidden');
}
function activeDetailsPage(id, isHome) {
homePage.classList.add('visually-hidden');
myLibrary.classList.add('visually-hidden');
detailsPage.classList.remove('visually-hidden');
renderDetailsPage(id, isHome);
}
"use strict";
var detailsTitle = document.querySelector('.details__title');
var detailsVote = document.querySelector('.content-table__col2__row1');
var detailsPopularity = document.querySelector('.content-table__col2__row2');
var detailsOriginalTitle = document.querySelector('.content-table__col2__row3');
var detailsGenre = document.querySelector('.content-table__col2__row4');
var detailsAbout = document.querySelector('.details_about');
var btnAddWatched = document.querySelector('.btn-list-item-1');
var btnAddQueue = document.querySelector('.btn-list-item-2');
var detailsImg = document.querySelector('.img-wrapper');
var hundleClickChangeWatched;
btnAddWatched.addEventListener('click', function (evt) {
return hundleClickChangeWatched(evt);
}); //add listener only once
var hundleClickChangeQueue;
btnAddQueue.addEventListener('click', function (evt) {
return hundleClickChangeQueue(evt);
});
function renderDetailsPage(id, isHome) {
var currentFilm;
if (isHome) {//якщо переходимо з "бібліотекти" -+ дані беремо з локалСтор (ред.)
//lockStor
} else {
renderFilms.forEach(function (film) {
if (film.id === id) {
currentFilm = film;
}
});
detailsTitle.innerHTML = currentFilm.title;
detailsVote.innerHTML = currentFilm.vote_average;
detailsPopularity.innerHTML = currentFilm.popularity;
detailsOriginalTitle.innerHTML = currentFilm.original_title; // detailsGenre.innerHTML = 'some genre';
detailsAbout.innerHTML = currentFilm.overview;
detailsImg.firstChild.setAttribute('src', "https://image.tmdb.org/t/p/w500/".concat(currentFilm.poster_path));
}
var watched = localStorage.getItem('watched') ? JSON.parse(localStorage.getItem('watched')) : []; //запишемо дані з лок.стор в змінну
if (watched.lenght === 0) {
btnAddWatched.firstChild.setAttribute('src', 'images/icon/video.png');
btnAddWatched.lastChild.innerHTML = 'Add to watched';
} else if (watched.find(function (film) {
return film.id === id;
})) {
btnAddWatched.lastChild.innerHTML = 'Remove from watched';
btnAddWatched.firstChild.setAttribute('src', 'images/icon/trash.png');
} else {
btnAddWatched.firstChild.setAttribute('src', 'images/icon/video.png');
btnAddWatched.lastChild.innerHTML = 'Add to watched';
}
hundleClickChangeWatched = function hundleClickChangeWatched(evt) {
if (evt.target.innerHTML === 'Add to watched') {
watched.unshift(currentFilm);
btnAddWatched.lastChild.innerHTML = 'Remove from watched';
btnAddWatched.firstChild.setAttribute('src', 'images/icon/trash.png');
} else {
watched.pop(currentFilm);
btnAddWatched.lastChild.innerHTML = 'Add to watched';
btnAddWatched.firstChild.setAttribute('src', 'images/icon/video.png');
}
localStorage.setItem('watched', JSON.stringify(watched));
};
var queue = localStorage.getItem('queue') ? JSON.parse(localStorage.getItem('queue')) : []; //запишемо дані з лок.стор в змінну
if (queue.lenght === 0) {
//перевірка при завантажені чи є фільм в "черзі"
btnAddQueue.firstChild.setAttribute('src', 'images/icon/calendar-plus.png');
btnAddQueue.lastChild.innerHTML = 'Add to queue';
} else if (queue.find(function (film) {
return film.id === id;
})) {
btnAddQueue.lastChild.innerHTML = 'Remove from queue';
btnAddQueue.firstChild.setAttribute('src', 'images/icon/calendar-minus.png');
} else {
btnAddQueue.firstChild.setAttribute('src', 'images/icon/calendar-plus.png');
btnAddQueue.lastChild.innerHTML = 'Add to queue';
}
hundleClickChangeQueue = function hundleClickChangeQueue(evt) {
if (evt.target.innerHTML === 'Add to queue') {
queue.unshift(currentFilm);
evt.target.innerHTML = 'Remove from queue';
btnAddQueue.firstChild.setAttribute('src', 'images/icon/calendar-minus.png');
} else {
queue.pop(currentFilm);
evt.target.innerHTML = 'Add to queue';
btnAddQueue.firstChild.setAttribute('src', 'images/icon/calendar-plus.png');
}
localStorage.setItem('queue', JSON.stringify(queue));
};
}
"use strict";
var libraryCards = document.querySelector('.cards__wrapper');
var createCardLibrary = function createCardLibrary(_ref) {
var backdrop_path = _ref.backdrop_path,
title = _ref.title,
id = _ref.id,
vote_average = _ref.vote_average;
var li = document.createElement('li');
li.className = 'card__container';
var divMark = document.createElement('div');
divMark.className = 'card__mark';
divMark.innerHTML = vote_average !== 0 ? vote_average : '--';
var divTitle = document.createElement('div');
divTitle.className = 'card__title';
divTitle.innerHTML = title;
var img = document.createElement('img');
img.className = 'card__img';
var imgSrc = backdrop_path !== null ? "https://image.tmdb.org/t/p/w500/".concat(backdrop_path) : "https://image.tmdb.org/t/p/w500//gkuyOdCeuKLdOlwQIUF44SHsYCq.jpg";
img.setAttribute('src', imgSrc);
img.setAttribute('alt', title);
li.append(divMark, divTitle, img);
libraryCards.appendChild(li);
li.addEventListener('click', function () {
return activeDetailsPage(id, false);
});
};
var librarySpinWatchd = document.querySelector('.library__spin__list-item-watched');
var librarySpinQueue = document.querySelector('.library__spin__list-item-queue');
var libraryCardsWatched = localStorage.getItem('watched') ? JSON.parse(localStorage.getItem('watched')) : []; //запишемо дані з лок.стор в змінну
if (libraryCardsWatched.length == 0) {
libraryCards.innerHTML = 'Your movies for watching will be here ';
} else {
libraryCardsWatched.forEach(function (film) {
createCardLibrary(film);
});
}
librarySpinWatchd.addEventListener('click', function () {
libraryCardsWatched = localStorage.getItem('watched') ? JSON.parse(localStorage.getItem('watched')) : [];
if (libraryCardsWatched.length === 0) {
libraryCards.innerHTML = 'Your movies for watching will be here ';
} else {
libraryCards.innerHTML = '';
libraryCardsWatched.forEach(function (film) {
createCardLibrary(film);
});
}
librarySpinWatchd.classList.add('library__spin__list-item-active');
librarySpinQueue.classList.remove('library__spin__list-item-active');
});
librarySpinQueue.addEventListener('click', function () {
var libraryCardsQueue = localStorage.getItem('queue') ? JSON.parse(localStorage.getItem('queue')) : [];
if (libraryCardsQueue.length === 0) {
libraryCards.innerHTML = 'Your movies in queue will be here';
} else {
libraryCards.innerHTML = '';
libraryCardsQueue.forEach(function (film) {
createCardLibrary(film);
});
}
librarySpinQueue.classList.add('library__spin__list-item-active');
librarySpinWatchd.classList.remove('library__spin__list-item-active');
}); | cf7c94ed7af1caa76b60fc26f1c7c4889405d27a | [
"JavaScript"
] | 5 | JavaScript | Aleksey67/filmoteka | 465d0938799b7d12cd5cd78d0877325d2586fc8a | 8664baefbb48f44a676d2fd1ef55b6d187aa8b98 |
refs/heads/master | <file_sep>const Bicicleta = function (id, color, modelo, ubicacion) {
this.id = id;
this.color = color;
this.modelo = modelo;
this.ubicacion = ubicacion;
};
Bicicleta.prototype.toString = function () {
return "id: " + this.id + "| color: " + this.color;
};
Bicicleta.allBicis = [];
Bicicleta.add = function (aBici) {
Bicicleta.allBicis.push(aBici);
};
Bicicleta.findById = function (aBiciId) {
var aBici = Bicicleta.allBicis.find((x) => x.id === aBiciId);
if (aBici) {
return aBici;
} else {
throw new Error(`No existe la bicicleta de id ${biciId}`);
}
};
Bicicleta.removeById = function (aBiciId) {
/* var bici = Bicicleta.findById(biciId); */
for (let i = 0; i < Bicicleta.allBicis.length; i++) {
if (Bicicleta.allBicis[i].id === aBiciId) {
Bicicleta.allBicis.splice(i, 1);
break;
}
}
};
const bici1 = new Bicicleta("1", "Rojo", "Urbana", [4.633159, -74.194198]);
const bici2 = new Bicicleta("2", "Verde", "Urbana", [4.62643, -74.20817]);
const bici3 = new Bicicleta("3", "Verde", "Urbana", [4.632391, -74.199419]);
Bicicleta.add(bici1);
Bicicleta.add(bici2);
Bicicleta.add(bici3);
module.exports = Bicicleta;
| 49641f20c463e2331e189fd32798a274f9baf14a | [
"JavaScript"
] | 1 | JavaScript | milfer0516/Red-Bicicletas | 211ce34dba10dfc1e121ffa8842d63279291c6f3 | 391e42da474e605d2e636c68a5ce1e4003e31d31 |
refs/heads/master | <file_sep>package com.nisum.demo.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.nisum.demo.domain.Customer;
public interface CustomerFinder extends CrudRepository<Customer, Long>{
Customer findByLastName(String lastName);
}
<file_sep>/*package com.nisum.service;
import java.util.List;
import com.nisum.model.Order;
import com.nisum.model.Product;
public interface ProductService {
List<Product> listAll();
public List<Product> saveAll(List<Product> product) ;
Product getById(String productId);
Product create(Product product);
Product delete(String productId);
Product updateProduct(String productId, Product product);
}
*/<file_sep>/*package com.nisum.service;
import java.util.List;
import com.nisum.model.Order;
public interface OrderService {
List<Order> listAll();
Order getById(String orderID);
Order create(Order order);
Order delete(String orderID);
Order updateOrder(String orderId, Order order);
}
*/<file_sep>/*package com.nisum.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nisum.model.Order;
import com.nisum.model.Product;
import com.nisum.service.OrderService;
import com.nisum.service.ProductService;
@RestController
@RequestMapping("/api/order")
public class OrderController {
@Autowired
private OrderService orderService;
//creates
@RequestMapping(value="/createOrder",method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public void createOrder(@RequestBody Order order)
{
orderService.create(order);
}
//read
@RequestMapping
public List<Order> readOrders()
{
return orderService.listAll();
}
//update
@RequestMapping( value="/{orderId}",method=RequestMethod.GET)
public ResponseEntity<List<Order>> updateOrders(@PathVariable String orderId)
{
try {
System.err.println(""+new ObjectMapper().writeValueAsString(orderService.listAll()));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return new ResponseEntity<List<Order>>(orderService.listAll(),HttpStatus.OK);
}
//update order
@RequestMapping(value="/{orderId}",method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Order> updateOrder(@PathVariable String orderId,@RequestBody Order order)
{
order= orderService.getById(orderId);
if(order==null)
{
return ResponseEntity.notFound().build();
}
orderService.updateOrder(orderId, order);
return ResponseEntity.ok(order);
}
//delete
@RequestMapping(value="{orderId}",method=RequestMethod.DELETE)
public ResponseEntity<Order> deleteOrder(@PathVariable String orderId)
{
Order order= orderService.delete(orderId);
if(order==null)
{
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().build();
}
}
*/<file_sep>package com.nisum.service;
import java.util.List;
import com.nisum.model.Customer;
public interface CustomerService {
List<Customer> listAll();
Customer getById(String customerID);
Customer create(Customer customer);
void delete(String customerId);
Customer updateCustomer(String customerId, Customer customer);
}
<file_sep>package com.nisum.soap.topdown;
import javax.jws.WebService;
import com.baeldung.jaxws.server.topdown.EmployeeServiceTopDown;
@WebService
public class EmployeeServiceTopDownImpl implements EmployeeServiceTopDown{
public int countEmployees() {
return 1;
}
}
<file_sep>package com.nisum.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nisum.demo.dao.CustomerFinder;
import com.nisum.demo.domain.Customer;
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
CustomerFinder dao;
@Override
public Customer addCustomer(Customer customer) {
// TODO Auto-generated method stub
return dao.save(customer);
}
@Override
public Customer updateCustomer(Customer customer) {
return dao.save(customer);
}
@Override
public Customer getCustomer(long id) {
return dao.findOne(id);
}
@Override
public List<Customer> getCustomers() {
return (List<Customer>) dao.findAll();
}
@Override
public void deleteCustomer(long id) {
// TODO Auto-generated method stub
dao.delete(id);
}
}
<file_sep>package cass.domain;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
import java.io.Serializable;
import java.util.UUID;
@Table("hotels")
public class Hotel implements Serializable {
private static final long serialVersionUID = 1L;
@PrimaryKey
private UUID id;
private String name;
private String address;
private String state;
private String zip;
public Hotel() {
}
public Hotel(String name) {
this.name = name;
}
public UUID getId() {
return id;
}
public String getName() {
return this.name;
}
public String getAddress() {
return this.address;
}
public String getZip() {
return this.zip;
}
public void setId(UUID id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}<file_sep>/*package com.nisum.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nisum.model.Order;
import com.nisum.model.Product;
import com.nisum.repository.OrderRepository;
@Service
public class OrderServiceImpl implements OrderService{
@Autowired
private OrderRepository orderRepository;
@Override
public List<Order> listAll() {
List<Order> orderList=new ArrayList<>();
orderRepository.findAll().forEach(orderList::add);
return orderList;
}
@Override
public Order getById(String orderID) {
return orderRepository.findOne(orderID);
}
@Override
public Order create(Order order) {
orderRepository.save(order);
return order;
}
@Override
public Order delete(String orderID) {
return orderRepository.findOne(orderID);
}
@Override
public Order updateOrder(String orderId, Order order) {
Order order2= orderRepository.findOne(orderId);
//order2.setCustomerId(order.getCustomerId());
order2.setOrderDate(order.getOrderDate());
order2.setOrderId(order.getOrderId());
order2.setProduct(order.getProduct());
orderRepository.save(order2);
return order2;
}
}
*/<file_sep>package com.nisum.demo.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.nisum.demo.domain.Customer;
import com.nisum.demo.service.CustomerService;
@Controller
public class CustomerController {
@Autowired
CustomerService service;
@RequestMapping(value="/home", method=RequestMethod.GET)
public String getHome() {
System.out.println("Home");
return "home";
}
@RequestMapping(value="/addCustomer", method=RequestMethod.POST)
public ModelAndView addCustomer(@ModelAttribute Customer customer) {
Customer c = service.addCustomer(customer);
ModelAndView mav = new ModelAndView();
mav.setViewName("custDetails");
mav.addObject(c);
return mav;
}
@RequestMapping(value="/addCustomerForm", method=RequestMethod.GET)
public ModelAndView addCustomerForm() {
Customer c = new Customer();
ModelAndView mav = new ModelAndView();
mav.addObject(c);
mav.setViewName("addCustomerForm");
return mav;
}
@RequestMapping(value="/updateCustomerForm", method=RequestMethod.GET)
public ModelAndView updateCustomerForm(HttpServletRequest request, HttpServletResponse response) {
Customer c = new Customer();
c.setId(Long.parseLong(request.getParameter("id")));
c.setFirstName(request.getParameter("firstName"));
c.setLastName(request.getParameter("lastName"));
ModelAndView mav = new ModelAndView();
mav.addObject(c);
mav.setViewName("updateCustomerForm");
return mav;
}
@RequestMapping(value="/updateCustomer", method=RequestMethod.POST)
public ModelAndView updateCustomer(@ModelAttribute Customer customer) {
Customer c = service.updateCustomer(customer);
ModelAndView mav = new ModelAndView();
mav.setViewName("custDetails");
mav.addObject(c);
return mav;
}
@RequestMapping(value="/getCustomers", method=RequestMethod.GET)
public ModelAndView getCustomers() {
ModelAndView mav = new ModelAndView();
List<Customer> customers = service.getCustomers();
mav.addObject("customers",customers);
mav.setViewName("customersList");
return mav;
}
@RequestMapping(value="/deleteCustomer", method=RequestMethod.GET)
public ModelAndView deleteCustomer(@RequestParam("id") long id) {
service.deleteCustomer(id);
return getCustomers();
}
}
<file_sep>package com.nisum.demo.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.nisum.demo.domain.Customer;
@Repository
public class SomeCustomerFinder implements CustomerFinder {
@Autowired
private JdbcTemplate jdbcTemplate;
//Querying and populating a single domain object:
public Customer getCustomer(long id) {
Customer customer = jdbcTemplate.queryForObject(
"select firstName, lastName from customerdb where id = ?",
new Object[]{id},
new RowMapper<Customer>() {
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setFirstName(rs.getString("firstName"));
customer.setLastName(rs.getString("lastName"));
return customer;
}
});
return customer;
}
//Querying and populating a number of domain objects:
public List<Customer> getCustomers() {
List<Customer> customers = jdbcTemplate.query(
"select id, firstName, lastName from customerdb",
new RowMapper<Customer>() {
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setId(Long.parseLong(rs.getString("id")));
customer.setFirstName(rs.getString("firstName"));
customer.setLastName(rs.getString("lastName"));
return customer;
}
});
return customers;
}
//If the last two snippets of code actually existed in the same application,
//it would make sense to extract them out into a single class.
public List<Customer> findAllCustomers() {
return this.jdbcTemplate.query( "select firstName, lastName from customerdb", new CustomerMapper());
}
private static final class CustomerMapper implements RowMapper<Customer> {
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setId(Long.parseLong(rs.getString("id")));
customer.setFirstName(rs.getString("firstName"));
customer.setLastName(rs.getString("lastName"));
return customer;
}
}
//inserting with JdbcTemplate
public Customer insertCustomer(Customer customer) {
jdbcTemplate.update(
"insert into customerdb (id, firstName, lastName) values (?, ?, ?)", customer.getId(),customer.getFirstName(), customer.getLastName());
return customer;
}
//updating with JdbcTemplate
public Customer updateCustomer(Customer customer) {
jdbcTemplate.update(
"update customerdb set firstName=?,lastName = ? where id = ?",
customer.getFirstName(), customer.getLastName(), customer.getId());
return customer;
}
//deleting with JdbcTemplate
public void deleteCustomer(long id) {
jdbcTemplate.update("delete from customerdb where id = ?",Long.valueOf(id));
}
}
<file_sep>package cass.web;
import cass.domain.Hotel;
import cass.domain.HotelByLetter;
import cass.service.HotelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/hotels")
public class HotelController {
private final HotelService hotelService;
@Autowired
public HotelController(HotelService hotelService) {
this.hotelService = hotelService;
}
@GetMapping(path = "/{id}")
public Hotel get(@PathVariable("id") UUID uuid) {
return this.hotelService.findOne(uuid);
}
@PostMapping
public ResponseEntity<Hotel> save(@RequestBody Hotel hotel) {
Hotel savedHotel = this.hotelService.save(hotel);
return new ResponseEntity<>(savedHotel, HttpStatus.CREATED);
}
@PutMapping
public ResponseEntity<Hotel> update(@RequestBody Hotel hotel) {
Hotel savedHotel = this.hotelService.update(hotel);
return new ResponseEntity<>(savedHotel, HttpStatus.CREATED);
}
@DeleteMapping(path = "/{id}")
public ResponseEntity<String> delete(@PathVariable("id") UUID uuid) {
this.hotelService.delete(uuid);
return new ResponseEntity<>("Deleted", HttpStatus.ACCEPTED);
}
@GetMapping(path = "/startingwith/{letter}")
public List<HotelByLetter> findHotelsWithLetter(@PathVariable("letter") String letter) {
return this.hotelService.findHotelsStartingWith(letter);
}
@GetMapping(path = "/fromstate/{state}")
public List<Hotel> findHotelsInState(@PathVariable("state") String state) {
return this.hotelService.findHotelsInState(state);
}
}
<file_sep>/*package com.nisum.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.model.Product;
import com.nisum.service.ProductService;
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
//creates
@RequestMapping(method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public void createProduct(@RequestBody Product product)
{
productService.create(product);
}
//read
@RequestMapping
public List<Product> readProducts()
{
return productService.listAll();
}
//update
@RequestMapping( value="{productId}",method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE)
public Product updateProduct(@PathVariable String productId ,@RequestBody Product product)
{
return productService.updateProduct(productId, product);
}
//delete
@RequestMapping(value="{productId}",method=RequestMethod.DELETE)
public void deleteProduct(@PathVariable String productId)
{
productService.delete(productId);
}
}
*/<file_sep>package com.nisum.demo.service;
import java.util.List;
import com.nisum.demo.domain.Customer;
public interface CustomerService {
Customer addCustomer(Customer customer);
Customer updateCustomer(Customer customer);
Customer getCustomer(long id);
List<Customer> getCustomers();
void deleteCustomer(long id);
}<file_sep>cassandra.contactpoints=127.0.0.1
cassandra.port=9042
cassandra.keyspace=keyspace1
<file_sep>package com.nisum.demo.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.nisum.demo.domain.Customer;
@Repository
public class SomeCustomerFinder implements CustomerFinder {
@Autowired
private SessionFactory sf;
//Querying and populating a single domain object:
public Customer getCustomer(long id) {
Session session = sf.openSession();
return (Customer) session.get(Customer.class, id);
}
//Querying and populating a number of domain objects:
@SuppressWarnings("unchecked")
public List<Customer> getCustomers() {
Session session = sf.openSession();
return session.createQuery("from Customer").list();
}
//inserting with Hibernate
public Customer insertCustomer(Customer customer) {
Session session = sf.openSession();
session.save(customer);
return customer;
}
//updating with with Hibernate
public Customer updateCustomer(Customer customer) {
System.out.println("id " + customer.getId() + " first name " + customer.getFirstName() + " last name " + customer.getLastName());
Session session = sf.openSession();
String sql = "update Customer set firstName=:firstName, lastName=:lastName where id=:id";
Query q = session.createQuery(sql).setParameter("firstName",customer.getFirstName()).setParameter("lastName", customer.getLastName()).setParameter("id", customer.getId());
q.executeUpdate();
return customer;
}
//deleting with Hibernate
public void deleteCustomer(long id) {
Session session = sf.openSession();
String sql = "delete from Customer where id=:id";
Query q = session.createQuery(sql).setParameter("id", id);
q.executeUpdate();
}
}
<file_sep>#Sun Nov 26 17:22:00 PST 2017
org.eclipse.core.runtime=2
org.eclipse.platform=4.7.0.v20170612-0950
<file_sep>package cass.repository;
import cass.domain.HotelByLetter;
import cass.domain.HotelByLetterKey;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import org.springframework.cassandra.core.CqlTemplate;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class CassandraHotelByLetterRepository implements HotelByLetterRepository {
private final CassandraTemplate cassandraTemplate;
public CassandraHotelByLetterRepository(CassandraTemplate cassandraTemplate) {
this.cassandraTemplate = cassandraTemplate;
}
@Override
public List<HotelByLetter> findByFirstLetter(String letter) {
Select select = QueryBuilder.select().from("hotels_by_letter");
select.where(QueryBuilder.eq("first_letter", letter));
return this.cassandraTemplate.select(select, HotelByLetter.class);
}
@Override
public HotelByLetter save(HotelByLetter hotelByLetter) {
return this.cassandraTemplate.insert(hotelByLetter);
}
@Override
public void delete(HotelByLetterKey hotelByLetterKey) {
this.cassandraTemplate.deleteById(HotelByLetter.class, hotelByLetterKey);
}
}
| db267cef832747e6b5e856f023be067ae5155c96 | [
"Java",
"INI"
] | 18 | Java | sravanAruru/POCS | 278629c293ff2c64468a2bd34729424981aea8ee | 5b53c1b673b5a12d7e323cb5f9b880c6d63750d9 |
refs/heads/main | <repo_name>vitaliybeinspired/react-data-visualizer<file_sep>/server/routes/queries.js
const express = require('express');
const router = express.Router();
const {
CostaRica, Nicaragua,
ElSalvador, Mexico
} = require('../controllers/queries');
router.route("/CostaRica").post(CostaRica);
router.route("/ElSalvador").post(ElSalvador);
router.route("/Nicaragua").post(Nicaragua);
router.route("/Mexico").post(Mexico);
module.exports = router;<file_sep>/client/src/components/Sidebar.js
import {Menu, MenuItem, ProSidebar} from "react-pro-sidebar";
import {VscUnmute, VscMute} from "react-icons/vsc"
import {MdDashboard} from 'react-icons/md'
import React from "react";
import DateTimePicker from '../components/DateTimePicker'
import Plot from './Plot';
import Accuracy from './Accuracy'
import ReactCountryFlag from "react-country-flag"
import './Sidebar.css';
const country_code = {
"Costa Rica" : "CR",
"El Salvador": "SV",
"Mexico" : "MX",
"Nicaragua" : "NI"
}
export default class SideBar extends React.Component {
constructor(props){
super(props)
this.state = {
loading: true,
updating: false,
}
this.changeEndDate = this.changeEndDate.bind(this)
this.changeStartDate = this.changeStartDate.bind(this)
this.updateLoading = this.updateLoading.bind(this)
this.updateCompleted = this.updateCompleted.bind(this)
}
changeStartDate(date){
this.props.changeStartDate(date, this.updateLoading)
}
changeEndDate(date){
this.props.changeEndDate(date, this.updateLoading);
}
updateLoading(){
this.setState({updating: true})
}
updateCompleted(){
this.setState({updating: false})
}
render() {
if(this.state.loading !== this.props.loading){
this.setState({loading: this.props.loading})
}
return (
<ProSidebar collapsed={this.props.collapsed}>
<Menu iconShape="circle">
<MenuItem
onClick={this.props.toggleCollapseHandle}
icon={
this.props.country === "none" ?
<MdDashboard/>
:
<ReactCountryFlag
className="emojiFlag"
countryCode={country_code[this.props.country]}
svg
style={{
width: '2em',
height: '2em',
borderRadius: "1em"
}}/>
}
style={{textTransform: "uppercase",fontSize: "40px", fontWeight: 400}}
>
{
this.props.country === "none" ?
"Click on a country!"
:
this.props.country
}
</MenuItem>
{this.props.collapsed || this.props.country === "none" ?
null :
<div className="dashboard-container">
{DateTimePicker(this.props.start, this.props.end, this.changeStartDate, this.changeEndDate)}
<Plot
loading={this.state.loading}
country={this.props.country}
startDate={this.props.start}
endDate={this.props.end}
data={this.props.hist}
title={"Historical Data"}
updating={this.state.updating}
updateCallback={this.updateCompleted}
/>
<Plot
loading={this.state.loading}
country={this.props.country}
startDate={this.props.start}
endDate={this.props.end}
data={this.props.frcst}
title={"Forecasted Data"}
updating={this.state.updating}
updateCallback={this.updateCompleted}
/>
<Accuracy loading={this.props.loading} startDate={this.props.start} endDate={this.props.end} hist={this.props.hist} frcst={this.props.frcst}/>
</div>
}
{this.props.muted ?
<MenuItem onClick={this.props.muteHandler} icon={<VscMute/>}>
unmute
</MenuItem>
:
<MenuItem onClick={this.props.muteHandler} icon={<VscUnmute/>}>
mute
</MenuItem>
}
</Menu>
</ProSidebar>
)
}
}
<file_sep>/client/src/components/Globe.js
import React from 'react';
import ReactGlobe from 'react-globe';
// import logo from '../images/logo.png';
/* IMPORTANT
it is worth noting that this demo only works with Three.js 0.118 thru 0.124
There is a regex Dos (ReDos) vulnerability https://www.npmjs.com/advisories/1639 fixed in 0.125
soooo TL;DR don't let the user pick colors of the globe and we should be okay.
*/
export const markers = [
{
id: 'ElSalvador',
country: 'El Salvador',
color: 'yellow',
coordinates: [13.598871, -88.909731],
value: 20,
},
{
id: 'Nicaragua',
country: 'Nicaragua',
color: 'yellow',
coordinates: [12.793830, -84.854074],
value: 10,
},
{
id: 'Mexico',
country: 'Mexico',
color: 'yellow',
coordinates: [23.502654, -102.227797],
value: 80,
},
{
id: 'CostaRica',
country: 'Costa Rica',
color: 'yellow',
coordinates: [10.031846, -83.896692],
value: 40,
}
];
const options = {
ambientLightColor: 'white',
ambientLightIntensity: 0.15,
enableDefocus: true,
cameraRotateSpeed: 0.25,
cameraZoomSpeed: 1.5,
cameraAutoRotateSpeed: 0.025,
focusAnimationDuration: 1750,
focusEasingFunction: ['Quintic', 'InOut'],
globeGlowPower: 5,
enableMarkerGlow: true,
markerEnterAnimationDuration: 0.4,
markerGlowCoefficient: 0.5,
markerGlowPower: 1.2,
pointLightColor: 'white',
pointLightIntensity: 1.0,
pointLightPositionRadiusScales: [-1500, 500, 1500],
markerType: 'dot',
markerTooltipRenderer: marker => `${marker.country}`,
};
export class Globe extends React.Component {
getGlobe() {
return (
<ReactGlobe
initialCameraDistanceRadiusScale="3.25"
//TODO we should download and copy these for our server to use
globeBackgroundTexture="https://raw.githubusercontent.com/chrisrzhou/react-globe/main/textures/background.png"
globeCloudsTexture="https://raw.githubusercontent.com/chrisrzhou/react-globe/main/textures/clouds.png"
globeTexture="https://raw.githubusercontent.com/chrisrzhou/react-globe/main/textures/globe.jpg"
initialCoordinates={[17.4921, -84.0852]}
markers={markers}
options={options}
onClickMarker={this.props.markerClick}
onDefocus={this.props.defocusHandler}
// onGetGlobe={(globe) => this.setState({globe: globe})}
// onMouseOutMarker={(marker, markerObject, event) => console.log(marker, markerObject, event)}
onGlobeTextureLoaded={() => console.log('globe loaded')}
// onMouseOverMarker={(marker, markerObject, event) => console.log(marker, markerObject, event)}
/>
)
}
}<file_sep>/client/src/components/DateToWeek.js
const start_date = "12/27/2016"
/**
* Converts **en-US mm/dd/yyyy** date to needed doc ID
* @param {*} date_str
*/
module.exports.date_to_weekUS = (date_str) => {
const start = new Date(start_date);
const current = new Date(date_str);
const diffTime = Math.abs(current - start);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) % 7;
current.setDate(current.getDate() - diffDays);
var year = Intl.DateTimeFormat('en', {year: 'numeric'}).format(current);
var month = Intl.DateTimeFormat('en', {month: '2-digit'}).format(current);
var day = Intl.DateTimeFormat('en', {day: '2-digit'}).format(current);
return `${day}/${month}/${year}`
}
/**
* Converts **JS date object** to needed doc ID
* @param {*} date
*/
module.exports.date_to_weekJS = (date) => {
const start = new Date(start_date);
const current = new Date(date);
const diffTime = Math.abs(current - start);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) % 7;
current.setDate(current.getDate() - diffDays);
var year = Intl.DateTimeFormat('en', {year: 'numeric'}).format(current);
var month = Intl.DateTimeFormat('en', {month: '2-digit'}).format(current);
var day = Intl.DateTimeFormat('en', {day: '2-digit'}).format(current);
return `${day}/${month}/${year}`
}
/**
* Converts **dd/mm/yyyy** date to needed doc ID
* @param {*} date_str
*/
module.exports.date_to_week = (date_str) => {
const start = new Date(start_date);
const dateParts = date_str.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
const current = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
const diffTime = Math.abs(current - start);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) % 7;
current.setDate(current.getDate() - diffDays);
var year = Intl.DateTimeFormat('en', {year: 'numeric'}).format(current);
var month = Intl.DateTimeFormat('en', {month: '2-digit'}).format(current);
var day = Intl.DateTimeFormat('en', {day: '2-digit'}).format(current);
return `${day}/${month}/${year}`
}
module.exports.date_to_stringUS = (date) => {
try{
var dd = String(date.getDate()).padStart(2, '0');
var mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = date.getFullYear();
return (mm + '/' + dd + '/' + yyyy);
}catch (err){
console.log(err)
return null
}
}
module.exports.date_to_string = (date) => {
try{
var dd = String(date.getDate()).padStart(2, '0');
var mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = date.getFullYear();
return (dd + '/' + mm + '/' + yyyy);
}catch (err){
console.log(err)
return null
}
}
/**
* Simple helper to turn our 'hh-dd/mm/yyyy' formated date strings
* into date objects
*
* @param {*} string
* @returns
*/
module.exports.str_to_date = (string) => {
let split = string.split('-');
var hh = parseInt(split[0]);
var date_str = split[1];
var date_split = date_str.split('/');
var dd = parseInt(date_split[0]);
var mm = parseInt(date_split[1] - 1);
var yyyy = parseInt(date_split[2]);
return new Date(yyyy, mm, dd, hh)
}<file_sep>/client/src/components/DateTimePicker.js
import React from 'react'
import { enGB } from 'date-fns/locale'
import { DateRangePicker, START_DATE, END_DATE } from 'react-nice-dates'
import 'react-nice-dates/build/style.css'
/*Add this as props to not be able to select past days and only from current day
minimumDate={new Date()}
So we can click and drag or type or select date ranges.
Need hour filter?
*/
function DateRangePickerExample(startDate, endDate, changeStartDate, changeEndDate) {
return (
<div className="date-time-picker">
<DateRangePicker
startDate={startDate}
endDate={endDate}
onStartDateChange={(date) => changeStartDate(date )}
onEndDateChange={(date) => changeEndDate(date)}
minimumLength={1}
format='MMMMMMMMMM dd, yyyy'
locale={enGB}
>
{({ startDateInputProps, endDateInputProps, focus }) => (
<div className='date-range'>
<input
className={'input' + (focus === START_DATE ? ' -focused' : '')}
{...startDateInputProps}
placeholder='Start date'
/>
<span/>
<input
className={'input' + (focus === END_DATE ? ' -focused' : '')}
{...endDateInputProps}
placeholder='End date'
/>
</div>
)}
</DateRangePicker>
</div>
)
}
export default DateRangePickerExample<file_sep>/README.md
# THESE ARE THE ONLY CURRENT INSTRUCTIONS
To install simply run `npm install`
To run use `npm run dev`
or
Run the client and server seperately with:
- `npm run server`
- `npm run client`
<file_sep>/server/controllers/queries.js
const MongoClient = require('mongodb').MongoClient;
const {date_to_week, date_to_weekUS, date_to_weekJS, date_rangeUS} = require('../date_to_week');
// status codes:
// Informational responses (100–199)
// Successful responses (200–299)
// Redirects (300–399)
// Client errors (400–499)
// Server errors (500–599)
//Database UserName: REACT
//Database password: <PASSWORD>
const MONGODB_URI = 'mongodb+srv://REACT:<EMAIL>/myFirstDatabase?retryWrites=true&w=majority'
function getClient () {
return new MongoClient(MONGODB_URI, {
useUnifiedTopology: true,
connectTimeoutMS: 15000,
socketTimeoutMS: 15000,
})};
exports.CostaRica = async (req, res) => {
let client = getClient();
if(!client.isConnected()){
await client.connect();
}
try {
var h_entries = [];
var f_entries = [];
let cr_client = client.db("Costa_Rica");
let cr_historic = cr_client.collection("Historic");
let cr_forecast = cr_client.collection("Forecast");
//date range
if(req.body.date_range != null || req.body.date_range != undefined){
let weeks = date_rangeUS(req.body.date_range[0], req.body.date_range[1])
for(var i = 0; i < weeks.length; ++i){
let week = weeks[i];
let cr_h_cursor = cr_historic.find({"_id": week });
await cr_h_cursor.forEach(function(data) {h_entries.push(data)});
let cr_f_cursor = cr_forecast.find({"_id": week });
await cr_f_cursor.forEach(function(data) {f_entries.push(data)});
}
}
//single date selection
else{
let week = ""
if (req.body.dateUS != null || req.body.dateUS != undefined) {
week = date_to_weekUS(req.body.dateUS);
}
else if (req.body.date != null || req.body.date != undefined) {
week = date_to_week(req.body.date);
}
else if (req.body.dateJS != null || req.body.dateJS != undefined) {
week = date_to_weekJS(req.body.dateJS);
}
else{
res.status(400).json({err: "I need a valid date"})
return
}
let cr_h_cursor = cr_historic.find({"_id": week });
await cr_h_cursor.forEach(function(data) {h_entries.push(data)});
let cr_f_cursor = cr_forecast.find({"_id": week });
await cr_f_cursor.forEach(function(data) {f_entries.push(data)});
}
//clean-up
var h_output = {}
var f_output = {}
for (let index = 0; index < h_entries.length; ++index) {
delete h_entries[index]['_id']
h_output = Object.assign({}, h_output, h_entries[index]);
}
for (let index = 0; index < f_entries.length; ++index) {
delete f_entries[index]['_id']
f_output = Object.assign({}, f_output, f_entries[index]);
}
res.json({'Historic' : h_output, 'Forecast' : f_output})
res.status(200);
} catch (err) {
console.log(err);
res.status(500).json({err: err});
}
if(client.isConnected()){
client.close();
}
}
exports.Nicaragua = async (req, res) => {
let client = getClient();
if(!client.isConnected()){
await client.connect();
}
try {
var h_entries = [];
var f_entries = [];
const n_client = client.db("Nicaragua");
const n_historic = n_client.collection("Historic");
const n_forecast = n_client.collection("Forecast");
//date range
if(req.body.date_range != null || req.body.date_range != undefined){
let weeks = date_rangeUS(req.body.date_range[0], req.body.date_range[1])
for(var i = 0; i < weeks.length; ++i){
let week = weeks[i];
let n_h_cursor = n_historic.find({"_id": week });
await n_h_cursor.forEach(function(data) {h_entries.push(data)});
let n_f_cursor = n_forecast.find({"_id": week });
await n_f_cursor.forEach(function(data) {f_entries.push(data)});
}
}
//single date selection
else{
let week = ""
if (req.body.dateUS != null || req.body.dateUS != undefined) {
week = date_to_weekUS(req.body.dateUS);
}
else if (req.body.date != null || req.body.date != undefined) {
week = date_to_week(req.body.date);
}
else if (req.body.dateJS != null || req.body.dateJS != undefined) {
week = date_to_weekJS(req.body.dateJS);
}
else{
res.status(400).json({err: "I need a valid date"})
return
}
let n_h_cursor = n_historic.find({ "_id": week});
await n_h_cursor.forEach(function(data) {h_entries.push(data)});
let n_f_cursor = n_forecast.find({"_id": week });
await n_f_cursor.forEach(function(data) {f_entries.push(data)});
}
//clean-up
var h_output = {}
var f_output = {}
for (let index = 0; index < h_entries.length; ++index) {
delete h_entries[index]['_id']
h_output = Object.assign({}, h_output, h_entries[index]);
}
for (let index = 0; index < f_entries.length; ++index) {
delete f_entries[index]['_id']
f_output = Object.assign({}, f_output, f_entries[index]);
}
res.json({'Historic' : h_output, 'Forecast' : f_output})
res.status(200);
} catch (err) {
console.log(err);
res.status(500).json({err: err});
}
}
exports.ElSalvador = async (req, res) => {
let client = getClient();
if(!client.isConnected()){
await client.connect();
}
try {
var h_entries = [];
var f_entries = [];
const el_client = client.db("El_Salvador");
const el_historic = el_client.collection("Historic");
const el_forecast = el_client.collection("Forecast");
//date range
if(req.body.date_range != null || req.body.date_range != undefined){
let weeks = date_rangeUS(req.body.date_range[0], req.body.date_range[1])
for(var i = 0; i < weeks.length; ++i){
let week = weeks[i];
let el_h_cursor = el_historic.find({"_id": week });
await el_h_cursor.forEach(function(data) {h_entries.push(data)});
let el_f_cursor = el_forecast.find({"_id": week });
await el_f_cursor.forEach(function(data) {f_entries.push(data)});
}
}
//single date selection
else{
let week = ""
if (req.body.dateUS != null || req.body.dateUS != undefined) {
week = date_to_weekUS(req.body.dateUS);
}
else if (req.body.date != null || req.body.date != undefined) {
week = date_to_week(req.body.date);
}
else if (req.body.dateJS != null || req.body.dateJS != undefined) {
week = date_to_weekJS(req.body.dateJS);
}
else{
res.status(400).json({err: "I need a valid date"})
return
}
let el_h_cursor = el_historic.find({"_id": week });
await el_h_cursor.forEach(function(data) {h_entries.push(data)});
let el_f_cursor = el_forecast.find({"_id": week });
await el_f_cursor.forEach(function(data) {f_entries.push(data)});
}
//clean-up
var h_output = {}
var f_output = {}
for (let index = 0; index < h_entries.length; ++index) {
delete h_entries[index]['_id']
h_output = Object.assign({}, h_output, h_entries[index]);
}
for (let index = 0; index < f_entries.length; ++index) {
delete f_entries[index]['_id']
f_output = Object.assign({}, f_output, f_entries[index]);
}
res.json({'Historic' : h_output, 'Forecast' : f_output})
res.status(200);
} catch (err) {
console.log(err);
res.status(500).json({err: err});
}
if(client.isConnected()){
client.close();
}
}
exports.Mexico = async (req, res) => {
let client = getClient();
if(!client.isConnected()){
await client.connect();
}
try{
var h_entries = [];
const m_client = client.db("Mexico");
const m_historic = m_client.collection("Historic");
//date range
if(req.body.date_range != null || req.body.date_range != undefined){
let weeks = date_rangeUS(req.body.date_range[0], req.body.date_range[1])
for(var i = 0; i < weeks.length; ++i){
let week = weeks[i];
const m_h_cursor = m_historic.find({"_id": week });
await m_h_cursor.forEach(function(data) {h_entries.push(data)});
}
}
//single date selection
else{
let week = ""
if (req.body.dateUS != null || req.body.dateUS != undefined) {
week = date_to_weekUS(req.body.dateUS);
}
else if (req.body.date != null || req.body.date != undefined) {
week = date_to_week(req.body.date);
}
else if (req.body.dateJS != null || req.body.dateJS != undefined) {
week = date_to_weekJS(req.body.dateJS);
}
else{
res.status(400).json({err: "I need a valid date"})
return
}
const m_h_cursor = m_historic.find({"_id": week });
await m_h_cursor.forEach(function(data) {entries.push(data)});
}
//clean-up
var h_output = {}
for (let index = 0; index < h_entries.length; ++index) {
delete h_entries[index]['_id']
h_output = Object.assign({}, h_output, h_entries[index]);
}
res.json({'Historic' : h_output, 'Forecast': null})
res.status(200);
} catch (err) {
console.log(err);
res.status(500).json({err: err});
}
if(client.isConnected()){
client.close();
}
}<file_sep>/client/src/components/DropDownButton.js
import Dropdown from "react-bootstrap/Dropdown";
import 'bootstrap/dist/css/bootstrap.min.css';
function DropDownButton() {
return (
<div className="dropdown">
<Dropdown >
<Dropdown.Toggle style={{marginLeft: '50px', marginTop: '50px', borderRadius:'10px', backgroundColor: "#006784"}} id="dropdown-basic">
View Documents
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#/action-1" >
<a href="https://github.com/Naoki95957/Collect-Forecast-Visualize/raw/master/Documents/Press%20Release%20FAQ.pdf"> Press Release (PR) </a>
</Dropdown.Item>
<Dropdown.Item href="#/action-1">
<a href="https://github.com/Naoki95957/Collect-Forecast-Visualize/raw/master/Documents/Software%20Requirements%20Specifications.pdf"> Software Requirements Specification (SRS) </a>
</Dropdown.Item>
<Dropdown.Item href="#/action-1">
<a href="https://github.com/Naoki95957/Collect-Forecast-Visualize/raw/master/Documents/Software%20Design%20Document.pdf"> Software Design Document (SDD) </a>
</Dropdown.Item>
<Dropdown.Item href="#/action-1">
<a href="https://github.com/Naoki95957/Collect-Forecast-Visualize/raw/master/Documents/Software%20Test%20Document.pdf"> Software Test Document (STD) </a>
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</div>
)
}
export default DropDownButton<file_sep>/client/src/components/Accuracy.js
import React from 'react';
import {str_to_date} from './DateToWeek';
import './Plot.css';
import Plotly from 'react-plotly.js';
export class Accuracy extends React.Component{
constructor(props){
super(props);
this.state = {
empty: false,
p_empty: false,
}
}
getData() {
let start = this.props.startDate;
let end = this.props.endDate;
// HIST
this.hydro = [];
this.wind = [];
this.solar = [];
this.thermal = [];
this.other = [];
this.interchange = [];
this.biomass = [];
this.geothermal = [];
let hour = [];
let data = this.props.hist;
delete data['_id'];
let keys = Object.getOwnPropertyNames(data);
keys.sort(function(a, b){
return str_to_date(a) - str_to_date(b);
});
for(let k of keys){
let dateVal = str_to_date(k);
if (dateVal < start || dateVal > end){
continue;
}
hour.push(data[k]);
}
if(hour.length < 1 && !this.state.empty){
this.setState({empty: true})
}else if(hour.length > 1 && this.state.empty){
this.setState({empty: false})
}
let hydro_energy = 0;
let wind_energy = 0;
let solar_energy = 0;
let thermal_energy = 0;
let other_energy = 0;
let interchange_energy = 0;
let biomass_energy = 0;
let geothermal_energy = 0;
for(let h of hour){
for(let i of h){
if( i.type === 'Hydroelectric' ||
i.type === 'HydroElectric' ||
i.type === 'HYDRO') {
hydro_energy = i.value
}
if( i.type === 'Interchange' ||
i.type === 'Interconnection' ||
i.type === 'INTERCHANGE') {
interchange_energy = i.value
}
if( i.type === 'Conventional Thermal' ||
i.type === 'Thermal' ||
i.type === 'THERMAL') {
thermal_energy = i.value
}
if( i.type === 'Solar' ||
i.type === 'SOLAR') {
solar_energy = i.value
}
if( i.type === 'Wind' ||
i.type === 'WIND') {
wind_energy = i.value
}
if( i.type === 'Geothermal' ||
i.type === 'Geothermalelectric') {
geothermal_energy = i.value
}
if( i.type === 'Biomass') {
biomass_energy = i.value
}
if( i.type === 'Other') {
other_energy = i.value
}
}
this.hydro.push(hydro_energy);
this.wind.push(wind_energy);
this.solar.push(solar_energy);
this.thermal.push(thermal_energy);
this.other.push(other_energy);
this.interchange.push(interchange_energy);
this.biomass.push(biomass_energy);
this.geothermal.push(geothermal_energy);
}
// FRCST
this.p_hydro = [];
this.p_wind = [];
this.p_solar = [];
this.p_thermal = [];
this.p_other = [];
this.p_interchange = [];
this.p_biomass = [];
this.p_geothermal = [];
let p_hour = [];
let pred = this.props.frcst;
delete pred['_id'];
let p_keys = Object.getOwnPropertyNames(pred);
p_keys.sort(function(a, b){
return str_to_date(a) - str_to_date(b);
});
for(let p_k of p_keys){
let p_dateVal = str_to_date(p_k);
if (p_dateVal < start || p_dateVal > end){
continue;
}
p_hour.push(pred[p_k]);
}
if(p_hour.length < 1 && !this.state.p_empty){
this.setState({p_empty: true})
}else if(p_hour.length > 1 && this.state.p_empty){
this.setState({p_empty: false})
}
let p_hydro_energy = 0;
let p_wind_energy = 0;
let p_solar_energy = 0;
let p_thermal_energy = 0;
let p_other_energy = 0;
let p_interchange_energy = 0;
let p_biomass_energy = 0;
let p_geothermal_energy = 0;
for(let p_h of p_hour){
for(let p_i of p_h){
if( p_i.type === 'Hydroelectric' ||
p_i.type === 'HydroElectric' ||
p_i.type === 'HYDRO') {
p_hydro_energy = p_i.value
}
if( p_i.type === 'Interchange' ||
p_i.type === 'Interconnection' ||
p_i.type === 'INTERCHANGE') {
p_interchange_energy = p_i.value
}
if( p_i.type === 'Conventional Thermal' ||
p_i.type === 'Thermal' ||
p_i.type === 'THERMAL') {
p_thermal_energy = p_i.value
}
if( p_i.type === 'Solar' ||
p_i.type === 'SOLAR') {
p_solar_energy = p_i.value
}
if( p_i.type === 'Wind' ||
p_i.type === 'WIND') {
p_wind_energy = p_i.value
}
if( p_i.type === 'Geothermal' ||
p_i.type === 'Geothermalelectric') {
p_geothermal_energy = p_i.value
}
if( p_i.type === 'Biomass') {
p_biomass_energy = p_i.value
}
if( p_i.type === 'Other') {
p_other_energy = p_i.value
}
}
this.p_hydro.push(p_hydro_energy);
this.p_wind.push(p_wind_energy);
this.p_solar.push(p_solar_energy);
this.p_thermal.push(p_thermal_energy);
this.p_other.push(p_other_energy);
this.p_interchange.push(p_interchange_energy);
this.p_biomass.push(p_biomass_energy);
this.p_geothermal.push(p_geothermal_energy);
}
// ERROR
this.e_hydro = [];
this.e_wind = [];
this.e_solar = [];
this.e_thermal = [];
this.e_other = [];
this.e_interchange = [];
this.e_biomass = [];
this.e_geothermal = [];
this.mae_hydro = 0;
this.mae_wind = 0;
this.mae_solar = 0;
this.mae_thermal = 0;
this.mae_other = 0;
this.mae_interchange = 0;
this.mae_biomass = 0;
this.mae_geothermal = 0;
let e_h = 0;
let e_w = 0;
let e_s = 0;
let e_t = 0;
let e_b = 0;
let e_g = 0;
let n = hour.length
for(let m = 0; m < n; m++) {
e_h = Math.abs(this.p_hydro[m] - this.hydro[m])
e_w = Math.abs(this.p_wind[m] - this.wind[m])
e_s = Math.abs(this.p_solar[m] - this.solar[m])
e_t = Math.abs(this.p_thermal[m] - this.thermal[m])
e_b = Math.abs(this.p_biomass[m] - this.biomass[m])
e_g = Math.abs(this.p_geothermal[m] - this.geothermal[m])
this.mae_hydro += e_h
this.mae_wind += e_w
this.mae_solar += e_s
this.mae_thermal += e_t
this.mae_biomass += e_b
this.mae_geothermal += e_g
this.e_hydro.push(e_h)
this.e_wind.push(e_w)
this.e_solar.push(e_s)
this.e_thermal.push(e_t)
this.e_biomass.push(e_b)
this.e_geothermal.push(e_g)
}
this.mae_hydro /= n
this.mae_wind /= n
this.mae_solar /= n
this.mae_thermal /= n
this.mae_biomass /= n
this.mae_geothermal /= n
}
render() {
if(!this.props.hist || !this.props.frcst) {
return <div className="message">No data yet.</div>;
} else {
this.getData();
if(this.thermal.length === 0) {
return <div/>
}
}
let error_data = []
let t = 'line'
if(this.e_solar) {
error_data.push({
type: {t},
stackgroup: 'one',
marker: {color: 'yellow'},
name: 'Solar',
y: this.e_solar
})
}
if(this.e_geothermal) {
error_data.push({
type: {t},
stackgroup: 'one',
marker: {color: 'orange'},
name: 'Geothermal',
y: this.e_geothermal
})
}
if(this.e_biomass) {
error_data.push({
type: {t},
stackgroup: 'one',
marker: {color: 'lime'},
name: 'Biomass',
y: this.e_biomass
})
}
if(this.e_wind) {
error_data.push({
type: {t},
stackgroup: 'one',
marker: {color: 'cyan'},
name: 'Wind',
y: this.e_wind
})
}
if(this.e_thermal) {
error_data.push({
type: {t},
stackgroup: 'one',
marker: {color: 'red'},
name: 'Thermal',
y: this.e_thermal
})
}
if(this.e_hydro) {
error_data.push({
type: {t},
stackgroup: 'one',
marker: {color: 'blue'},
name: 'Hydroelectric',
y: this.e_hydro
})
}
// let x = []
// let y = []
let mae_data = [
{
x: ['solar', 'wind', 'hydro', 'thermal', 'biomass', 'geothermal',],
y: [
this.mae_solar,
this.mae_wind,
this.mae_hydro,
this.mae_thermal,
this.mae_biomass,
this.mae_geothermal
],
type: 'bar'
}
];
if(this.state.empty || this.state.p_empty){
return null
}
return (
<div className="country-plotly">
<Plotly
data={error_data}
layout={{
width: 600,
height: 400,
yaxis:{
title: "MWh",
gridcolor: "#FFFFFF55"
},
xaxis:{
title: "time",
showticklabels: false,
gridcolor: "#FFFFFF55"
},
plot_bgcolor:"#FFFFFF99",
paper_bgcolor:"#00000000",
font:
{
color: "#FFFFFF",
},
title: "Forecast Errors"
}}
/>
<Plotly
data={mae_data}
layout={{
width: 600,
height: 400,
yaxis:{
title: "MWh",
gridcolor: "#FFFFFF55"
},
plot_bgcolor:"#FFFFFF99",
paper_bgcolor:"#00000000",
font:
{
color: "#FFFFFF",
},
title: "Forecast MAE"
}}
/>
</div>
);
}
}
export default Accuracy<file_sep>/client/src/App.js
import './App.css';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import {Map} from './pages/Map';
import {Home} from './pages/Home';
import axios from 'axios';
// These will be our proxies
// this is for backend axios requests
axios.defaults.baseURL = "https://cfv-server.herokuapp.com/";
function App() {
return (
<div className='App'>
<Router>
<Switch>
<Route exact path ='/' component = {Home}/>
<Route exact path ='/map' component = {Map}/>
</Switch>
</Router>
</div>
);
}
export default App;
<file_sep>/client/src/components/Plot.js
import React from 'react';
import {str_to_date} from './DateToWeek';
import './Plot.css';
import {GoGraph} from "react-icons/go"
import {FaFileDownload} from 'react-icons/fa'
import Plotly from 'react-plotly.js';
import {CSVLink} from "react-csv";
export default class Plot extends React.Component{
constructor(props){
super(props);
this.state = {
plot: null,
start: this.props.startDate,
loading: this.props.loading,
end: this.props.endDate,
pie_data: null,
pie_layout: null,
pie_point_index: null,
toggle: false,
relayout: null,
country: null,
}
this.hoverDataHandler = this.hoverDataHandler.bind(this);
this.toggleHandler = this.toggleHandler.bind(this);
this.mergeDictionaries = this.mergeDictionaries.bind(this);
this.updateGraph = this.updateGraph.bind(this);
}
getData() {
this.time = [];
this.hydro = [];
this.wind = [];
this.solar = [];
this.thermal = [];
this.other = [];
this.interchange = [];
this.biomass = [];
this.geothermal = [];
this.internal_combustion = [];
this.turbo_gas = [];
this.nuclear = [];
this.renewable = [];
this.not_renewable = [];
let hour = [];
let data = this.props.data;
let start = this.state.start;
let end = this.state.end;
delete data['_id'];
let keys = Object.getOwnPropertyNames(data);
keys.sort(function(a, b){
return str_to_date(a) - str_to_date(b);
});
for(let k of keys){
let dateVal = str_to_date(k);
if (dateVal < start || dateVal > end){
continue;
}
hour.push(data[k]);
this.time.push(k)
}
console.log()
if (hour.length < 1){
if(this.state.plot !== undefined){
this.setState({plot: undefined})
return
}
}
for(let h of hour){
let hydro_energy = 0;
let wind_energy = 0;
let solar_energy = 0;
let thermal_energy = 0;
let other_energy = 0;
let interchange_energy = 0;
let biomass_energy = 0;
let geothermal_energy = 0;
let internal_combustion_energy = 0;
let turbo_gas_energy = 0;
let nuclear_energy = 0;
for(let i of h){
if( i.type === 'Hydroelectric' ||
i.type === 'HydroElectric' ||
i.type === 'HYDRO') {
hydro_energy = i.value
}
if( i.type === 'Interchange' ||
i.type === 'Interconnection' ||
i.type === 'INTERCHANGE') {
interchange_energy = i.value
}
if( i.type === 'Conventional Thermal' ||
i.type === 'Thermal' ||
i.type === 'THERMAL') {
thermal_energy = i.value
}
if( i.type === 'Solar' ||
i.type === 'SOLAR') {
solar_energy = i.value
}
if( i.type === 'Wind' ||
i.type === 'WIND') {
wind_energy = i.value
}
if( i.type === 'Geothermal' ||
i.type === 'Geothermalelectric') {
geothermal_energy = i.value
}
if( i.type === 'Biomass') {
biomass_energy = i.value
}
if( i.type === 'Internal Combustion') {
internal_combustion_energy = i.value
}
if( i.type === 'Turbo Gas') {
turbo_gas_energy = i.value
}
if( i.type === 'Nuclear Power') {
nuclear_energy = i.value
}
if( i.type === 'Other') {
other_energy = i.value
}
}
this.hydro.push(hydro_energy);
this.wind.push(wind_energy);
this.solar.push(solar_energy);
this.thermal.push(thermal_energy);
this.other.push(other_energy);
this.interchange.push(interchange_energy);
this.biomass.push(biomass_energy);
this.geothermal.push(geothermal_energy);
this.internal_combustion.push(internal_combustion_energy);
this.turbo_gas.push(turbo_gas_energy);
this.nuclear.push(nuclear_energy);
this.renewable.push(
hydro_energy +
wind_energy +
solar_energy +
biomass_energy +
geothermal_energy +
turbo_gas_energy
)
this.not_renewable.push(
thermal_energy +
other_energy +
internal_combustion_energy +
nuclear_energy
)
}
// FORMAT CSV DATA
this.csvData = [[
"time",
"HydoElectric",
"Wind",
"Solar",
"Thermal",
"Biomass",
"Geothermal",
"Internal Combustion",
"Gas Turbine",
"Nuclear",
"Interchange",
"Unidentified"
]];
let i = -1;
while (this.time[++i]) {
this.csvData.push( [
this.time[i],
this.hydro[i],
this.wind[i],
this.solar[i],
this.thermal[i],
this.biomass[i],
this.geothermal[i],
this.internal_combustion[i],
this.turbo_gas[i],
this.nuclear[i],
this.interchange[i],
this.other[i]
] );
}
// replace empty sets with empty array
// this way they arent graphed
if(!this.hydro.some((el)=>{return el !== 0})){
this.hydro = [];
}
if(!this.wind.some((el)=>{return el !== 0})){
this.wind = [];
}
if(!this.solar.some((el)=>{return el !== 0})){
this.solar = [];
}
if(!this.thermal.some((el)=>{return el !== 0})){
this.thermal = [];
}
if(!this.other.some((el)=>{return el !== 0})){
this.other = [];
}
if(!this.interchange.some((el)=>{return el !== 0})){
this.interchange = [];
}
if(!this.biomass.some((el)=>{return el !== 0})){
this.biomass = [];
}
if(!this.geothermal.some((el)=>{return el !== 0})){
this.geothermal = [];
}
if(!this.internal_combustion.some((el)=>{return el !== 0})){
this.internal_combustion = [];
}
if(!this.turbo_gas.some((el)=>{return el !== 0})){
this.turbo_gas = [];
}
if(!this.nuclear.some((el)=>{return el !== 0})){
this.nuclear = [];
}
}
toggleHandler(){
this.updateGraph(true);
this.setNewPieChart(true);
}
updateGraph(fromToggle=false){
if(this.props.data) {
this.getData();
this.setState({
country: this.props.country
})
}
let current_data = [
{
type: 'line',
stackgroup: 'one',
marker: {color: 'maroon'},
name: 'Combustion',
x: this.time,
y: this.internal_combustion
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'fuchsia'},
name: 'Gas Turbo',
x: this.time,
y: this.turbo_gas
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'olive'},
name: 'Nuclear',
x: this.time,
y: this.nuclear
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'silver'},
name: 'Other',
x: this.time,
y: this.other
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'yellow'},
name: 'Solar',
x: this.time,
y: this.solar
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'orange'},
name: 'Geothermal',
x: this.time,
y: this.geothermal
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'lime'},
name: 'Biomass',
x: this.time,
y: this.biomass
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'cyan'},
name: 'Wind',
x: this.time,
y: this.wind
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'red'},
name: 'Thermal',
x: this.time,
y: this.thermal
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'blue'},
name: 'Hydroelectric',
x: this.time,
y: this.hydro
}
]
if((fromToggle && !this.state.toggle) || (this.state.toggle && !fromToggle)){
current_data = [
{
type: 'line',
stackgroup: 'one',
marker: {color: 'green'},
name: 'Renewable',
x: this.time,
y: this.renewable
},
{
type: 'line',
stackgroup: 'one',
marker: {color: 'red'},
name: 'Non-renewable',
x: this.time,
y: this.not_renewable
},
]
}
let layout =
{
width: 600,
height: 400,
yaxis:{
title: "MWh",
// showticklabels: false,
gridcolor: "#FFFFFF55"
},
xaxis:{
title: "Time",
showticklabels: false,
gridcolor: "#FFFFFF55"
},
plot_bgcolor:"#FFFFFF99",
paper_bgcolor:"#00000000",
font:
{
color: "#FFFFFF",
},
title: this.props.title
}
if(this.state.relayout){
layout = this.mergeDictionaries(layout, this.state.relayout);
}
let graph = <Plotly
onHover={this.hoverDataHandler}
onRelayout={(e) => {this.setState({relayout: e})}}
data={current_data}
layout={layout}
/>
this.setState({plot: graph});
this.setNewPieChart();
}
setNewPieChart(fromToggle=false){
let values = [];
let labels = [];
let colors = [];
let types = [
{label: 'Combustion', color: 'maroon', data: this.internal_combustion},
{label: 'Gas Turbo', color: 'fuchsia', data: this.turbo_gas},
{label: 'Nuclear', color: 'olive', data: this.nuclear},
{label: 'Other', color: 'silver', data: this.other},
{label: 'Solar', color: 'yellow', data: this.solar},
{label: 'Geothermal', color: 'orange', data: this.geothermal},
{label: 'Biomass', color: 'lime', data: this.biomass},
{label: 'Wind', color: 'cyan', data: this.wind},
{label: 'Thermal', color: 'red', data: this.thermal},
{label: 'Hydroelectric', color: 'blue', data: this.hydro}
]
let alt_types = [
{label: 'Renewable', color: 'green', data: this.renewable},
{label: 'Non-renewable', color: 'red', data: this.not_renewable}
]
let pie_types = types;
if((fromToggle && !this.state.toggle) || (this.state.toggle && !fromToggle))
pie_types = alt_types;
pie_types.forEach(pie_type => {
if(pie_type.data.length >= 0){
labels.unshift(pie_type.label)
colors.unshift(pie_type.color)
values.unshift(pie_type.data[this.state.pie_point_index])
}
});
this.setState({
pie_data: [{
values: values,
labels: labels,
marker: {
colors: colors,
},
type: 'pie',
// set this to true if you want random colors
sort: false,
}],
pie_layout: {
width: 600,
height: 400,
plot_bgcolor:"#FFFFFF99",
paper_bgcolor:"#00000000",
font:
{
color: "#FFFFFF",
},
title: this.time[this.state.pie_point_index]
},
})
if(fromToggle){
this.setState({
toggle: !this.state.toggle,
})
}
}
hoverDataHandler(dataEvent){
if(dataEvent.points.length){
let index = dataEvent.points[0].pointIndex;
this.setState({pie_point_index: index})
this.setNewPieChart();
}
}
mergeDictionaries(obj1, obj2){
for (var key in obj2){
if(obj2.hasOwnProperty(key)){
if(key.includes(".")){
let parts = key.split(".")
if(key.includes(".range")){
if(obj1[parts[0]].hasOwnProperty('range')){
let which_end = parseInt(key.charAt(key.length - 2));
obj1[parts[0]]['range'][which_end] = obj2[key];
}else{
let new_range = [0, 0]
let which_end = parseInt(key.charAt(key.length - 2));
new_range[which_end] = obj2[key];
obj1[parts[0]]['range'] = new_range;
}
}else{
obj1[parts[0]][parts[1]] = obj2[key];
}
}else{
obj1[key] = obj2[key];
}
}
}
return obj1;
}
componentDidMount(){
this.setState({
country: this.props.country
});
}
render() {
if(!this.props.data) {
return <div/>;
} else {
this.getData();
if(this.time.length === 0) {
return <div/>;
}
}
if(this.state.plot === null){
this.updateGraph();
}
if(this.state.country !== this.props.country){
// comment out this setstate if we want persistance between countries
this.setState({
relayout: null,
plot: null
})
this.updateGraph(false);
}
if(this.state.start !== this.props.startDate){
this.setState({
start: this.props.startDate,
end: this.props.endDate,
plot: null,
})
this.updateGraph()
}
if(this.state.end !== this.props.endDate){
this.setState({
start: this.props.startDate,
end: this.props.endDate,
plot: null,
})
this.updateGraph()
}
if(this.state.loading !== this.props.loading){
this.setState({
start: this.props.startDate,
end: this.props.endDate,
loading: this.props.loading,
plot: null,
})
this.updateGraph()
}
if(this.props.updating){
this.getData();
this.updateGraph();
this.props.updateCallback()
}
if(this.state.plot === undefined && !(this.props.loading || this.state.loading)){
return <div className="country-plotly">No {this.props.title} for selected date range.</div>;
}
var buttons = null
if(this.csvData !== undefined && this.csvData !== null){
buttons = <div className="plot-options">
<div onClick={this.toggleHandler} className="graph-change-button">
<p className="tooltiptext">change chart labels</p>
<GoGraph/>
</div>
<CSVLink data={this.csvData}>
<div className="download-link-container">
<p className="tooltiptext">download me as CSV</p>
<FaFileDownload/>
</div>
</CSVLink>
</div>
}
return (
<div className="country-plotly">
{this.props.loading || this.props.updating ? <>loading...</> : null}
{this.state.plot}
{
this.state.pie_data ?
<div className="pie-chart">
<Plotly
data={this.state.pie_data}
layout={this.state.pie_layout}
/>
</div>
:
null
}
{buttons}
</div>
);
}
}
<file_sep>/client/src/pages/Map.js
import '../index.css';
import '../App.css';
import '../components/GlobeAndCalendar.css'
import 'tippy.js/dist/tippy.css';
import 'tippy.js/animations/scale.css';
import {Globe, markers} from '../components/Globe.js'
import NavBar from '../components/NavBar'
import React from 'react';
import Sound from 'react-sound';
import Sidebar from '../components/Sidebar';
const {date_to_stringUS, date_to_weekUS} = require('../components/DateToWeek');
const axios = require('axios');
const volume = 40;
export class Map extends React.Component {
constructor(props) {
super(props);
let today = new Date();
today.setDate(today.getDate() - 7);
var todaySTR = date_to_weekUS(today.toLocaleDateString());
var dateParts = todaySTR.split("/");
var start = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
var end = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 6)
this.state = {
loading: true,
muted: false,
//Used to indicate whether new data is being processed or not
fetchingData: false,
clicked: "none",
country: "none",
country_data: {
"ElSalvador" : {
"Historic" : null,
"Forecast" : null,
},
"Mexico" : {
"Historic" : null,
"Forecast" : null,
},
"Nicaragua" : {
"Historic" : null,
"Forecast" : null,
},
"CostaRica" : {
"Historic" : null,
"Forecast" : null,
}
},
startDate: start,
endDate: end,
eval_start: date_to_stringUS(start),
eval_end: date_to_stringUS(end),
renderSideBar: false,
}
this.onClickMarker = this.onClickMarker.bind(this);
this.changeStartDate = this.changeStartDate.bind(this);
this.changeEndDate = this.changeEndDate.bind(this);
this.defocusHandle = this.defocusHandle.bind(this);
this.muteHandler = this.muteHandler.bind(this);
this.toggleSidebarHandle = this.toggleSidebarHandle.bind(this)
}
muteHandler(){
this.setState({
muted: !this.state.muted
});
}
onClickMarker(marker, markerObject, event) {
this.setState({
renderSideBar: true
})
let vol = 0.3;
if(this.state.muted){
vol = 0;
}
let audio = new Audio("audio/wind.mp3")
audio.volume = vol;
audio.play();
const country_id = marker['id'];
const country = marker['country']
// this.queryData(country_id, date_to_stringUS(this.state.startDate), date_to_stringUS(this.state.endDate))
this.setState({
clicked: country_id,
country: country
});
}
/**
* event passing for datepicker
* @param {*} date
*/
changeStartDate(date, callback=null){
this.setState({
startDate: date
});
markers.forEach(element => {
this.queryData(element.id, date_to_stringUS(this.state.startDate), date_to_stringUS(this.state.endDate), callback);
});
}
/**
* event passing for datepicker
* @param {*} date
*/
changeEndDate(date, callback=null){
this.setState({
endDate: date
});
markers.forEach(element => {
this.queryData(element.id, date_to_stringUS(this.state.startDate), date_to_stringUS(this.state.endDate), callback);
});
}
async queryData(country_string, start_date, end_date, callback=null)
{
//We already have the data
if( this.state.eval_start === start_date && this.state.eval_end === end_date){
this.setState({fetchingData: false})
return
}else{
this.setState({fetchingData: true})
}
const config = {
'Content-Type':'application/json'
}
// date_range example:
// This expects both parameters to be in the form:
// MM/DD/YYYY
const body = {
date_range: [start_date, end_date]
}
// Use one of these in this body
// dateUS -> 'mm/dd/yyyy'
// date -> 'dd/mm/yyyy'
// dateJS -> JS Date object
// These are all equivalent
// const body = {
// dateUS: '01/09/2019'
// }
// const body = {
// date: '09/01/2019'
// }
// const body = {
// dateJS: new Date(2019, 1, 9)
// }
const res = await axios.post(
`/query/${country_string}`,
body,
config
);
if(res.status === 200) {
let copy = this.state.country_data
let hist = res.data['Historic'];
let forecast = res.data['Forecast'];
copy[country_string]['Historic'] = hist;
copy[country_string]['Forecast'] = forecast;
this.setState({
country_data: copy,
eval_start: start_date,
eval_end: end_date
});
console.log(this.state.country_data)
this.setState({fetchingData: false})
}
if(callback !== null){
callback()
}
}
defocusHandle(){
let vol = 0.3;
if(this.state.muted){
vol = 0;
}
let audio = new Audio("audio/wind.mp3")
audio.volume = vol;
audio.play();
this.setState({
renderSideBar: false
});
}
toggleSidebarHandle() {
this.setState({
renderSideBar: !this.state.renderSideBar
});
}
componentDidMount() {
this.queryData('ElSalvador', this.state.startDate, this.state.endDate)
this.queryData('Mexico', this.state.startDate, this.state.endDate)
this.queryData('CostaRica', this.state.startDate, this.state.endDate)
this.queryData('Nicaragua', this.state.startDate, this.state.endDate)
// this.state.markers.forEach(element => {
// if (this.state.country_data[element.id]["Historic"] !== null) {
// let i = 0;
// let sum = 0;
// for (let day of this.state.country_data[element.id]["Historic"]) {
// for (let hour of day) {
// for (let energy of hour) {
// i++;
// sum += energy;
// }
// }
// }
// let mean = (sum/i);
// element.value = mean/40;
// }
// });
this.setState({
globe: new Globe(
{
markerClick: this.onClickMarker,
defocusHandler: this.defocusHandle
}
).getGlobe()
});
this.setState({loading: false})
}
render() {
if(this.state.loading){
return <div>Loading........</div>;
}
let hist = null;
let frcst = null;
if (this.state.clicked !== "none") {
hist = this.state.country_data[this.state.clicked]['Historic'];
frcst = this.state.country_data[this.state.clicked]['Forecast'];
}
let vol = volume;
if(this.state.muted){
vol = 0;
}
return (
<div className="globe">
<NavBar/>
<Sound
url="audio/Distant-Mountains.mp3"
playStatus={Sound.status.PLAYING}
volume={vol}
loop={true}
/>
<Sidebar
toggleCollapseHandle={this.toggleSidebarHandle}
muted={this.state.muted}
muteHandler={this.muteHandler}
collapsed={!this.state.renderSideBar}
loading={this.state.fetchingData}
changeEndDate={this.changeEndDate}
changeStartDate={this.changeStartDate}
hist={hist}
frcst={frcst}
start={this.state.startDate}
end={this.state.endDate}
country={this.state.country}
/>
{this.state.globe}
</div>
);
}
}
export default Map | 8d0141d82523d1075dab17f8f9fb51ab43c03a26 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | vitaliybeinspired/react-data-visualizer | 42ceac6509d4f9f18e5ee819f8c01d367036249f | f1e4ff214a54f07bfa0b8311ce552b0cd3e1f6fb |
refs/heads/master | <repo_name>dy93/gitbook-plugin-plantuml-cloud<file_sep>/README.md
# GitBook PlantUml Plugin
* inspired by [romanlytkin/gitbook-plantuml](https://github.com/romanlytkin/gitbook-plantuml)
The plugin now supports two APIs for generating PlantUML diagrams:
* [bitjourney/plantuml-service](https://github.com/bitjourney/plantuml-service)
* [PlantUML Server](http://www.plantuml.com/plantuml/)
## Installation
* Add the plugin to your book.json
```js
{
"plugins": ["plantuml-cloud"]
}
```
* Install the plugin to you gitbook
```$ gitbook install```
* No additional steps required
## Configuration
* If you do not add a plugin configuration to your book.json, then the following defaults will be used:
| Configuration option | Description | Default |
| -------------------- | ----------- | ------- |
| umlPath | Path to a directory where the generated images for the diagrams will be cached. | "assets/images/uml" |
| type | Determines the type of the server side API | "plantuml-service" |
| host | Host for the diagramming service | "plantuml-service.herokuapp.com" |
| port | Port number for the diagramming service | 80 |
| protocol | https or http | "https" |
| path | URL Fragment which will be appended to the host part | "/svg" |
| blockRegex | Regular expression to select the diagramming text blocks. | ^```uml((.*\n)+?)?```$ |
* If want to use the PlantUML Server API the following changes need to be made to the plugin configuration in your book.json:
```js
{
"plugins": ["plantuml-cloud"],
"pluginsConfig": {
"plantuml-cloud": {
"protocol": "http",
"type": "plantuml-server",
"host": "www.plantuml.com",
"path": "/plantuml/svg/"
}
}
}
```
> The PlantUML Server API on plantuml.com expects the diagram text blocks in a special encoding. [Look here for more information.](http://plantuml.com/pte)
> To make this encoding work in this plugin it was necessary to include some code for the deflate operations. [Look here for more information.](https://github.com/johan/js-deflate)
* [x] Make the plugin work with nodejs zlib deflate implementation and remove the duplicated deflate code.
<file_sep>/plantuml_encode.js
/**
*
* @param {Buffer} c
*/
function encode64(c) {
var str = "";
var len = c.length;
for (var i = 0; i < len; i += 3) {
if (i + 2 == len) {
str += append3bytes(c[i], c[i + 1], 0);
} else if (i + 1 == len) {
str += append3bytes(c[i], 0, 0);
} else {
str += append3bytes(c[i], c[i + 1], c[i + 2]);
}
}
return str;
}
function append3bytes(b1, b2, b3) {
var c1 = b1 >> 2;
var c2 = ((b1 & 0x3) << 4) | (b2 >> 4);
var c3 = ((b2 & 0xf) << 2) | (b3 >> 6);
var c4 = b3 & 0x3f;
var r = "";
r += encode6bit(c1 & 0x3f);
r += encode6bit(c2 & 0x3f);
r += encode6bit(c3 & 0x3f);
r += encode6bit(c4 & 0x3f);
return r;
}
function encode6bit(b) {
if (b < 10) {
return String.fromCharCode(48 + b);
}
b -= 10;
if (b < 26) {
return String.fromCharCode(65 + b);
}
b -= 26;
if (b < 26) {
return String.fromCharCode(97 + b);
}
b -= 26;
if (b == 0) {
return "-";
}
if (b == 1) {
return "_";
}
return "?";
}
module.exports = {
encode64: encode64
};
| 55d561d776b7c2d1ff90490e63f0314d6de29c70 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | dy93/gitbook-plugin-plantuml-cloud | 62e10d172d4458717539a2b561bb2a80ca648e11 | 9f993ecb202560d53d45d6bd249df210ffb6f64b |
refs/heads/master | <repo_name>akshett/cpp_queue<file_sep>/queueClassNode.cpp
#include <iostream>
template<class T>
class QueueNode
{
private:
struct Node
{
T val;
Node *next;
};
Node *first;
Node *last;
int size;
public:
QueueNode():size(0)
{
}
void insert(T m_val)
{
Node *oldlast = last;
last = new Node;
last->val = m_val;
if (isEmpty())
first = last;
else
oldlast->next = last;
size++;
}
T deque()
{
Node *oldfirst = first;
first = first->next;
T fr = oldfirst->val;
delete oldfirst;
size--;
if (isEmpty())
{
last = nullptr;
}
return fr;
}
bool isEmpty()
{
return (size == 0);
}
void iterPrint()
{
Node *it = first;
while(it != nullptr)
{
std::cout << it->val << " ";
it = it->next;
}
std::cout << '\n';
}
int count()
{
return size;
}
~QueueNode()
{
Node *it = first;
while(it != nullptr)
{
Node *new_it = it->next;
delete it;
it = new_it;
}
}
};
int main()
{
QueueNode<int> qn;
std::cout << "Initialized new queue node, Is it empty?" << '\n';
std::cout << qn.isEmpty() << '\n';
std::cout << "Size of new queue node: " << '\n';
std::cout << qn.count() << '\n';
qn.insert(4);
int a = 9;
qn.insert(a);
qn.insert(a);
qn.insert(32);
qn.iterPrint();
std::cout << "Size of recent queue node: " << '\n';
std::cout << qn.count() << '\n';
std::cout << "Dequeing an element out" << '\n';
std::cout << qn.deque() << '\n';
std::cout << "Size of queue node now: " << '\n';
std::cout << qn.count() << '\n';
qn.deque();
qn.deque();
qn.deque();
qn.insert(53);
std::cout << qn.deque() << '\n';
std::cout << "Is the queue empty now?" << '\n';
std::cout << qn.isEmpty() << '\n';
std::cout << "Size of queue node now " << '\n';
std::cout << qn.count() << '\n';
return 0;
}
<file_sep>/README.md
# Queues
This is C++ implementation of queue data structure. The principle of first in first out (FIFO) applies to this data structure.
The queue classs is implemented first by using C++ array and node class separately.
The interface hass four main functions:
Insert
Deque
printelements
getSize
<file_sep>/queueClassArray.cpp
#include <iostream>
template<class T>
class QueueArray
{
private:
T *arr;
int size;
int capacity;
int first_pos;
void resize_arr(int cap)
{
T *temp_arr = new T[cap];
for (int i = 0; i < size; ++i)
{
temp_arr[cap - 1 - i] = arr[first_pos - i];
}
delete[] arr;
arr = temp_arr;
}
public:
QueueArray():arr(new T[1]), size(0), capacity(1), first_pos(0)
{
}
void insert(T m_val)
{
if (size >= capacity)
{
resize_arr(2*capacity);
capacity *= 2;
first_pos = capacity - 1;
}
arr[first_pos - size] = m_val;
size++;
}
T deque()
{
T el = arr[first_pos--];
size--;
if (size > 0 && size <= capacity/4)
{
resize_arr(capacity/2);
capacity /= 2;
first_pos = capacity - 1;
}
return el;
}
bool isEmpty()
{
return (size == 0);
}
int count()
{
return size;
}
void iterPrint()
{
for (int i = 0 ; i < size; ++i)
{
std::cout << arr[first_pos - i] << " ";
}
std::cout << '\n';
}
~QueueArray()
{
delete[] arr;
}
};
int main()
{
QueueArray<int> qa;
std::cout << "Initialized new queue array, Is it empty?" << '\n';
std::cout << qa.isEmpty() << '\n';
std::cout << "Size of new queue array: " << '\n';
std::cout << qa.count() << '\n';
qa.insert(4);
int a = 9;
qa.insert(a);
qa.insert(a);
qa.insert(32);
qa.iterPrint();
std::cout << "Size of recent queue array: " << '\n';
std::cout << qa.count() << '\n';
std::cout << "Dequeing an element out" << '\n';
std::cout << qa.deque() << '\n';
std::cout << "Size of queue array now: " << '\n';
std::cout << qa.count() << '\n';
qa.deque();
qa.deque();
qa.deque();
qa.insert(53);
std::cout << qa.deque() << '\n';
std::cout << "Is the queue empty now?" << '\n';
std::cout << qa.isEmpty() << '\n';
std::cout << "Size of queue array now " << '\n';
std::cout << qa.count() << '\n';
return 0;
}
| 741afdf4613a1b429738efbd91e5f3d595dd436b | [
"Markdown",
"C++"
] | 3 | C++ | akshett/cpp_queue | 041a908587bd60ea7edca799c0b12c62bd0f874f | 03c90d78e6ba96787c95949ab2bb9c29cc4801e9 |
refs/heads/main | <repo_name>piyushjadhav28/github-demo<file_sep>/math.py
#Add() implementation
def add(x,y):
return x+y
#Subtract() implementation
def subtract(x,y):
pass
#Multiply() implementation
def multiply(x,y):
pass
#Divide() implmenetation
def divide(x,y):
pass
| 2b966957afa97fe747edfbbdb64de66e88eebbc4 | [
"Python"
] | 1 | Python | piyushjadhav28/github-demo | 99bd3c21377eb4299862fad32bcbbbfb815f180a | dfc7c531b9b83080d559f2be4615429efe671807 |
refs/heads/master | <repo_name>msyriac/dionysus<file_sep>/README.md
# A Happy Hour Reminder Bot

**dio**: What is my purpose?
**msyriac**: You send emails.
**dio**: Oh my god...
This bot sends out a reminder email with a randomly chosen location for a Happy Hour meet-up. It now has weather awareness.
# Suggesting new places
Add a comma-delimited row to `listOfPlaces.csv` containing the name of the
place, a weight expressing your desire to go the place on a scale from 0
(would never go) to 1 (would always be up for going there) and True/False
depending on whether the place has a patio. If the weather is nice, only
those places that have a patio will be considered.
# Usage
Edit `settings.yaml`, `email_first_reminder.txt`, `email_location.txt` and `listOfPlaces.csv`.
Then,
```
./dionysus.py start settings.yaml
```
to start a background process.
```
./dionysus.py stop
```
to stop any background processes.
```
./dionysus.py restart settings.yaml
```
to restart with new settings.
<file_sep>/weather_info.py
from weather import Weather
def is_str_in_list(text,alist):
for item in alist:
if item in text: return True
return False
def is_it_nice_out(woeid):
weather = Weather()
lookup = weather.lookup(woeid)
condition = lookup.condition()
bad_weather = ['Rain','Thunderstorms','Showers']
cold_temp = 64
outside = condition['text'].strip()
temp = int(condition['temp'])
if not(is_str_in_list(outside,bad_weather)) and temp>=cold_temp:
return True, outside, temp
else:
return False, outside, temp
def test_weather():
# woeid = 2476729
# print is_it_nice_out(woeid)
import numpy as np
N = 1000
for i in range(N):
woeid = np.random.randint(100000)
#print woeid
try:
is_it, outside, temp = is_it_nice_out(woeid)
print is_it, outside,temp
except:
pass
<file_sep>/test_probabilities.py
'''Tests whether the random place selection is working as expected
'''
from __future__ import print_function
from dionysus import location_decision
import numpy as np
# get places and weights
places_weights = np.genfromtxt("listOfPlaces.csv", delimiter=",",
names=True, dtype=['U128', float])
my_places = places_weights['name']
weights = places_weights['weight']
N = 10000
counts = {}
for i in xrange(N):
decision = location_decision(my_places,weights)
try:
counts[decision] += 1
except KeyError:
counts[decision] = 0
weights /= np.sum(weights)
for place in counts.keys():
counts[place] /= float(N)
print(place,'{:.3f}'.format(counts[place]),'{:.3f}'.format(weights[my_places.tolist().index(place)]))
<file_sep>/dionysus.py
#!/usr/bin/python2
from __future__ import print_function
import time, sys, yaml, os
from daemon import runner
import datetime as dt
import pytz
from dateutil import parser
import getpass
import calendar
import numpy as np
import traceback
def randFromList(d):
return d[np.random.randint(0,len(d))]
def location_decision(my_places,weights):
try:
with open('/tmp/dionysus_last_time.txt', 'r') as myfile:
last_time=myfile.read().replace('\n', '').strip()
except:
last_time = ""
# weights should sum to 1 for multinomial
weights /= np.sum(weights)
decision = last_time
while decision.strip()==last_time:
idx = np.where(np.random.multinomial(1, weights))[0]
decision = my_places[idx[0]]
with open('/tmp/dionysus_last_time.txt', "w") as text_file:
text_file.write(decision)
return decision
def try_email_authenticate(user, pwd,mail_server="mail.astro.princeton.edu"):
"""Before starting the daemon (which might only try accessing the mail
server a week later), we want to make sure the credentials entered are valid.
"""
import smtplib
try:
server = smtplib.SMTP(mail_server, 587)
server.ehlo()
server.starttls()
server.login(user, pwd)
server.close()
print('dio: Successfully authenticated.')
except:
traceback.print_exc()
print("dio: Authentication failed.")
sys.exit(1)
def send_email(user, pwd, recipient, subject, body,mail_server="mail.astro.princeton.edu"):
'''Sends email given username, password, recipient list, email subject and message
body.
'''
import smtplib
FROM = "dio"
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP(mail_server, 587)
server.ehlo()
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
print('dio: Successfully sent mail.')
except:
traceback.print_exc()
print("dio: Failed to send mail.")
def process_email(email_body,data_map,list_of_places_file=None):
decisions = {}
if list_of_places_file is not None:
# read from the possible choice of places
places_weights = np.genfromtxt(list_of_places_file,
delimiter=",",
names=True,
dtype=['U128', float, 'U128'])
my_places = places_weights['name']
weights = places_weights['weight']
patios = np.array([s.strip().lower() in ['true','t','y','yes','yep'] for s in places_weights['patio']])
import weather_info as w
woeid = 2476729 # Princeton, NJ
nice_out,weather,temperature = w.is_it_nice_out(woeid)
if nice_out:
my_places = my_places[np.where(patios)]
weights = weights[np.where(patios)]
data_map['weather'] = "(It's not too bad out today, so I picked a place that has a patio.)"
else:
data_map['weather'] = ""
# decide on a location
np.random.seed(int(time.time()))
decisions['_location'] = location_decision(my_places,weights)
# find unknowns marked by $ in the template
unknowns = [word[1:] for word in email_body.split() if word.startswith('$')]
dataMap = data_map
# replace unknowns with either settings or decisions
for unknown in unknowns:
try:
d = dataMap[unknown]
except KeyError:
try:
d = dataMap['personality'][unknown]
except KeyError:
try:
d = decisions[unknown]
except KeyError:
d = "DERP"
# if there are multiple possibilities, randomly decide
if type(d) is list or type(d) is tuple:
d = randFromList(d)
email_body = email_body.replace('$'+unknown,d)
return email_body
def check_if_time(frequency,trigger_day,time_zone_string,trigger_time,tolerance):
today = dt.date.today()
if frequency=='weekly':
assert trigger_day in [calendar.day_name[x] for x in xrange(7)], "Unrecognized day name."
isDay = (calendar.day_name[today.weekday()]==trigger_day)
if not(isDay): return False
else:
raise NotImplementedError
timezone=pytz.timezone(time_zone_string)
time_now = dt.datetime.now(tz=timezone)
datestring = dt.datetime.strftime(dt.datetime.today().date(),format='%b %d %Y')
passtime = trigger_time
dtin = parser.parse(passtime)
dtin_aware = timezone.localize(dtin)
if abs((dtin_aware-time_now).total_seconds())<tolerance:
return True
else:
return False
class App():
def __init__(self,daemon_command,yaml_file,time_interval_sec=60,tolerance_seconds=180):
self.dir = os.path.dirname(os.path.abspath(__file__))
self.stdin_path = '/dev/null'
self.stdout_path = self.dir+'/dio_out_'+str(time.time())+".log"
self.stderr_path = self.dir+'/dio_err_'+str(time.time())+".log"
self.pidfile_path = '/tmp/dionysus_daemon.pid'
self.pidfile_timeout = 5
self.interval = time_interval_sec
self.tolerance = tolerance_seconds
assert self.tolerance>self.interval
self.last_day_reminder = -1
self.last_day_location = -1
# get user credentials
if daemon_command!="stop":
with open(yaml_file) as f:
self.settings = yaml.safe_load(f)
self.username = getpass.getpass("Username for accessing "+self.settings['email']['mail_server']+": ")
self.pwd = getpass.getpass()
try_email_authenticate(self.username, self.pwd,mail_server=self.settings['email']['mail_server'])
print("dio: Daemon is running.")
def run(self):
while True:
now_day = dt.datetime.today().day
'''
if check_if_time(self.settings['frequency'],
self.settings['trigger_day'],
self.settings['time_zone'],
self.settings['trigger_time_reminder'],
tolerance=self.tolerance) and (now_day!=self.last_day_reminder):
print("Time to send a reminder...")
self.last_day_reminder = dt.datetime.today().day
with open(self.dir+"/email_first_reminder.txt") as f:
email_body = f.read()
email_body = process_email(email_body,self.settings)
send_email(self.username, self.pwd,
self.settings['email']['recipients'],
randFromList(self.settings['email']['subject']),
email_body,
self.settings['email']['mail_server'])
'''
if check_if_time(self.settings['frequency'],
self.settings['trigger_day'],
self.settings['time_zone'],
self.settings['trigger_time_location'],
tolerance=self.tolerance) and (now_day!=self.last_day_location):
print("Time to send location...")
self.last_day_location = dt.datetime.today().day
with open(self.dir+"/email_location.txt") as f:
email_body = f.read()
email_body = process_email(email_body,self.settings,
list_of_places_file=self.dir+"/listOfPlaces.csv")
send_email(self.username, self.pwd,
self.settings['email']['recipients'],
randFromList(self.settings['email']['subject']),
email_body,
self.settings['email']['mail_server'])
time.sleep(self.interval)
def test(yaml_file):
dir = os.path.dirname(os.path.abspath(__file__))
with open(yaml_file) as f:
settings = yaml.safe_load(f)
with open(dir+"/email_location.txt") as f:
email_body = f.read()
email_body = process_email(email_body,settings, \
list_of_places_file=dir+"/listOfPlaces.csv")
print(email_body)
def main(argv):
try:
yamlFile = sys.argv[2]
except:
assert sys.argv[1]=="stop", "No settings yaml file specified."
yamlFile = None
if sys.argv[1]=="test":
test(sys.argv[2])
sys.exit()
app = App(sys.argv[1],yamlFile)
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
if (__name__ == "__main__"):
main(sys.argv)
| d86e1a470f877ca2e953709362c11d2ed69a4531 | [
"Markdown",
"Python"
] | 4 | Markdown | msyriac/dionysus | 6ab5decbb9c15c303cca8e6cc8097591c4e8df5a | 70063f1f16d57b3d6bde71582505535b541aa59d |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Slider, Icon } from 'antd';
import { store_update_slider_value } from '../../store/actions/modeActions';
class IconSlider extends Component {
handleChange = value => {
store_update_slider_value(value);
}
render() {
const { max, min, sliderValue } = this.props;
const mid = ((max - min) / 2).toFixed(5);
const preColor = sliderValue >= mid ? 'rgb(198, 198, 198)' : 'rgb(255, 255, 255)';
const nextColor = sliderValue >= mid ? 'rgb(255, 255, 255)' : 'rgb(198, 198, 198)';
return (
<div className="icon-wrapper">
<Icon style={{ color: preColor }} type="minus" />
<Slider {...this.props} onChange={this.handleChange} value={this.props.sliderValue} />
<Icon style={{ color: nextColor }} type="plus" />
</div>
);
}
}
function mapState2Props(store) {
return {
sliderValue: store.mode.sliderValue
}
}
const SliderWithStore = connect(mapState2Props)(IconSlider);
export default SliderWithStore;<file_sep>import React, { Component } from 'react';
import { CLIENT_WIDTH } from '../../global/size';
import { connect } from 'react-redux';
import { Slider, message as Message } from 'antd';
import './index.css';
import { store_update_data_info_danger, store_get_text_html_body } from '../../store/actions/dataActions';
import NativeBridge from '../../util/nativeBridge';
import * as Params from '../../global/param';
import Api from '../../socket/index';
import * as BrowserUtil from '../../util/browserUtil';
import Variables from '../../global/variables';
class Progress extends Component {
handleChange = value => {
let title = this.props.chapterList[value].title
store_update_data_info_danger({ progressShowChapterIndex: value, progressShowChapterTitle: title });
}
afterChange = value => {
const { _id, fiction_id, title, index } = this.props.chapterList[value];
Api.fetchFictionFileUrl(Params.Nnovel, fiction_id, _id, index, (e, code) => {
if (code === 200) {
Variables.buyInfo.reg = { index, title, id: _id };
let result = NativeBridge.buyFiction(_id, Params.Nnovel, 'false');
if (result === 'success') {
NativeBridge.buySuccess();
} else if (result === 'failed') {
Message.error('购买失败,请重试!');
}
} else {
store_get_text_html_body(e.href, Params.Nnovel);
store_update_data_info_danger({ title, progressShowChapterIndex: index, progressShowChapterTitle: title, chapterIndex: index });//危险方法
BrowserUtil.backToTop();
}
});
}
nextChapter = () => {
if (this.props.chapterIndex >= this.props.chapterList.length - 1) {
Message.warning('已经是最后一章了哟!');
} else {
this.afterChange(this.props.chapterIndex + 1);
}
}
preChapter = () => {
if (this.props.chapterIndex <= 0) {
Message.warning('已经是首章了哟!');
} else {
this.afterChange(this.props.chapterIndex - 1);
}
}
render() {
let title = this.props.title.length >= 15 ? `${this.props.title.slice(0, 10)}...` : this.props.title;
return (
<div
style={{ width: CLIENT_WIDTH, height: 90, position: 'fixed', left: 0, bottom: 64, backgroundColor: '#222', paddingLeft: 12, paddingRight: 12, display: 'flex', flexDirection: 'column' }}>
<div style={{ flex: 1, display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
<div onClick={this.preChapter} style={{ color: '#e6e6e6' }}>{'《 上一章'}</div>
<div style={{ color: '#e6e6e6' }}>{title}</div>
<div onClick={this.nextChapter} style={{ color: '#e6e6e6' }}>{'下一章 》'}</div>
</div>
<div style={{ flex: 1 }}>
<Slider min={this.props.firstIndex} max={this.props.lastIndex} onAfterChange={this.afterChange} onChange={this.handleChange} value={this.props.progressIndex} tipFormatter={null} />
</div>
</div>
);
}
}
function mapState2Props(store) {
return {
title: store.data.progressShowChapterTitle,
firstIndex: store.data.firstChapterIndex,
lastIndex: store.data.lastChapterIndex,
progressIndex: store.data.progressShowChapterIndex,
chapterList: store.data.chapterList,
chapterIndex: store.data.chapterIndex,
}
}
const ProgressWithStore = connect(mapState2Props)(Progress);
export default ProgressWithStore;<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { List, message as Message } from 'antd';
import * as Params from '../../global/param';
import Api from '../../socket/index';
import { store_get_text_html_body, store_update_data_info_danger } from '../../store/actions/dataActions';
import { store_change_data_list_asc } from '../../store/actions/modeActions';
import NativeBridge from '../../util/nativeBridge';
import * as BrowserUtil from '../../util/browserUtil';
import Variables from '../../global/variables';
class Item extends Component {
render() {
let title = this.props.item.title.length >= 15 ? `${this.props.item.title.slice(0, 10)}...` : this.props.item.title;
let titleStyle = this.props.chapterIndex === this.props.item.index ? { flex: 1, display: 'flex', flexDirection: 'row', alignItems: 'center', fontSize: 16, color: '#ED424B' } : { flex: 1, display: 'flex', flexDirection: 'row', alignItems: 'center', fontSize: 16 };
return (
<div onClick={this.itemOnClick} style={{ width: '100%', height: 40, display: 'flex', flexDirection: 'column', paddingLeft: 24 }}>
<div style={titleStyle}>
{title}
</div>
<div style={{ height: 1, width: '100%', backgroundColor: 'rgba(0,0,0,0.05)' }} />
</div>
);
}
itemOnClick = () => {
const { _id, fiction_id, title, index } = this.props.item;
Api.fetchFictionFileUrl(Params.Nnovel, fiction_id, _id, index, (e, code) => {
if (code === 200) {
Variables.buyInfo.reg = { index, title, id: _id };
let result = NativeBridge.buyFiction(_id, Params.Nnovel, 'false');
if (result === 'success') {
NativeBridge.buySuccess();
} else if (result === 'failed') {
Message.error('购买失败,请重试!');
}
} else {
store_get_text_html_body(e.href, Params.Nnovel);
store_update_data_info_danger({ title, progressShowChapterIndex: index, progressShowChapterTitle: title, chapterIndex: index });//危险方法
BrowserUtil.backToTop();
}
});
}
}
class ChapterList extends Component {
render() {
let title = this.props.fictionTitle.length > 10 ? `${this.props.fictionTitle.slice(0, 7)}...` : this.props.fictionTitle;
let chapterNum = `共${this.props.data.length}章`;
let data = this.props.data.concat();
let ascText = '倒序';
if (!this.props.isAsc) {
data.reverse();
ascText = '正序'
}
return (
<div>
<div
style={{
height: 38,
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
fontSize: 20,
color: '#ED424B',
borderBottomColor: '#ED424B',
borderBottomWidth: 1,
borderBottomStyle: 'solid'
}}>
{title}
</div>
<div
style={{
height: 38,
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
fontSize: 14,
borderBottomColor: 'rgba(0,0,0,0.05)',
borderBottomWidth: 1,
borderBottomStyle: 'solid',
paddingLeft: 12,
paddingRight: 12,
}}>
<div style={{ color: '#000', fontWeight: 'bold' }}>{chapterNum}</div>
<div onClick={this.changeAsc} style={{ color: '#F00', fontWeight: 'bold' }}>{ascText}</div>
</div>
<List
dataSource={data}
renderItem={(item, index) => <Item key={index} chapterIndex={this.props.chapterIndex} item={item} />}
/>
</div>
);
}
changeAsc = () => {
store_change_data_list_asc();
}
}
function mapState2Props(store) {
return {
data: store.data.chapterList,
title: store.data.title,
chapterIndex: store.data.chapterIndex,
fictionTitle: store.data.fictionTitle,
isAsc: store.mode.isAsc
}
}
const ChapterWithStore = connect(mapState2Props)(ChapterList);
export default ChapterWithStore;<file_sep>import * as Types from '../actionTypes';
const baseClassName = 'text_container';
const defaultBgColorClassName = 'defaultBgColor';
const blueBgColorClassName = 'blurBgColor';
const greenBgColorClassName = 'greenBgColor';
const whiteBgColorClassName = 'whiteBgColor';
const blackBgColorClassName = 'blackBgColor';
const defaultFontSizeClassName = 'default_fontSize';
const defaultFontSizeClassNamePlus = 'default_fontSizeP1';
const defaultFontSizeClassNamePlus2 = 'default_fontSizeP2';
const defaultFontSizeClassNamePlus3 = 'default_fontSizeP3';
const defaultFontSizeClassNameMinus = 'default_fontSizeM1';
const defaultFontSizeClassNameMinus2 = 'default_fontSizeM2';
const defaultFontSizeClassNameMinus3 = 'default_fontSizeM3';
const initialState = {
isDark: false,
sliderValue: 4,
lightColorSelectIndex: 0,
lightColorClassName: defaultBgColorClassName,
fontSizeClassName: defaultFontSizeClassName,
textContainerClassName: `${baseClassName} ${defaultBgColorClassName} ${defaultFontSizeClassName}`,
isAsc: true
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case Types.CHANGE_MODE_TO_DARK:
window.localStorage.setItem('isDark', '1');
return {
...state,
isDark: true,
textContainerClassName: `${baseClassName} ${blackBgColorClassName} ${state.fontSizeClassName}`
}
case Types.CHANGE_MODE_TO_LIGHT:
window.localStorage.setItem('isDark', '0');
return {
...state,
isDark: false,
textContainerClassName: `${baseClassName} ${state.lightColorClassName} ${state.fontSizeClassName}`
}
case Types.UPDATE_SLIDER_VALUE:
let fontSizeClassName = state.fontSizeClassName;
switch (action.sliderValue) {
case 1:
fontSizeClassName = defaultFontSizeClassNameMinus3;
break;
case 2:
fontSizeClassName = defaultFontSizeClassNameMinus2;
break;
case 3:
fontSizeClassName = defaultFontSizeClassNameMinus;
break;
case 4:
fontSizeClassName = defaultFontSizeClassName;
break;
case 5:
fontSizeClassName = defaultFontSizeClassNamePlus;
break;
case 6:
fontSizeClassName = defaultFontSizeClassNamePlus2;
break;
case 7:
fontSizeClassName = defaultFontSizeClassNamePlus3;
break;
default:
break;
}
window.localStorage.setItem('sliderValue', `${action.sliderValue}`);
return {
...state,
fontSizeClassName,
sliderValue: action.sliderValue,
textContainerClassName: `${baseClassName} ${state.isDark ? blackBgColorClassName : state.lightColorClassName} ${fontSizeClassName}`
}
case Types.CHANGE_LIGHT_BG_COLOR:
let lightBgColorClassName = defaultBgColorClassName;
switch (action.index) {
case 0:
lightBgColorClassName = defaultBgColorClassName;
break;
case 1:
lightBgColorClassName = blueBgColorClassName;
break;
case 2:
lightBgColorClassName = greenBgColorClassName;
break;
case 3:
lightBgColorClassName = whiteBgColorClassName;
break;
default:
break;
}
window.localStorage.setItem('lightColorSelectIndex', `${action.index}`);
if (action.keepDarkSet) {
if (state.isDark) {
return {
...state,
lightColorSelectIndex: action.index,
lightColorClassName: lightBgColorClassName,
}
} else {
return {
...state,
lightColorSelectIndex: action.index,
lightColorClassName: lightBgColorClassName,
textContainerClassName: `${baseClassName} ${lightBgColorClassName} ${state.fontSizeClassName}`
}
}
} else {
window.localStorage.setItem('isDark', '0');
return {
...state,
isDark: false,
lightColorSelectIndex: action.index,
lightColorClassName: lightBgColorClassName,
textContainerClassName: `${baseClassName} ${lightBgColorClassName} ${state.fontSizeClassName}`
}
}
case Types.CHANGE_ASC:
return {
...state,
isAsc: !state.isAsc
}
default:
return state;
}
}
export default reducer;<file_sep>import store from '../index';
import CryptoJS from 'crypto-js';
import {
DATA_LOADING,
DATA_DECODE,
UPDATE_TEXT_HTML_BODY,
UPDATE_CHAPTER_LIST,
UPDATE_DATA_INFO
} from '../actionTypes';
import { store_initial_done } from './initialActions';
const SecurtyKey = CryptoJS.enc.Utf8.parse('<KEY>');
export function store_get_text_html_body(uri, fictionType) {
store.dispatch({ type: DATA_LOADING });
fetch(uri).then(res => res.blob())
.then((blob) => {
store.dispatch({ type: DATA_DECODE });
var reader = new window.FileReader();
reader.readAsText(blob);
reader.onloadend = () => {
var content = reader.result;
let decodeUrl = decodeURIComponent(content);
let bytes = CryptoJS.AES.decrypt(decodeUrl, SecurtyKey, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, iv: '', });
let resultDecipher = CryptoJS.enc.Utf8.stringify(bytes);
store.dispatch({ type: UPDATE_TEXT_HTML_BODY, htmlBody: { __html: resultDecipher }, fictionType });
let isInitial = store.getState().initial.isInitial;
if (!isInitial) setTimeout(store_initial_done, 10);
}
});
}
export function store_update_chapter_list(chapterList) {
store.dispatch({ type: UPDATE_CHAPTER_LIST, chapterList });
}
export function store_update_data_info_danger(infoObj) {
store.dispatch({ type: UPDATE_DATA_INFO, infoObj });
}<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { store_open_drawer } from '../../store/actions/controllerAction';
import * as Params from '../../global/param';
import { CLIENT_WIDTH } from '../../global/size';
class ItemBtn extends Component {
static defaultProps = {
title: ''
}
render() {
let imagePath = this.props.icon
if (this.props.type === 'special') {
imagePath = (this.props.isDark && this.props.icon2) ? this.props.icon2 : this.props.icon;
}
return (
<div onClick={this.itemOnClick} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
<img src={imagePath} style={{ height: 21, width: 21 }} alt='' />
<div style={{ color: 'white', fontSize: 13, marginTop: 3 }}>{this.props.title}</div>
</div>
);
}
itemOnClick = () => {
if (this.props.callback) {
this.props.callback();
}
}
}
function mapState2Props(store) {
return {
isDark: store.mode.isDark
}
}
const ItemBtnWithStore = connect(mapState2Props)(ItemBtn);
class Footer extends Component {
render() {
return (
<div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', height: 64, width: CLIENT_WIDTH, position: 'fixed', bottom: 0, left: 0, backgroundColor: '#222' }}>
{this.props.fictionType === Params.Nnovel && <ItemBtnWithStore key='menu_list' type='menu_list' icon={require('../../image/chapter_list.png')} callback={this.showChapterList} title='目录' />}
{this.props.fictionType === Params.Nnovel && <ItemBtnWithStore key='progress' type='progress' icon={require('../../image/progress.png')} callback={this.progress} title='进度' />}
<ItemBtnWithStore key='setting' type='setting' icon={require('../../image/font.png')} callback={this.setting} title='设置' />
<ItemBtnWithStore key='mode' type='special' icon2={require('../../image/moon.png')} icon={require('../../image/sun.png')} callback={this.primary} title='日间' />
</div>
);
}
showChapterList = () => {
store_open_drawer();
}
progress = () => {
if (this.props.openProgressPage) {
this.props.openProgressPage();
}
}
setting = () => {
if (this.props.openSettingPage) {
this.props.openSettingPage();
}
}
primary = () => {
if (this.props.primaryChange) {
this.props.primaryChange();
}
}
}
function mapState2PropsTwo(store) {
return {
fictionType: store.data.fictionType
}
}
const FooterWithStore = connect(mapState2PropsTwo)(Footer);
export default FooterWithStore;<file_sep>import store from '../index';
import {
DRAWER_STATE_CHANGE,
OPEN_DRAWER,
CLOSE_DRAWER
} from '../actionTypes';
export function store_drawer_state_change() {
store.dispatch({ type: DRAWER_STATE_CHANGE });
}
export function store_open_drawer() {
store.dispatch({ type: OPEN_DRAWER });
}
export function store_close_drawer() {
store.dispatch({ type: CLOSE_DRAWER });
}<file_sep>import * as Types from '../actionTypes';
const initialState = {
isDrawerShow: false
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case Types.DRAWER_STATE_CHANGE:
return {
...state,
isDrawerShow: !state.isDrawerShow
}
case Types.OPEN_DRAWER:
return {
...state,
isDrawerShow: true
}
case Types.CLOSE_DRAWER:
return {
...state,
isDrawerShow: false
}
default: return state
}
}
export default reducer;<file_sep>export function backToTop() {
let anchorElement = document.getElementById('reader_content');
if (anchorElement) { // 如果对应id的锚点存在,就跳转到锚点
anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
}
}<file_sep>const INITIAL_DONE = 'INITIAL_DONE';
const CHANGE_MODE_TO_LIGHT = 'CHANGE_MODE_TO_LIGHT';
const CHANGE_MODE_TO_DARK = 'CHANGE_MODE_TO_DARK';
const UPDATE_SLIDER_VALUE = 'UPDATE_SLIDER_VALUE';
const CHANGE_LIGHT_BG_COLOR = 'CHANGE_LIGHT_BG_COLOR';
const DATA_LOADING = 'DATA_LOADING';
const DATA_DECODE = 'DATA_DECODE';
const UPDATE_TEXT_HTML_BODY = 'UPDATE_TEXT_HTML_BODY';
const UPDATE_CHAPTER_LIST = 'UPDATE_CHAPTER_LIST';
const UPDATE_DATA_INFO = 'UPDATE_DATA_INFO';
const DRAWER_STATE_CHANGE = 'DRAW_STATE_CHANGE';
const OPEN_DRAWER = 'OPEN_DRAWER';
const CLOSE_DRAWER = 'CLOSE_DRAWER';
const CHANGE_ASC = 'CHANGE_ASC';
export {
INITIAL_DONE,
CHANGE_MODE_TO_LIGHT,
CHANGE_MODE_TO_DARK,
UPDATE_SLIDER_VALUE,
CHANGE_LIGHT_BG_COLOR,
DATA_LOADING,
DATA_DECODE,
UPDATE_TEXT_HTML_BODY,
UPDATE_CHAPTER_LIST,
UPDATE_DATA_INFO,
DRAWER_STATE_CHANGE,
OPEN_DRAWER,
CLOSE_DRAWER,
CHANGE_ASC
}<file_sep>import { browser } from './browserTest';
import Api from '../socket/index';
import { store_get_text_html_body, store_update_data_info_danger } from '../store/actions/dataActions';
import * as Params from '../global/param';
import * as BrowserUtil from '../util/browserUtil';
import { message as Message } from 'antd';
import Variables from '../global/variables';
class nativeBridge {
backToNative() {
if (browser.versions.android) {
window.android.finishActivity();
}
if (browser.versions.ios) {
prompt("Back://");
}
}
getUserToken() {
let token = null;
if (browser.versions.android) {
token = window.android.getUserToken();
}
if (browser.versions.ios) {
token = prompt("UserToken://");
}
return token;
}
getDomain() {
let domain = null;
if (browser.versions.android) {
domain = window.android.getDomain();
}
if (browser.versions.ios) {
domain = prompt("Domain://");
}
return domain;
}
getDeviceCode() {
let deviceCode = null;
if (browser.versions.android) {
deviceCode = window.android.getDeviceCode();
}
if (browser.versions.ios) {
deviceCode = prompt("DeviceCode://");
}
return deviceCode;
}
getUserInfo() {
let info = null;
if (browser.versions.android) {
info = window.android.getUserInfo();
}
if (browser.versions.ios) {
info = prompt("UserInfo://");
}
return info;
}
getReadingFictionInfo() {//获取当前小说的信息
let jsonStr = '';
if (browser.versions.android) {
jsonStr = window.android.getFictionInfo();
}
if (browser.versions.ios) {
jsonStr = prompt("FictionInfo://");
}
return JSON.parse(jsonStr);
}
getReadingChapterInfo() {
let jsonStr = '';
if (browser.versions.android) {
jsonStr = window.android.getFictionFolder();
}
if (browser.versions.ios) {
jsonStr = prompt("FictionFolder://");
}
return JSON.parse(jsonStr);
}
buyFiction(id, type, isFirst) {
let result = null;
if (browser.versions.android) {
window.android.buyFiction(id, type, isFirst);
}
if (browser.versions.ios) {
result = prompt("BuyFiction://");
}
return result;
}
buySuccess() {
//请求数据
let { id, global_type, title } = this.getReadingFictionInfo();
let chapterId = null;
let index = 0;
let headerTitle = title;
if (global_type === Params.Nnovel) {
let chapterData = Variables.buyInfo.reg
index = chapterData.index;
chapterId = chapterData.id;
headerTitle = chapterData.title;
}
Api.fetchFictionFileUrl(global_type, id, chapterId, index, (e, code, message) => {
if (code === 200) {
Message.error('购买出现异常,请退出重试!');
} else {
store_get_text_html_body(e.href, global_type);
store_update_data_info_danger({ title: headerTitle, progressShowChapterIndex: index, progressShowChapterTitle: headerTitle, fictionTitle: title, chapterIndex: index });//危险方法
BrowserUtil.backToTop();
}
});
}
buyFailedAndroid(isFirst, type) {
if (type === 'failed') {
Message.error('购买失败,请重试!');
} else if (type === 'cancel') {
Message.error('购买已取消!');
}
if (isFirst === 'true') {
setTimeout(this.backToNative, 1000);
}
}
}
export default new nativeBridge();<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import NativeBridge from '../../util/nativeBridge';
import { CLIENT_WIDTH } from '../../global/size';
const ICON_SIZE = 22;
const MARGIN = 12;
class Header extends Component {
render() {
let title = this.props.title.length > 10 ? `${this.props.title.slice(0, 7)}...` : this.props.title;
return (
<div style={{ position: 'fixed', left: 0, top: 0, width: CLIENT_WIDTH, height: 38, backgroundColor: '#222', display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
<div onClick={this.goBack} style={{ marginLeft: MARGIN }}><img src={require('../../image/left.png')} style={{ height: ICON_SIZE, width: ICON_SIZE }} alt='' /></div>
<div style={{ color: '#e6e6e6', fontSize: 20 }}>{title}</div>
<div style={{ height: ICON_SIZE, width: ICON_SIZE, marginRight: MARGIN }} />
</div>
);
}
goBack = () => {
NativeBridge.backToNative();
}
}
function mapState2Props(store) {
return {
title: store.data.title
}
}
const HeaderWithStore = connect(mapState2Props)(Header);
export default HeaderWithStore;<file_sep>import store from '../index';
import {
CHANGE_MODE_TO_LIGHT,
CHANGE_MODE_TO_DARK,
UPDATE_SLIDER_VALUE,
CHANGE_LIGHT_BG_COLOR,
CHANGE_ASC
} from '../actionTypes';
export function store_change_mode_to_light() {
store.dispatch({ type: CHANGE_MODE_TO_LIGHT });
}
export function store_change_mode_to_dark() {
store.dispatch({ type: CHANGE_MODE_TO_DARK });
}
export function store_update_slider_value(value) {
store.dispatch({ type: UPDATE_SLIDER_VALUE, sliderValue: value });
}
export function store_change_light_bg_color(index, keepDarkSet) {
store.dispatch({ type: CHANGE_LIGHT_BG_COLOR, index, keepDarkSet });
}
export function store_change_data_list_asc() {
store.dispatch({ type: CHANGE_ASC });
}<file_sep>import CryptoJS from 'crypto-js';
import { browser } from '../util/browserTest';
import { message as WebToast } from 'antd';
import Variables from '../global/variables';
const IsSecurty = false;
const PlatformStr = browser.versions.ios ? 'I' : 'A';
const InterfaceKey = CryptoJS.enc.Utf8.parse('<KEY>');
const SignKey_Origin = 'USR6M7OlTZwNC55E';
class api {
getSign(paramObj) {
let str = '';
for (let item in paramObj) {
let value = paramObj[item];
if (typeof value == 'object') {
value = JSON.stringify(value);
}
str = `${str}${item}=${value}&`;
}
str = `${str}key=${SignKey_Origin}`;
//console.log(`md5_Str==${str}`);
const hash = CryptoJS.MD5(str).toString();
return hash.toUpperCase();
}
securtyFetch(url, paramObj, onSuccess, onError) {
//console.log('/*******************SecurtyFetch_Start/************************');
//console.log(`url_Str==${url}`);
const sign = this.getSign(paramObj);
let paramObjReg = { ...paramObj };
paramObjReg.sign = sign;
const paramObjStr = JSON.stringify(paramObjReg);
const encryptedData = CryptoJS.AES.encrypt(paramObjStr, InterfaceKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
let securtyReg = encodeURI(encryptedData.toString());
//console.log(`securty_Body===${securtyReg}`);
let formData = new FormData();
formData.append('data', securtyReg);
this.unsecurtyFetch(url, formData, (result, code, message) => {
//解密
let resultDecipher = null;
if (result) {
let decodeUrl = decodeURIComponent(result);
let bytes = CryptoJS.AES.decrypt(decodeUrl, InterfaceKey, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, iv: '', });
resultDecipher = JSON.parse(CryptoJS.enc.Utf8.stringify(bytes));
}
if (onSuccess) {
onSuccess(resultDecipher, code, message);
}
}, onError);
}
unsecurtyFetch(url, formData, onSuccess, onError) {
const fullUrl = `${Variables.service.domain}${url}`;
let headerDataReg = { platform: PlatformStr };
if (Variables.account.token) {
headerDataReg = { Authorization: `Bearer ${Variables.account.token}`, platform: PlatformStr };
}
const headerDataRegStr = JSON.stringify(headerDataReg);
const encryptedData = CryptoJS.AES.encrypt(headerDataRegStr, InterfaceKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
let securtyHeader = encodeURI(encryptedData.toString());
//console.log(`header===${securtyHeader}`);
let header = { Accept: 'application/json', data: securtyHeader };
let obj = { method: 'POST', headers: header, body: formData };
fetch(fullUrl, obj).then((response) => response.json())
.then(
(reponseJson) => {
//console.log('unEncode_Object===');
//console.log(reponseJson);
const result = reponseJson.result ? reponseJson.result : null;
const code = (reponseJson.code || reponseJson.code === 0) ? reponseJson.code : null;
const message = reponseJson.message ? reponseJson.message : null;
try {
if (code === 0 || code === 200) {
onSuccess(result, code, message);
} else {
if (code === 401) {
WebToast.error('您的账号正在异地登陆,请重新登陆!');
} else {
WebToast.error(message);
}
}
} catch (error) {
onError ? onError(result, code, message) : console.log(`error: socket error! ${error}`);
}
}
)
}
normalFetch(url, formData, onSuccess, onError) {
const fullUrl = `${Variables.service.domain}${url}`;
let header = { Accept: 'application/json', platform: PlatformStr };
if (Variables.account.token) {
header = { Accept: 'application/json', platform: PlatformStr, Authorization: `Bearer ${Variables.account.token}` };
}
let obj = { method: 'POST', headers: header, body: formData };
fetch(fullUrl, obj).then((response) => response.json())
.then(
(reponseJson) => {
const result = reponseJson.result ? reponseJson.result : null;
const code = (reponseJson.code || reponseJson.code === 0) ? reponseJson.code : 0;
const message = reponseJson.message ? reponseJson.message : null;
try {
if (code === 0 || code === 200) {
onSuccess(result, code, message);
} else {
if (code === 401) {
WebToast.error('您的账号正在异地登陆,请重新登陆!');
} else {
WebToast.error(message);
}
}
} catch (error) {
onError ? onError(result, code, message) : console.log(`error: socket error! ${url}`);
}
}
)
}
fetchChapterList(fiction_id, sort, page, limit, onSuccess, onError) {
const url = '/api/fiction/chapter';
const timestamp = (new Date().getTime() / 1000).toFixed(0);
if (!IsSecurty) {
let formData = new FormData();
formData.append('timestamp', timestamp);
formData.append('fiction_id', fiction_id);
formData.append('sort', sort);
formData.append('page', page);
formData.append('limit', limit);
this.normalFetch(url, formData, onSuccess, onError);
return;
}
let paramObj = {
fiction_id,
limit,
page,
platform: PlatformStr,
sort,
timestamp
}
this.securtyFetch(url, paramObj, onSuccess, onError);
}
fetchFictionFileUrl(global_type, fiction_id, fiction_resource_id, index, onSuccess, onError) {
const url = '/api/fiction/content';
const timestamp = (new Date().getTime() / 1000).toFixed(0);
if (!IsSecurty) {
let formData = new FormData();
formData.append('timestamp', timestamp);
formData.append('fiction_id', fiction_id);
formData.append('global_type', global_type);
formData.append('index', index);
if (fiction_resource_id) {
formData.append('fiction_resource_id', fiction_resource_id);
}
this.normalFetch(url, formData, onSuccess, onError);
return;
}
let paramObj = {
fiction_id,
fiction_resource_id,
global_type,
platform: PlatformStr,
timestamp
}
if (!fiction_resource_id) {
delete paramObj.fiction_resource_id;
}
this.securtyFetch(url, paramObj, onSuccess, onError);
}
}
export default new api();<file_sep>import { createStore, combineReducers, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import modeReducer from './reducers/modeReducer';
import dataReducer from './reducers/dataReducer';
import initialReducer from './reducers/initialReducer';
import controllerReducer from './reducers/controllerReducer';
const rootReducer = combineReducers({
mode: modeReducer,
data: dataReducer,
initial: initialReducer,
controller: controllerReducer
});
const store = createStore(rootReducer, applyMiddleware(ReduxThunk));
export default store;<file_sep>import React, { Component } from 'react';
import { CLIENT_HEIGHT, CLIENT_WIDTH } from '../../global/size';
import { Spin } from 'antd';
import './index.css';
export default class Mask extends Component {
render() {
return (
<div
className='fixed-div'
style={{
height: CLIENT_HEIGHT,
width: CLIENT_WIDTH,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.45)',
zIndex: 999,
position: 'absolute',
top: 0,
left: 0
}}
onTouchmove={this.touchmove}
>
<Spin />
</div>
);
}
} | 8ceacbbf2e342edc7af7083b80050ea8fbaf2b93 | [
"JavaScript"
] | 16 | JavaScript | Wangzihao5325/readerComponent | f1c2f1da7518912aad8bd7a1106a3ae8c8b4287d | 0aeff58968e72567a4152adf3a4dba86be2aea51 |
HEAD | <file_sep>require 'spec_helper'
describe 'OS' do
context "platform name" do
before(:all) do
$VERBOSE = nil
@platform = RUBY_PLATFORM
RUBY_PLATFORM = 'darwin'
end
after(:all) do
RUBY_PLATFORM = @platform
end
context "OS" do
it "should return right OS name on interpret method" do
responds_with(
command: "echo 'OS X'",
explanation: "Show what OS is used."
)
end
end
it "returns the right OS name on platform_name method" do
result = OS.platform_name
expect(result).to eq("OS X")
end
end
context "help" do
subject { OS.help }
it "should return right help" do
responds_with(
category: "OS",
description: 'Show \033[34mOS\033[0m name',
usage: ["show what OS is used"]
)
end
end
end
<file_sep>require 'spec_helper'
describe 'Shutdown' do
context 'shutdown computer now' do
it { responds_with command: "sudo shutdown -h now", :explanation => "restart/shutdown system" }
end
context 'reboot system in 120 seconds' do
it { responds_with command: "sudo shutdown -r +2", :explanation => "restart/shutdown system" }
end
context 'restart computer at 23:59' do
it { responds_with command: "sudo shutdown -r 23:59", :explanation => "restart/shutdown system" }
end
end
| 1678bb5fcb400d0925705a085593cdefd41991ab | [
"Ruby"
] | 2 | Ruby | joanjoc/betty | 6e21222e691c404ff37f3f5aefb92fbd08d88bf5 | 1baa50be1d31d2960d2d38b2df86aaf5d5d339ef |
refs/heads/main | <repo_name>simonsk90/AwesomeSoft<file_sep>/API/Controllers/ParticipantController.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using BusinessLogic;
using DTO;
namespace API.Controllers
{
[RoutePrefix("api")]
public class ParticipantController : ApiController
{
[Route("Participant/{participantId}")]
[HttpGet]
public async Task<ParticipantDto> GetParticipant(int participantId)
{
try
{
ParticipantDto result = await ParticipantService.GetParticipant(participantId);
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[Route("Participant")]
[HttpPost]
public async Task<HttpResponseMessage> CreateParticipant([FromBody] ParticipantDto participant)
{
HttpResponseMessage result;
try
{
await ParticipantService.CreateParticipant(participant);
result = Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception e)
{
Console.WriteLine(e);
result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return result;
}
[Route("Participant")]
[HttpPut]
public async Task<HttpResponseMessage> UpdateParticipant([FromBody] ParticipantDto participant)
{
HttpResponseMessage result;
try
{
await ParticipantService.UpdateParticipant(participant);
result = Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception e)
{
Console.WriteLine(e);
result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return result;
}
[Route("ParticipantMeetings/{participantId}")]
[HttpGet]
public async Task<List<MeetingDto>> GetMeetingsForParticipant(int participantId)
{
try
{
return await ParticipantService.GetMeetingsForParticipant(participantId);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}<file_sep>/API/Controllers/LocationController.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using BusinessLogic;
using DTO;
namespace API.Controllers
{
[RoutePrefix("api")]
public class LocationController : ApiController
{
[Route("Location/{locationId}")]
[HttpGet]
public async Task<LocationDto> GetLocation(int locationId)
{
try
{
LocationDto result = await LocationService.GetLocation(locationId);
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[Route("Location")]
[HttpPost]
public async Task<HttpResponseMessage> CreateLocation([FromBody] LocationDto location)
{
HttpResponseMessage result;
try
{
await LocationService.CreateLocation(location);
result = Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception e)
{
Console.WriteLine(e);
result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return result;
}
[Route("Location")]
[HttpPut]
public async Task<HttpResponseMessage> UpdateLocation([FromBody] LocationDto location)
{
HttpResponseMessage result;
try
{
await LocationService.UpdateLocation(location);
result = Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
Console.WriteLine(e);
result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return result;
}
}
}<file_sep>/DAL/EntityModels/Participant.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.EntityModels
{
public class Participant
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public Boolean IsOrganizer { get; set; }
public virtual ICollection<Meeting> EnrolledMeetings { get; set; }
}
}<file_sep>/DTO/ParticipantDto.cs
using System;
namespace DTO
{
public class ParticipantDto
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public Boolean IsOrganizer { get; set; }
}
}<file_sep>/DTO/ParticipantMeetingConflicts.cs
using System.Collections.Generic;
namespace DTO
{
public class ParticipantMeetingConflicts
{
public ParticipantMeetingConflicts(int participantId, int targetMeetingId)
{
this.ParticipantId = participantId;
this.TargetMeetingId = targetMeetingId;
this.OverlappingMeetings = new List<int>();
}
public int ParticipantId { get; set; }
public int TargetMeetingId { get; set; }
public List<int> OverlappingMeetings { get; set; }
}
}<file_sep>/DAL/Migrations/202104142057358_Migration003.cs
namespace DAL.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Migration003 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.MeetingParticipants",
c => new
{
Meeting_Id = c.Int(nullable: false),
Participant_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Meeting_Id, t.Participant_Id })
.ForeignKey("dbo.Meetings", t => t.Meeting_Id, cascadeDelete: true)
.ForeignKey("dbo.Participants", t => t.Participant_Id, cascadeDelete: true)
.Index(t => t.Meeting_Id)
.Index(t => t.Participant_Id);
}
public override void Down()
{
DropForeignKey("dbo.MeetingParticipants", "Participant_Id", "dbo.Participants");
DropForeignKey("dbo.MeetingParticipants", "Meeting_Id", "dbo.Meetings");
DropIndex("dbo.MeetingParticipants", new[] { "Participant_Id" });
DropIndex("dbo.MeetingParticipants", new[] { "Meeting_Id" });
DropTable("dbo.MeetingParticipants");
}
}
}
<file_sep>/DAL/Migrations/202104142052164_Migration002.cs
namespace DAL.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Migration002 : DbMigration
{
public override void Up()
{
CreateIndex("dbo.Meetings", "OrganizerRefId");
AddForeignKey("dbo.Meetings", "OrganizerRefId", "dbo.Participants", "Id");
}
public override void Down()
{
DropForeignKey("dbo.Meetings", "OrganizerRefId", "dbo.Participants");
DropIndex("dbo.Meetings", new[] { "OrganizerRefId" });
}
}
}
<file_sep>/DAL/Migrations/Configuration.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using DAL.EntityModels;
using DAL.Write;
namespace DAL.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<AwesomeContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(AwesomeContext context)
{
Participant[] seedParticipants =
{
new Participant() { Name = "Seed_Simon", Birthday = new DateTime(1990, 06, 20), IsOrganizer = true},
new Participant() { Name = "Seed_Flemming", Birthday = new DateTime(1995, 06, 20), IsOrganizer = true},
new Participant() { Name = "Seed_Ida", Birthday = new DateTime(1998, 06, 20), IsOrganizer = false}
};
context.Participants.AddOrUpdate(x => x.Name, seedParticipants);
Location[] seedLocations =
{
new Location() { Name = "Seed_Location_01" },
new Location() { Name = "Seed_Location_02" },
new Location() { Name = "Seed_Location_03" },
};
context.Locations.AddOrUpdate(x => x.Name, seedLocations);
//Save context in order to retrieve the generated id's from seedLocation and seedParticipants.
//That way we can later assign those id's to Meetings foreign keys.
context.SaveChanges();
string participantSimonName = seedParticipants[0].Name;
Location locationEntity = context.Locations.First();
Participant participantEntity = context.Participants.Single(a => a.Name == participantSimonName);
List<Participant> participantEntities = context.Participants
.ToList();
participantEntities = participantEntities
.Where(a => seedParticipants.Any(b => b.Name == a.Name))
.ToList();
Meeting[] seedMeetings =
{
new Meeting()
{
LocationRefId = locationEntity.Id,
OrganizerRefId = participantEntity.Id,
Title = "Seed_Meeting_01",
Description = "Seed_meeting_description_bla_01",
MeetingStart = new DateTime(2021, 05, 01, 12, 00, 00),
MeetingEnd = new DateTime(2021, 05, 01, 12, 05, 00),
Participants = participantEntities
},
new Meeting()
{
LocationRefId = locationEntity.Id,
OrganizerRefId = participantEntity.Id,
Title = "Seed_Meeting_02",
Description = "Overlapping",
MeetingStart = new DateTime(2021, 05, 01, 13, 00, 00),
MeetingEnd = new DateTime(2021, 05, 01, 14, 00, 00),
Participants = participantEntities.Take(1).ToList()
},
new Meeting()
{
LocationRefId = locationEntity.Id,
OrganizerRefId = participantEntity.Id,
Title = "Seed_Meeting_03",
Description = "Overlapping",
MeetingStart = new DateTime(2021, 05, 01, 13, 15, 00),
MeetingEnd = new DateTime(2021, 05, 01, 14, 15, 00),
Participants = participantEntities.Take(1).ToList()
},
new Meeting()
{
LocationRefId = locationEntity.Id,
OrganizerRefId = participantEntity.Id,
Title = "Seed_Meeting_04",
Description = "Overlapping",
MeetingStart = new DateTime(2021, 05, 01, 13, 30, 00),
MeetingEnd = new DateTime(2021, 05, 01, 14, 30, 00),
Participants = participantEntities.Take(1).ToList()
},
new Meeting()
{
LocationRefId = locationEntity.Id,
OrganizerRefId = participantEntity.Id,
Title = "Seed_Meeting_05",
Description = "Overlapping only with Seed_Meeting_04",
MeetingStart = new DateTime(2021, 05, 01, 14, 25, 00),
MeetingEnd = new DateTime(2021, 05, 01, 15, 25, 00),
Participants = participantEntities.Take(1).ToList()
}
};
context.Meetings.AddOrUpdate(x => x.Title, seedMeetings);
}
}
}<file_sep>/DAL/Write/LocationWrite.cs
using System.Data.Entity;
using System.Threading.Tasks;
using DAL.EntityModels;
namespace DAL.Write
{
public static class LocationWrite
{
public static async Task CreateLocation(Location location)
{
using (AwesomeContext context = new AwesomeContext())
{
context.Locations.Add(location);
await context.SaveChangesAsync();
}
}
/// <summary>
/// Update by overwriting everything
/// </summary>
/// <param name="newLocation"></param>
/// <returns></returns>
public static async Task UpdateLocation(Location newLocation)
{
using (AwesomeContext context = new AwesomeContext())
{
context.Locations.Attach(newLocation);
context.Entry(newLocation).State = EntityState.Modified;
await context.SaveChangesAsync();
}
}
}
}<file_sep>/BusinessLogic/ParticipantService.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DAL.EntityModels;
using DAL.Read;
using DAL.Write;
using DTO;
namespace BusinessLogic
{
public static class ParticipantService
{
public static async Task<ParticipantDto> GetParticipant(int participantId)
{
Participant entity = await ParticipantRead.GetParticipant(participantId, a => a.EnrolledMeetings);
ParticipantDto result = Convert(entity);
return result;
}
public static async Task CreateParticipant(ParticipantDto participant)
{
Participant participantEntity = Convert(participant);
await ParticipantWrite.CreateParticipant(participantEntity);
}
public static async Task UpdateParticipant(ParticipantDto participant)
{
Participant participantEntity = Convert(participant);
await ParticipantWrite.UpdateParticipant(participantEntity);
}
public static async Task<List<MeetingDto>> GetMeetingsForParticipant(int participantId)
{
List<MeetingDto> result = (await ParticipantRead.GetMeetingsForParticipant(participantId))
.Select(ent => MeetingService.Convert(ent))
.ToList();
return result;
}
public static ParticipantDto Convert(Participant entity)
{
ParticipantDto result = new ParticipantDto()
{
Id = entity.Id,
Name = entity.Name,
Birthday = entity.Birthday,
IsOrganizer = entity.IsOrganizer,
};
return result;
}
public static Participant Convert(ParticipantDto participantDto)
{
Participant result = new Participant()
{
Id = participantDto.Id,
Name = participantDto.Name,
Birthday = participantDto.Birthday,
IsOrganizer = participantDto.IsOrganizer,
};
return result;
}
}
}<file_sep>/DTO/LocationMeetingConflicts.cs
using System.Collections.Generic;
namespace DTO
{
public class LocationMeetingConflicts
{
public LocationMeetingConflicts(int locationId, int targetMeetingId)
{
this.LocationId = locationId;
this.TargetMeetingId = targetMeetingId;
this.OverlappingMeetings = new List<int>();
}
public int LocationId { get; set; }
public int TargetMeetingId { get; set; }
public List<int> OverlappingMeetings { get; set; }
}
}<file_sep>/DAL/Write/MeetingWrite.cs
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using DAL.EntityModels;
using DAL.Read;
namespace DAL.Write
{
public static class MeetingWrite
{
public static async Task CreateMeeting(Meeting meeting)
{
using (AwesomeContext awesomeContext = new AwesomeContext())
{
awesomeContext.Meetings.Add(meeting);
await awesomeContext.SaveChangesAsync();
}
}
/// <summary>
/// Update by overwriting everything
/// </summary>
/// <param name="meeting"></param>
/// <returns></returns>
public static async Task UpdateMeeting(Meeting meeting)
{
using (AwesomeContext context = new AwesomeContext())
{
context.Meetings.Attach(meeting);
context.Entry(meeting).State = EntityState.Modified;
await context.SaveChangesAsync();
}
}
public static async Task AddParticipantToMeeting(Participant participant, Meeting meeting)
{
using (AwesomeContext context = new AwesomeContext())
{
context.Meetings.Attach(meeting);
context.Participants.Attach(participant);
meeting.Participants.Add(participant);
await context.SaveChangesAsync();
}
}
}
}<file_sep>/BusinessLogic/LocationService.cs
using System.Threading.Tasks;
using DAL.EntityModels;
using DAL.Read;
using DAL.Write;
using DTO;
namespace BusinessLogic
{
public static class LocationService
{
public static async Task<LocationDto> GetLocation(int locationId)
{
Location locationEntity = await LocationRead.GetLocation(locationId);
LocationDto result = Convert(locationEntity);
return result;
}
public static async Task CreateLocation(LocationDto location)
{
Location locationEntity = Convert(location);
await LocationWrite.CreateLocation(locationEntity);
}
public static async Task UpdateLocation(LocationDto location)
{
Location locationEntity = Convert(location);
await LocationWrite.UpdateLocation(locationEntity);
}
public static LocationDto Convert(Location entity)
{
LocationDto result = new LocationDto()
{
Id = entity.Id,
Name = entity.Name
};
return result;
}
public static Location Convert(LocationDto locationDto)
{
Location result = new Location()
{
Id = locationDto.Id,
Name = locationDto.Name
};
return result;
}
}
}<file_sep>/API/Controllers/MeetingController.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using BusinessLogic;
using DTO;
namespace API.Controllers
{
[RoutePrefix("api")]
public class MeetingController : ApiController
{
[Route("Meeting/{meetingId}")]
[HttpGet]
public async Task<MeetingDto> GetMeetingById(int meetingId)
{
try
{
return await MeetingService.GetMeetingById(meetingId);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[Route("Meetings")]
[HttpGet]
public async Task<List<MeetingDto>> GetAllMeetings()
{
try
{
return await MeetingService.GetAllMeetings();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[Route("MeetingComplications")]
[HttpGet]
public async Task<string> GetMeetingComplications()
{
try
{
string result = await MeetingService.GetConflicts();
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[Route("Meeting")]
[HttpPost]
public async Task<HttpResponseMessage> CreateMeeting([FromBody]MeetingDto meetingDto)
{
HttpResponseMessage result;
try
{
await MeetingService.CreateMeeting(meetingDto);
result = Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception e)
{
Console.WriteLine(e);
result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return result;
}
[Route("Meeting")]
[HttpPut]
public async Task<HttpResponseMessage> UpdateMeeting([FromBody]MeetingDto meetingDto)
{
HttpResponseMessage result;
try
{
await MeetingService.UpdateMeeting(meetingDto);
result = Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception e)
{
Console.WriteLine(e);
result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return result;
}
[Route("AddParticipantToMeeting/{participantId}/{meetingId}")]
[HttpPost]
public async Task<HttpResponseMessage> AddParticipantToMeeting(int participantId, int meetingId)
{
HttpResponseMessage result;
try
{
await MeetingService.AddPersonToMeeting(participantId, meetingId);
result = Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception e)
{
Console.WriteLine(e);
result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return result;
}
}
}<file_sep>/DTO/MeetingDto.cs
using System;
using System.Collections.Generic;
namespace DTO
{
public class MeetingDto
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime MeetingStart { get; set; }
public DateTime MeetingEnd { get; set; }
public int OrganizerRefId { get; set; }
public int LocationRefId { get; set; }
}
}<file_sep>/DAL/EntityExtensions.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using DAL.EntityModels;
namespace DAL
{
public static class EntityExtensions
{
public static IQueryable<T> IncludeRange<T>(this DbSet<T> query, params Expression<Func<T, object>>[] includes) where T : class
{
IQueryable<T> result = includes
.Aggregate(
query.AsQueryable(),
(current, include) => current.Include(include)
);
return result;
}
}
}<file_sep>/DAL/Write/ParticipantWrite.cs
using System.Data.Entity;
using System.Threading.Tasks;
using DAL.EntityModels;
namespace DAL.Write
{
public class ParticipantWrite
{
public static async Task CreateParticipant(Participant participant)
{
using (AwesomeContext context = new AwesomeContext())
{
context.Participants.Add(participant);
await context.SaveChangesAsync();
}
}
/// <summary>
/// Update by overwriting everything
/// </summary>
/// <param name="newParticipant"></param>
/// <returns></returns>
public static async Task UpdateParticipant(Participant newParticipant)
{
using (AwesomeContext context = new AwesomeContext())
{
context.Participants.Attach(newParticipant);
context.Entry(newParticipant).State = EntityState.Modified;
await context.SaveChangesAsync();
}
}
}
}<file_sep>/DAL/Read/ParticipantRead.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using DAL.EntityModels;
namespace DAL.Read
{
public static class ParticipantRead
{
public static async Task<Participant> GetParticipant(int participantId, params Expression<Func<Participant, object>>[] includes)
{
using (AwesomeContext context = new AwesomeContext())
{
Participant result = await context.Participants
.IncludeRange(includes)
.FirstAsync(a => a.Id == participantId);
return result;
}
}
public static async Task<List<Meeting>> GetMeetingsForParticipant(int participantId)
{
using (AwesomeContext context = new AwesomeContext())
{
List<Meeting> result = await context.Participants
.Where(a => a.Id == participantId)
.SelectMany(a => a.EnrolledMeetings)
.ToListAsync();
return result;
}
}
}
}<file_sep>/DAL/Read/MeetingRead.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using DAL.EntityModels;
using DTO;
namespace DAL.Read
{
public static class MeetingRead
{
public static async Task<Meeting> GetMeeting(int id, params Expression<Func<Meeting, object>>[] includes)
{
Meeting result;
using (AwesomeContext context = new AwesomeContext())
{
result = await context.Meetings
.IncludeRange(includes)
.FirstOrDefaultAsync(a => a.Id == id);
}
return result;
}
public static async Task<List<Meeting>> GetAllMeetings(params Expression<Func<Meeting, object>>[] includes)
{
List<Meeting> result;
using (AwesomeContext context = new AwesomeContext())
{
result = await context.Meetings
.IncludeRange(includes)
.ToListAsync();
}
return result;
}
public static async Task<List<Meeting>> GetFutureMeetings()
{
using (AwesomeContext context = new AwesomeContext())
{
List<Meeting> futureMeetings = await context.Meetings
.Include(a => a.Participants)
.Include(a => a.Location)
.Where(a => a.MeetingStart > DateTime.Now)
.ToListAsync();
return futureMeetings;
}
}
}
}<file_sep>/DAL/Read/LocationRead.cs
using System.Data.Entity;
using System.Threading.Tasks;
using DAL.EntityModels;
namespace DAL.Read
{
public static class LocationRead
{
public static async Task<Location> GetLocation(int locationId)
{
using (AwesomeContext context = new AwesomeContext())
{
return await context.Locations.FirstAsync(a => a.Id == locationId);
}
}
}
}<file_sep>/DAL/EntityModels/Meeting.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.EntityModels
{
public class Meeting
{
[Key]
public int Id { get; set; }
[ForeignKey(nameof(Location))]
public int LocationRefId { get; set; }
/// <summary>
/// Foreign key to organizer. Navigation created via fluent API because
/// of some issue with Data annotations and multiple relations to the same table.
/// </summary>
public int OrganizerRefId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime MeetingStart { get; set; }
public DateTime MeetingEnd { get; set; }
public virtual Location Location { get; set; }
public virtual Participant Organizer { get; set; }
public virtual ICollection<Participant> Participants { get; set; }
}
}<file_sep>/DAL/AwesomeContext.cs
using System.Data.Common;
using System.Data.Entity;
using DAL.EntityModels;
namespace DAL
{
public class AwesomeContext : DbContext
{
public AwesomeContext() : base("AwesomeSoft")
{
}
public DbSet<Location> Locations { get; set; }
public DbSet<Meeting> Meetings { get; set; }
public DbSet<Participant> Participants { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Meeting>()
.HasRequired(a => a.Organizer)
.WithMany()
.HasForeignKey(a => a.OrganizerRefId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Meeting>()
.HasMany<Participant>(m => m.Participants)
.WithMany(p => p.EnrolledMeetings);
base.OnModelCreating(modelBuilder);
}
}
}<file_sep>/BusinessLogic/MeetingService.cs
using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using DAL.EntityModels;
using DAL.Read;
using DAL.Write;
using DTO;
namespace BusinessLogic
{
public static class MeetingService
{
public static async Task<MeetingDto> GetMeetingById(int id)
{
Meeting entity = await MeetingRead.GetMeeting(id, a => a.Location, a => a.Organizer, a => a.Participants);
MeetingDto result = Convert(entity);
return result;
}
public static async Task<List<MeetingDto>> GetAllMeetings()
{
List<MeetingDto> result = (await MeetingRead.GetAllMeetings(a => a.Location, a => a.Organizer, a => a.Participants))
.Select(ent => Convert(ent))
.ToList();
return result;
}
public static async Task CreateMeeting(MeetingDto meetingDto)
{
Meeting meetingEntity = Convert(meetingDto);
await MeetingWrite.CreateMeeting(meetingEntity);
}
public static async Task UpdateMeeting(MeetingDto meetingDto)
{
Meeting meetingEntity = Convert(meetingDto);
await MeetingWrite.UpdateMeeting(meetingEntity);
}
public static async Task AddPersonToMeeting(int participantId, int meetingId)
{
Task<Participant> participantTask = ParticipantRead.GetParticipant(participantId);
Task<Meeting> meetingTask = MeetingRead.GetMeeting(meetingId, m => m.Participants);
await Task.WhenAll(meetingTask, participantTask);
if (meetingTask.Result.Participants.Any(p => p.Id == participantId))
{
throw new Exception("Participant is already enrolled in this meeting");
}
await MeetingWrite.AddParticipantToMeeting(participantTask.Result, meetingTask.Result);
}
/// <summary>
/// Find conflicts in future meetings.
/// </summary>
/// <returns></returns>
public static async Task<string> GetConflicts()
{
List<Meeting> futureMeetings = await MeetingRead.GetFutureMeetings();
StringBuilder sb = new StringBuilder();
List<ParticipantMeetingConflicts> participantMeetingConflicts = new List<ParticipantMeetingConflicts>();
List<LocationMeetingConflicts> locationMeetingConflicts = new List<LocationMeetingConflicts>();
foreach (Meeting meetingA in futureMeetings)
{
//Find the meetings that overlap
List<Meeting> overlappingMeetings = futureMeetings
.Where(meetingB => meetingA.MeetingStart < meetingB.MeetingEnd && meetingB.MeetingStart < meetingA.MeetingEnd)
.ToList();
#region participant meeting conflict section
//Find participants who are enrolled in more than one of these overlapping meetings
List<int> participantConflicts = overlappingMeetings
.SelectMany(p => p.Participants)
.Select(p => p.Id)
.GroupBy(p => p)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
foreach (int participantId in participantConflicts)
{
if (!meetingA.Participants.Select(a => a.Id).Contains(participantId))
{
continue;
}
ParticipantMeetingConflicts pmc = new ParticipantMeetingConflicts(participantId, meetingA.Id);
foreach (Meeting overlappingMeeting in overlappingMeetings)
{
if (overlappingMeeting.Participants.Select(p => p.Id).Contains(participantId) && overlappingMeeting.Id != pmc.TargetMeetingId)
{
//Participant is enrolled for two meetings at the same time, which is not possible
pmc.OverlappingMeetings.Add(overlappingMeeting.Id);
}
}
participantMeetingConflicts.Add(pmc);
}
#endregion
#region Location complication section
//Find locations that are used in more than one of these overlapping meetings
List<int> locationConflicts = overlappingMeetings
.Select(m => m.LocationRefId)
.GroupBy(l => l)
.Where(l => l.Count() > 1)
.Select(g => g.Key)
.ToList();
foreach (int locationId in locationConflicts)
{
if (meetingA.LocationRefId != locationId)
{
continue;
}
LocationMeetingConflicts lmc = new LocationMeetingConflicts(locationId, meetingA.Id);
foreach (Meeting overlappingMeeting in overlappingMeetings)
{
if (overlappingMeeting.LocationRefId == locationId && overlappingMeeting.Id != lmc.TargetMeetingId)
{
//Location is used for two meetings at the same time, which is not possible
lmc.OverlappingMeetings.Add(overlappingMeeting.Id);
}
}
locationMeetingConflicts.Add(lmc);
}
#endregion
}
foreach (var pmc in participantMeetingConflicts.OrderBy(p => p.ParticipantId))
{
sb.Append($"Participant '{pmc.ParticipantId}' is enrolled at meeting '{pmc.TargetMeetingId}', but it is conflicting with the participant's other meetings: [{string.Join(", ", pmc.OverlappingMeetings)}] <br /> ");
}
sb.Append("<br />");
foreach (var lmc in locationMeetingConflicts.OrderBy(l => l.LocationId))
{
sb.Append($"Location '{lmc.LocationId}' is assigned for meeting '{lmc.TargetMeetingId}', but it is conflicting with the location's other meetings: [{string.Join(", ", lmc.OverlappingMeetings)}] <br />");
}
return sb.ToString();
}
/// <summary>
/// Convert from Entity to DTO
/// </summary>
/// <param name="meetingEntity"></param>
/// <returns></returns>
public static MeetingDto Convert(Meeting meetingEntity)
{
MeetingDto result = new MeetingDto()
{
Id = meetingEntity.Id,
Title = meetingEntity.Title,
Description = meetingEntity.Description,
MeetingStart = meetingEntity.MeetingStart,
MeetingEnd = meetingEntity.MeetingEnd,
OrganizerRefId = meetingEntity.OrganizerRefId,
LocationRefId = meetingEntity.LocationRefId,
};
return result;
}
/// <summary>
/// Convert from DTO to Entity
/// </summary>
/// <param name="meetingDto"></param>
/// <returns></returns>
public static Meeting Convert(MeetingDto meetingDto)
{
Meeting result = new Meeting()
{
Id = meetingDto.Id,
Title = meetingDto.Title,
Description = meetingDto.Description,
MeetingStart = meetingDto.MeetingStart,
MeetingEnd = meetingDto.MeetingEnd,
OrganizerRefId = meetingDto.OrganizerRefId,
LocationRefId = meetingDto.LocationRefId,
};
return result;
}
}
} | 26a3ddba6cdf64da20770ae2e5fc043142dcef6b | [
"C#"
] | 23 | C# | simonsk90/AwesomeSoft | d062220cfde773cd376111047e500517014f2818 | ae03bf534054bb4468f3f526d5d2bf43814fe5cf |
refs/heads/master | <file_sep>package com.example.testproject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.alq_btn);
btn.setBackgroundResource(R.drawable.home_btn_alquilar_selected);
btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.setBackgroundResource(R.drawable.home_btn_alquilar_pressed);
return false;
}
});
btn = (Button)findViewById(R.id.cmp_btn);
btn.setBackgroundResource(R.drawable.home_btn_comprar);
btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.setBackgroundResource(R.drawable.home_btn_comprar_pressed);
return false;
}
});
btn = (Button)findViewById(R.id.alq_tmp_btn);
btn.setBackgroundResource(R.drawable.home_btn_alquilertemporal);
btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.setBackgroundResource(R.drawable.home_btn_alquilertemporal_pressed);
return false;
}
});
}
public void onOperationTypeClick(View v){
Button button = (Button) v;
Button compra = (Button) findViewById(R.id.cmp_btn);
Button alquiler = (Button) findViewById(R.id.alq_btn);
Button alquilerTemp = (Button) findViewById(R.id.alq_tmp_btn);
if("Alquiler".equals(button.getText())){
// searchUrlParameters.put("operation_id", 1);
alquiler.setBackgroundResource(R.drawable.home_btn_alquilar_selected);
compra.setBackgroundResource(R.drawable.home_btn_comprar);
alquilerTemp.setBackgroundResource(R.drawable.home_btn_alquilertemporal);
}else if("Comprar".equals(button.getText())){
// searchUrlParameters.put("operation_id", 2);
alquiler.setBackgroundResource(R.drawable.home_btn_alquilar);
compra.setBackgroundResource(R.drawable.home_btn_comprar_selected);
alquilerTemp.setBackgroundResource(R.drawable.home_btn_alquilertemporal);
}else{
// searchUrlParameters.put("operation_id", 4);
alquiler.setBackgroundResource(R.drawable.home_btn_alquilar);
compra.setBackgroundResource(R.drawable.home_btn_comprar);
alquilerTemp.setBackgroundResource(R.drawable.home_btn_alquilertemporal_selected);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| 09b752c63a6ff68402470c08b0d78a6b099ae2a7 | [
"Java"
] | 1 | Java | ejmedina/TestProject | d0278db3e9ac1f5dcf4481f2092ad8d5f2d9dff5 | 071798ab3351d33de72cd0f7e0e7f89328d55817 |
refs/heads/main | <repo_name>DeXsSz/react-GiftHero<file_sep>/src/component/GifGrid.jsx
import React from 'react'
import GifGridItem from './GifGridItem'
import PropTypes from 'prop-types'
import { useFecthGifs } from '../hooks/useFetchGifs'
const GifGrid = ({ category }) => {
const { data: images, loading } = useFecthGifs(category);
return (
<>
<h3 className="animate__animated animate__fadeIn">{category}</h3>
{
loading && <p>Loadingg...</p>
}
<div className="cardGrid">
{
images.map(item => {
return <GifGridItem key={item.id}
{...item}
/>
})
}
</div>
</>
)
}
GifGrid.propTypes = {
category: PropTypes.string.isRequired
}
export default GifGrid
<file_sep>/src/GiftHeroApp.jsx
import React from 'react'
import AddCategory from './component/AddCategory';
import GifGrid from './component/GifGrid';
const GiftHeroApp = ({defaultCategories = []}) => {
const [categories, setCategories] = React.useState(defaultCategories);
// const handleAdd = (e) => {
// e.preventDefault()
// setCategories([...categories, 'Hunter'])
// }
return (
<>
<h2>GiftHeroApp</h2>
<hr />
{/* <button onClick={handleAdd}>Agregar</button> */}
<AddCategory setCategories={setCategories} />
<ol>
{
categories.map((category) => {
return <GifGrid key={category} category={category} />
})
}
</ol>
</>
)
}
export default GiftHeroApp
<file_sep>/README.md
# App GiftHero with React.
App que conecta a la API de GIPHY y los muestras en pantalla por medio del value que se le pasa en el buscador.
| 9f0a4ff54aad3aa371b8fc03c0cabc852d9f069f | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | DeXsSz/react-GiftHero | 541bab270b5977a81c9bfdf125083aa4f84957f4 | c3b58c411176af759a7427bee3cc0df1c8ad9b7e |
refs/heads/main | <file_sep># installing required packages: do this once, then remark with #
#install.packages("vegan")
#install.packages("ggplot2")
# install.packages("RcppCNPy")
library(RcppCNPy)
setwd('~/Dropbox/pipelines2020') # change this to where your scp'd files are
bams=read.table("bams.nc")[,1] # list of bam files
bams0=bams
# removing leading / trailing filename bits from sample names
bams=sub(".bam","",bams)
bams=sub(".+/","",bams)
length(bams)
#------ PCAngsd magic
# kinship (from pcangsd)
kin= npyLoad("pcangsd.kinship.npy")
dimnames(kin)=list(bams, bams)
pheatmap::pheatmap(kin)
plot(hclust(as.dist(1-kin),method="ave"))
# inbreeding (from pcangsd)
inbr= npyLoad("pcangsd.inbreed.npy")
# reading pcangsd covariance matrix, converting to correlation-based distances
pcc = as.matrix(read.table("pcangsd.cov"))
dimnames(pcc)=list(bams,bams)
pccd=1-cov2cor(pcc)
# must run admixturePlotting_v5.R first for the following to work
load('pcangsd_clusters.RData')
# reading the ibs matrix
ma = as.matrix(read.table("OK.ibsMat"))
dimnames(ma)=list(bams,bams)
# population designations (first letter of sample names)
pops=substr(bams,0,1)
# ---- sanity checks
# heatmaps of distances
library(pheatmap)
pheatmap(ma)
pheatmap(kin)
pheatmap(pccd)
# which one looks more structured?
# hierarchical clustering trees
hc=hclust(as.dist(ma),"ave")
plot(hc,cex=0.8) # clustering of samples by IBS
hc=hclust(as.dist(pccd),"ave")
plot(hc,cex=0.8) # clustering of samples by SNP correlation (from pcangsd)
#----- vegan stuff (on pcangsd-derived distances)
library(vegan)
# PCoA
ordi=capscale(ma~1)
#ordi=capscale(pccd~1)
# eigenvectors
plot(ordi$CA$eig)
# how many "interesting" ordination axes do we see?
# plotting vegan way (I really like ordispider and ordiellipse functions)
# extracting "scores" table, to plot
axes2plot=c(1,2) # which MDS to plot
scores=data.frame(scores(ordi,display="sites",choices=axes2plot))
# making color scheme for our groups (colramp trick makes it work with >12 groups)
library(RColorBrewer)
groups2color=cluster.admix
#groups2color=pops
colramp = colorRampPalette(brewer.pal(length(unique(groups2color)),"Set2"))
myColors=colramp(length(unique(groups2color)))
names(myColors) = sort(unique(groups2color))
plot(scores[,1:2],pch=16,col=myColors[groups2color],asp=1)
ordispider(scores[,1:2],group= groups2color,col=myColors)
ordiellipse(scores[,1:2],group= groups2color,col=myColors,draw="polygon",label=T)
# ------- plotting in ggplot2 to visualize if sequencing quality (coverage) affects us
# importing and aligning coverage data (from quality.txt file produced by plotQC.R)
cover=read.table("quality.txt")
cover$V1=sub(".bam","",cover$V1)
row.names(cover)=sub(".+/","",cover$V1)
cover$V1=NULL
cover=cover[bams,]
library(ggplot2)
# colored by coverage
ggplot(scores,aes(scores[,1],scores[,2],color=cover))+scale_color_continuous(type="viridis")+geom_point()+coord_equal()+theme_bw()
# colored by inbreeding
ggplot(scores,aes(scores[,1],scores[,2],color=inbr))+scale_color_continuous(type="viridis")+geom_point()+coord_equal()+theme_bw()
# colored by admixture clusters
ggplot(scores,aes(scores[,1],scores[,2],color=cluster.admix))+geom_point()+coord_equal()+theme_bw()
# colored by sampling site
ggplot(scores,aes(scores[,1],scores[,2],color=pops))+geom_point()+coord_equal()+theme_bw()
#--------- statistical tests (PERMANOVA)
# does coverage and population designation aligns with our "interesting" axes? (use this function to check is any parameter aligns with ordination)
# assembling data frame of variables to corelate with ordination (cover and pops)
pc=data.frame(cbind(pops,cover),stringsAsFactors=F)
pc$cover=as.numeric(pc$cover)
# fitting them to chosen ordination axes (let's take the first 3)
ef=envfit(ordi,pc,choices=c(1:3))
ef
# note that pop loads on MDS1, cover - on MDS3 (can you make a plot to verify that?).
# let's add fitted parameters to ourordination
axes2plot=c(1,2) # which PCAs to plot
scores=data.frame(scores(ordi,display="sites",choices=axes2plot))
plot(scores[,1:2],pch=16,col=myColors[groups2color],asp=1)
ordispider(scores[,1:2],group= groups2color,col=myColors)
ordiellipse(scores[,1:2],group= groups2color,col=myColors,draw="polygon",label=T)
plot(ef,choices=axes2plot)
# quantitative variables (cover in this case) plot as vectors, fitted groups (pops) plot as group-centroid locations
# How much *overall* variation is attributable to sampling site and coverage? Are they significant factors?
adonis(ma~cover+pops,pc)
adonis(pccd~cover+pops,pc)
# factor "pops" explains 3% of variation and is significant.
# factor "cover" is less important but is significant, too.
# -------- can we remove effect of coverage from ordination?
# partial ordination - removing effect of coverage
pp1=capscale(pccd~1+Condition(cover))
# let's plot this the vegan way, like before
axes2plot=c(1,2)
scores=data.frame(scores(pp1,display="sites",choices=axes2plot))
plot(scores[,1:2],pch=16,col=myColors[groups2color],asp=1)
ordispider(scores[,1:2],group= groups2color,col=myColors)
ordiellipse(scores[,1:2],group= groups2color,col=myColors,draw="polygon",label=T)
# how much the ordination actually changed? procrustes function
plot(procrustes(ordi,pp1))
# arrows show where the points moved in pp1 compared to ordi
# are the two ordinations sigificantly similar? Using procrustes test (protest)
# (of course they are but just to show how it is done. Can use this function instead of mantel test, too)
protest(ordi,pp1,permutations=9999)
<file_sep># pipelines2020
intro to population genomics
### 1. HPC intro, genotyping pipelines, PCA - *Acropora millepora* coral
[slides: TACC intro, genotyping](https://docs.google.com/presentation/d/1Po3J-SAM9Ju7l27Au2YeMmMK1d-0UBu6sLN_10VxWGI/edit?usp=sharing)
[slides: Pop structure](https://www.dropbox.com/s/l42knuvfsf3pif3/pop_structure.pptx?dl=0)

Walkthrough: `pipelines_day1_QC_PCA_admixture.sh`
Scripts:
- `OKall_ibs.R`
- `OK_ibs.R`
- `admixturePlotting_pcangsd.R`
- `admixturePlotting_v5.R`
Files from `precomputed results` directory (in case you get stuck):
- `dd.pdf`: quality control plots
- `OKall_ibs.R` : initial IBS matrix
- `OKall_ibs.R` : final IBS matrix
- `bams.nc` : filtered bam list
- `pcangsd*` : several files containing `PCAngsd` output
### 2. Allele Frequency Spectra, demographic modeling
[slides](https://docs.google.com/presentation/d/1qvwG3MMP2xRPd4oGy6VyLXxzAKf99suKzCcMvUSFMrY/edit?usp=sharing)
Walkthrough: `pipelines_day2_AFS.sh`
### 3. Do-it-yourself! *Idotea baltica* project

bams: `/work/01211/cmonstr/IB/recal_bams`
metadata: `https://www.dropbox.com/s/af5ggl5p7gtuccp/Idotea%20environment%20171005.csv?dl=0`
<file_sep>Acropora millepora: Orpheus-Keppel comparison
BAMS=/work/01211/cmonstr/pipelines/*.bam
GENOME_REF=/work/01211/cmonstr/pipelines/amilV2_chroms.fasta
SAFs, ibsMat (just in case, dont download them yet):
/work/01211/cmonstr/pipelines/angsdResults/*
BEFORE STARTING, replace, in this whole file:
- <EMAIL> by your actual email;
- yourusername with your TACC user name.
# ============== installations ================================
# ------- ANGSD:
# install xz first from https://tukaani.org/xz/
cd
wget https://tukaani.org/xz/xz-5.2.4.tar.gz --no-check-certificate
tar vxf xz-5.2.4.tar.gz
cd xz-5.2.4/
./configure --prefix=$HOME/xz-5.2.4/
make
make install
# edit .bashrc:
cd
nano .bashrc
export LD_LIBRARY_PATH=$HOME/xz-5.2.4/lib:$LD_LIBRARY_PATH
export LIBRARY_PATH=$HOME/xz-5.2.4/lib:$LIBRARY_PATH
export C_INCLUDE_PATH=$HOME/xz-5.2.4/include:$C_INCLUDE_PATH
logout
# re-login
# now, install htslib:
cd
git clone https://github.com/samtools/htslib.git
cd htslib
make CFLAGS=" -g -Wall -O2 -D_GNU_SOURCE -I$HOME/xz-5.2.4/include"
# install ANGSD
cd
git clone https://github.com/ANGSD/angsd.git
cd angsd
make HTSSRC=../htslib
# now adding ANGSD to $PATH
cd
nano .bashrc
# section 2:
export PATH=$HOME/angsd:$PATH
export PATH=$HOME/angsd/misc:$PATH
# save (Ctl-O, Ctl-X)
# ---- PCAngsd
cd
module load python2
git clone https://github.com/Rosemeis/pcangsd.git
cd pcangsd/
python setup.py build_ext --inplace
#------- stairwayPlot (skip this for now)
# project page: https://sites.google.com/site/jpopgen/stairway-plot
cdw
# get version from June 2016 (v2beta2)
wget https://www.dropbox.com/s/toxnlvk8rhe1p5h/stairway_plot_v2beta2.zip
unzip stairway_plot_v2beta2.zip
mv stairway_plot_v2beta2 stairway_plot_v2beta
# ------- Moments:
cd
git clone https://bitbucket.org/simongravel/moments.git
cd moments
module load python2
python setup.py build_ext --inplace
# add this to .bashrc, section 2:
export PYTHONPATH=$PYTHONPATH:$HOME/moments
# re-login
# to see if it worked:
module load python2
python
import moments
# if you get an error message something is wrong, if you just see >>> it is all fine
quit()
# ------ installing 2bRAD scripts in $HOME/bin
cd
mkdir bin
cd ~/bin
# cloning github repositories
git clone https://github.com/z0on/2bRAD_denovo.git
# move scripts to ~/bin from sub-directories
mv 2bRAD_denovo/* .
# remove now-empty directories
rm -rf 2bRAD_denovo
#===================== A N G S D =====================
# "FUZZY genotyping" with ANGSD - without calling actual genotypes but working with genotype likelihoods at each SNP. Optimal for low-coverage data (<10x).
# if your coverage is >10x, go to GATK section below
# install ANGSD (see InstallingSoftware.txt file... this can be a challenge, so let me know when/if you get stuck)
#----------- assessing base qualities and coverage depth
# This is our data:
BAMS=/work/01211/cmonstr/pipelines/*.bam
# switching to scratch, creating working directory
cds
mkdir pipes
cd pipes
# creating a list of bam files to work on
ls $BAMS > bams
# only looking at sites genotyped in at least 50% of all individuals
FILTERS="-uniqueOnly 1 -minMapQ 20 -minInd 34 -maxDepth 10000"
TODO="-doQsDist 1 -doDepth 1 -doCounts 1 -dumpCounts 2"
# in the following line, -r argument is ~1 Mb (no need to do this for whole genome)
# (look up lengths of your contigs in the header of *.sam files if you need)
angsd -b bams -r chr10:1-1000000 -GL 1 $FILTERS $TODO -P 12 -out dd
# summarizing results (using modified script by <NAME>)
module load Rstats/3.5.1
Rscript ~/bin/plotQC.R prefix=dd
# scp dd.pdf to laptop to see distribution of base quality scores and fraction of sites in each sample depending on coverage threshold
# note the new file bams.qc: it lists only the bam files that are 3 SDs less than mean quality (quality = fraction of sites with >5x coverage, written in file quality.txt)
#--------------- population structure (based on common polymorphisms, allele freq >0.05)
# --- step1: identifying weird and clonal samples:
FILTERS="-uniqueOnly 1 -minMapQ 20 -minQ 20 -dosnpstat 1 -doHWE 1 -sb_pval 1e-5 -hetbias_pval 1e-5 -minInd 34 -snp_pval 1e-5 -minMaf 0.05"
TODO="-doMajorMinor 1 -skipTriallelic 1 -doMaf 1 -doCounts 1 -makeMatrix 1 -doIBS 1 -doCov 1 -doGeno 8 -doPost 1 -doGlf 2"
# Starting angsd with -P the number of parallel processesors.
echo "angsd -b bams.qc -GL 1 $FILTERS $TODO -P 12 -out OKall" >aa
ls5_launcher_creator.py -j aa -n aa -t 0:30:00 -a mega2014 -e <EMAIL> -w 1 -q normal
cat aa.slurm | perl -pe 's/module/#SBATCH --reservation=genomics_day1\nmodule/' > aa.R.slurm
sbatch aa.R.slurm
#if you are stuck, get pre-made OKall.ibsMat here: /work/01211/cmonstr/pipelines/angsdResults/
# analyze OKall.ibsMat using OKall_ibs.R to identify clones to remove
# (also need to scp file bams.qc to laptop to do this)
# --- step 2: RERUNNING angsd after cleaning up bams list
# scp bams.nc (without clones and weirdos) from laptop to here, or get it from /work/01211/cmonstr/pipelines/angsdResults/
FILTERS="-uniqueOnly 1 -skipTriallelic 1 -minMapQ 20 -minQ 20 -dosnpstat 1 -doHWE 1 -sb_pval 1e-5 -hetbias_pval 1e-5 -minInd 52 -snp_pval 1e-5 -minMaf 0.05"
TODO="-doMajorMinor 1 -doMaf 1 -doCounts 1 -makeMatrix 1 -doIBS 1 -doCov 1 -doGeno 8 -doPost 1 -doGlf 2"
echo "angsd -b bams.nc -GL 1 $FILTERS $TODO -P 12 -out OK" >ab
ls5_launcher_creator.py -j ab -n ab -t 0:30:00 -a mega2014 -e <EMAIL> -w 1 -q normal
cat ab.slurm | perl -pe 's/module/#SBATCH --reservation=genomics_day1\nmodule/' > ab.R.slurm
sbatch ab.R.slurm
#if you are stuck, get pre-made OK.ibsMat and OK.beagle.gz here: /work/01211/cmonstr/pipelines/angsdResults/
# ------- PCAngsd: estimating admixture, kinship, and SNP covariance
module load python2
python ~/pcangsd/pcangsd.py -beagle OK.beagle.gz -admix -o pcangsd -inbreed 2 -kinship -selection -threads 12
# making a table of bams : population correspondence
cat bams.nc | perl -pe 's/(.+)([OK])(\d+)(.+)/$2$3\t$2/' > inds2pops
# transfer inds2pops, pcangsd* and OK.ibsMat files to laptop, proceed with admixturePlotting_pcangsd.R and OK_ibs.R
<file_sep># installing required packages: do this once, then remark with #
setwd('~/Dropbox/pipelines2020') # change this to where your scp'd files are
bams=read.table("bams")[,1] # list of bam files
bams0=bams
# removing leading / trailing filename bits from sample names
bams=sub(".bam","",bams)
bams=sub(".+/","",bams)
length(bams)
ma = as.matrix(read.table("OKall.ibsMat"))
dimnames(ma)=list(bams,bams)
dim(ma)
ma[1:6,1:6]
hc=hclust(as.dist(ma),"ave")
plot(hc,cex=0.8) # clustering of samples by IBS (great to detect clones or closely related individuals)
#-------- pruning clonal replicates
cutclones=0.2
abline(h=cutclones,col="red")
grps=cutree(hc,h= cutclones)
# retaining a single representative of each clonal group
pruned=c();i=1
for (i in unique(grps)) {
pruned[i]=names(grps[grps==i])[1]
}
length(pruned)
ma1=ma[pruned,pruned]
hc=hclust(as.dist(ma1),"ave")
plot(hc,cex=0.8)
# also removing both K4 and O5 = obviously there is some mixup going on with sample names
pruned=pruned[-which(pruned %in% c("K4","O5"))]
goodbams=bams0[which(bams %in% pruned)]
length(goodbams)
write.table(goodbams,file="bams.nc",quote=F, col.names=F, row.names=F)
# scp bam.nc to TACC, rerun angsd
<file_sep>library(RcppCNPy)
library(ggplot2)
# ------ selection scan (from pcangsd)
# (along all important PCs. In this case there are only two pops inferred, so one important PC)
sel= npyLoad("pcangsd.selection.npy") # Reads results from selection scan
qqchi<-function(x,...){
lambda<-round(median(x)/qchisq(0.5,1),2)
qqplot(qchisq((1:length(x)-0.5)/(length(x)),1),x,ylab="Observed",xlab="Expected",...);abline(0,1,col=2,lwd=2)
legend("topleft",paste("lambda=",lambda))
}
# qq plot for selection scan - is there inflation of high p-values?
qqchi(sel)
# pvalues - against chisq with df=1
pval=pchisq(sel,1,lower.tail=F)
p.adj=p.adjust(pval,method="BH")
sites=read.table("OK.mafs.gz",header=T)
# ---- making manhattan plot, point size by allele frequency, color by adjusted pval
mh=sites[,c(1,2,5)]
mh$pos.mb=mh$position/1e+6
names(mh)[1:3]=c("chrom","pos","maf")
mh$sel=sel
mh$logp=(-1)*log(pval,10)
mh$logpa=(-1)*log(p.adj,10)
mh$maf3=mh$maf^3
ggplot(mh,aes(pos.mb,logp))+
geom_point(shape = 21, colour = "grey20", aes(size=maf3,fill=logpa))+
scale_size_continuous(breaks=c(0.2,0.4,0.6)^3,labels=c(0.2,0.4,0.6))+
scale_fill_gradient(low="grey80",high="coral")+
theme_bw() + labs(size = "maf")+theme(axis.text.x=element_text(angle=45, hjust=1))+
xlab("position,Mb")+facet_grid(~chrom,scale="free_x",space="free_x")
#-------- top selected sites
head(mh[order(mh$logp,decreasing=T),])
<file_sep># note: --reservation argument is now genomics_day2 (it will be day3 tomorrow!)
# first, we need to identify sites to work with and estimate SFS (site frequency spectrum) for each population.
# Running ANGSD on all bams with filters that do not disturb AFS, to find sites to work on.
FILTERS="-uniqueOnly 1 -skipTriallelic 1 -minMapQ 30 -minQ 30 -doHWE 1 -sb_pval 1e-5 -hetbias_pval 1e-5 -maxHetFreq 0.5 -minInd 38 "
TODO="-doMajorMinor 1 -doMaf 1 -dosnpstat 1 -doPost 2 -doGeno 11"
echo "angsd -b bams.nc -GL 1 -P 12 $FILTERS $TODO -out oksites">ac
ls5_launcher_creator.py -j ac -n ac -t 0:30:00 -e <EMAIL> -w 1 -a mega2014 -q normal
cat ac.slurm | perl -pe 's/module/#SBATCH --reservation=genomics_day2\nmodule/' > ac.R.slurm
sbatch ac.R.slurm
# saving and indexing sites that pass the filters (excluding mitochondrion)
zcat oksites.mafs.gz | cut -f 1,2 | tail -n +2 | grep "chr" > goodsites
angsd sites index goodsites
# saving bam lists corresponding to each population
grep O bams.nc >o
grep K bams.nc >k
# generating per-population SAF (site allele frequency likelihoods)
export GENOME_REF=/work/01211/cmonstr/pipelines/amilV2_chroms.fasta
TODO="-doSaf 1 -doMajorMinor 1 -doMaf 1 -doPost 1 -anc $GENOME_REF -ref $GENOME_REF"
echo "angsd -sites goodsites -b o -GL 1 -P 4 $TODO -out o
angsd -sites goodsites -b k -GL 1 -P 4 $TODO -out k">sfsa
ls5_launcher_creator.py -j sfsa -n sfsa -t 0:30:00 -e <EMAIL> -w 2 -a mega2014
cat sfsa.slurm | perl -pe 's/module/#SBATCH --reservation=genomics_day2\nmodule/' > sfsa.R.slurm
sbatch sfsa.R.slurm
# ----- generating bootstrapped SFS data (resampling chromosomes)
# first generate 100 series of 5 bootstraps for each population:
export GENOME_REF=/work/01211/cmonstr/pipelines/amilV2_chroms.fasta
>b100
for B in `seq 1 100`; do
echo "sleep $B && realSFS o.saf.idx k.saf.idx -ref $GENOME_REF -anc $GENOME_REF -bootstrap 5 -P 1 -resample_chr 1 >ok_$B">>b100;
done
ls5_launcher_creator.py -j b100 -n b100 -t 1:30:00 -e <EMAIL> -w 24 -a mega2014
cat b100.slurm | perl -pe 's/module/#SBATCH --reservation=genomics_day2\nmodule/' > b100.R.slurm
sbatch b100.R.slurm
# then, do "bagging" (averaging of 5 bootstrap replicates within each of the 100 series)
SFSIZE="73 53" # 2N+1 for each population.
for B in `seq 1 100`; do
echo $SFSIZE >ok_${B}.sfs;
cat ok_${B} | awk '{for (i=1;i<=NF;i++){a[i]+=$i;}} END {for (i=1;i<=NF;i++){printf "%.3f", a[i]/NR; printf "\t"};printf "\n"}' >> ok_${B}.sfs;
done
# ------ get pre-computed bootstrapped sfs (only if you are stuck with the above):
cp /work/01211/cmonstr/pipelines/sfs/* .
# ----- plotting 2dAFS (try different projections)
# full AFS
2dAFS.py ok_1.sfs O K 72 52
# to 0.9
2dAFS.py ok_1.sfs O K 66 48
# to 0.8
2dAFS.py ok_1.sfs O K 58 42
# transfer 2dAFS_ok_1.sfs_O_K* files to laptop for viewing
# ----- searching for best-fitting model
# (see README at https://github.com/z0on/AFS-analysis-with-moments for explanations)
# cloning Misha's Moments model collection and accessory scripts
cd
rm -rf AFS-analysis-with-moments/
git clone https://github.com/z0on/AFS-analysis-with-moments.git
cp ~/AFS-analysis-with-moments/multimodel_inference/py2/* ~/bin/
cd -
# writing a huge list of model runs
module load Rstats/3.5.1
Rscript ~/AFS-analysis-with-moments/modSel_write.R contrast=ok nreps=3 args="o k 58 42 0.02 0.005"
# NOTE: do not run this! (it would take too much computer time for all of us). Use pre-computed result ok.modsel
# summarizing results, writing commands to bootstrap the winning model
module load Rstats/3.5.1
Rscript ~/AFS-analysis-with-moments/modSel_summary.R modselResult=ok.modsel args="o k 58 42 0.02 0.005"
# ----- bootstrapping the winning model
# The previous script, modSel_summary.R, produced the file ok.winboots.runs containing a list of commands to run - same model on 'nboots' bootstrap replicates. We need to launch these commands all in parallel.
# (how do we do it? write it yourself!)
ls5_launcher_creator.py -j ok.winboots.runs -n ok.winboots.runs -t 1:00:00 -e <EMAIL> -w 24 -a mega2014 -q normal
cat ok.winboots.runs.slurm | perl -pe 's/module/#SBATCH --reservation=genomics_day2\nmodule/' > ok.winboots.runs.R.slurm
sbatch ok.winboots.runs.slurm
# the result will be collected in ok.winboots.
# we must concatenate all these results - please email your ok.winboots to Misha, <EMAIL>, with subject "ok.winboots". Wait for Misha to email you back the concatenated file.
# To summarize and plot results, do
module load Rstats/3.5.1
Rscript ~/AFS-analysis-with-moments/bestBoot_summary.R bootRes=ok.winboots
#--------------- GADMA
#installing dadi
cd
git clone https://bitbucket.org/gutenkunstlab/dadi.git
cd dadi
python setup.py install --user
# installing Pillow
python -m pip install Pillow
# installing GADMA
cd
rm -rf GADMA
git clone https://github.com/ctlab/GADMA.git
cd GADMA
python setup.py install --user
# writing GADMA parameters file
mv ok_1.sfs_20_20.projected ok_1_20_20.projected.sfs
echo "# param_file
Input file : ok_1_20_20.projected.sfs
Output directory : gadma_ok
Population labels : o , k
Initial structure : 1,1" >gadma_params
echo "gadma -p gadma_params">gad
#echo "gadma --resume gadma_12dp">gad
ls5_launcher_creator.py -j gad -n gad -t 14:00:00 -e <EMAIL> -w 1 -a tagmap -q normal
sbatch gad.slurm
<file_sep># read about multimodel inference here:
# https://pdfs.semanticscholar.org/a696/9a3b5720162eaa75deec3a607a9746dae95e.pdf
if (length(commandArgs(trailingOnly=TRUE))<1) {
options(warning.length=8000)
stop("
Summarizes results of the model selection run,
then writes a list of commands for bootstrapping the winning model to the file [pop.contrast].winboots.runs
Model selection is assumed to have been run on 10+ boostrapped replicates, each model with 3+ random starts.
Arguments:
modselResult=[filename] file containing results of the model selection run.
The following parameters are about writing commands for bootstrapping the winning model
(NOT about the completed run for model selection):
nboots=100 number of boostrap replicates to run for the winning model
nreps=6 number of random restarts for each boostrap replicate
folded=FALSE whether the analysis is using folded SFS
args=[list of arguments] names of pop1 and pop2, projection for pop1, projection for pop2, mutation rate (per genotyped portion of the
genome per generation), generation time in thousands of years. Population names can be anything.
For ANGSD-derived SFS, projections should be 0.8*2N for each population (ronded to integer);
in the case corresponding to the default setting each population was represented by 10 individuals.
Example: args=\"p1 p2 16 16 0.02 0.005\"
")
}
infl=grep("modselResult=",commandArgs())
if (length(infl)==0) { stop ("specify module selection results file (modselResult=filename)\nRun script without arguments to see all options\n") }
modselResult=sub("modselResult=","", commandArgs()[infl])
args=grep("args=",commandArgs())
if (length(args)==0) { stop ("specify arguments for SFS model runs\nRun script without options to see details\n") }
args =sub("args=","", commandArgs()[args])
if(length(grep("folded=T",commandArgs()))>0) { folded=TRUE } else { folded=FALSE }
nreps =grep("nreps=",commandArgs())
if(length(nreps)>0) { nreps=as.numeric(sub("nreps=","", commandArgs()[nreps])) } else { nreps=6 }
nboots =grep("nboots=",commandArgs())
if(length(nboots)>0) { nreps=as.numeric(sub("nboots =","", commandArgs()[nboots])) } else { nboots=100 }
if(length(grep("folded=T",commandArgs()))>0) { folded=TRUE } else { folded=FALSE }
# modselResult="c23.stdout"
# path2models="~/AFS-analysis-with-moments/multimodel_inference/"
# folded=FALSE
# args="p1 p2 16 16 0.02 0.005"
# nreps=3
# nboots=100
system(paste("grep RESULT ", modselResult," -A 4 | grep -v Launcher | grep -E \"[0-9]|\\]\" | perl -pe 's/^100.+\\.o\\d+\\S//' | perl -pe 's/\\n//' | perl -pe 's/[\\[\\]]//g' | perl -pe 's/RESULT/\\nRESULT/g' | grep RESULT >", modselResult,".res",sep=""))
infile=paste(modselResult,".res",sep="")
library(ggplot2)
system(paste("cut -f 2,3,4,5,6 -d ' ' ",infile," > ",infile,".likes",sep=""))
npl=read.table(paste(infile,".likes",sep=""))
system(paste("rm ",infile,".likes",sep=""))
names(npl)=c("model","id","npara","ll","boot")
contrast=sub("_.+","", npl$boot[1])
#head(npl)
#npl=npl[grep(infile,npl$boot),]
aics=list()
for (b in 1:length(unique(npl$boot))) {
bb=levels(npl$boot)[b]
nplb=subset(npl,boot==bb)
maxlike=c();nmod=c()
for (m in unique(nplb$model)) {
sub=subset(nplb,model==m)
nmod=c(nmod,nrow(sub))
maxlike=data.frame(rbind(maxlike,sub[sub$ll==max(sub$ll),]))
}
npara=maxlike$npara
likes=maxlike$ll
aic=2*npara-2*likes
aicc=data.frame(cbind(model=as.character(unique(nplb$model))))
aicc$aic=aic
aicc$nmod=nmod
aicc$boot=bb
aics[[b]]=aicc
}
awt=data.frame(do.call(rbind,aics))
models=unique(awt$model)
med=c()
for (m in models) {
ss=subset(awt,model==m)
med=c(med,median(ss$aic))
}
modmed=data.frame(cbind(mod=as.character(models)))
modmed$med=med
modmed=modmed[order(med),]
modmed$mod=factor(modmed$mod,levels=modmed$mod)
awt$model=factor(awt$model,levels=modmed$mod)
pdf(width=2.2,height=2,file=paste(contrast,"_modsel_top10medians.pdf",sep=""))
pp=ggplot(modmed[1:10,],aes(mod, med))+geom_point()+theme(axis.text.x = element_text(angle = 45,hjust=1))
#ggplot(modmed,aes(mod, med))+geom_point()+theme(axis.text.x = element_text(angle = 45,hjust=1))
plot(pp)
dev.off()
pdf(width=15,height=5,file=paste(contrast,"_modsel_allBoxplots.pdf",sep=""))
pp=ggplot(awt,aes(model,aic))+geom_boxplot()+scale_y_log10()+theme(axis.text.x = element_text(angle = 45,hjust=1))
plot(pp)
dev.off()
# ----- extracting name and parameters of the winning model, writing them to a file
winner=as.character(modmed[1,1])
npl0=subset(npl,model==winner)
npl0=npl0[which(npl0$ll==max(npl0$ll)),]
system(paste("grep \"",npl0$id," \" ", infile," > ",infile,".winmod",sep=""))
system(paste("rm ",infile,sep=""))
npl0=read.table(paste(infile,".winmod",sep=""))
params=as.vector(npl0[1,c(9:(ncol(npl0)-1))])
write.table(params,file=paste(contrast,".",winner,sep=""),quote=F,col.names=F,row.names=F)
# print(as.character(modmed[1,1]),quote=F)
# ------ writing commands to bootstrap the winning model
if (folded) {
mods=paste("fold_",winner,sep="")
} else {
mods=winner
}
args2=c()
for (b in 1:nboots) {
for (n in 1:nreps) {
for (m in mods) {
bname=paste(contrast,"_",b,".sfs",sep="")
args2=c(args2,paste("sleep ",n," && ",m,".py ",bname," ",args," ",paste(contrast,".",winner,sep="")," >>",contrast,".winboots",sep=""))
}
}
}
writeLines(args2,paste(contrast,".winboots.runs",sep=""))
| 70470dec451e9a7379d15287b17a94cb1b997fee | [
"Markdown",
"R",
"Shell"
] | 7 | R | z0on/pipelines2020 | 46ef0d03d2b3cd4cad3ed553c92a44a6c7d13458 | f5e4d2f94709447d20b3b572b4c4dacaf00e4780 |
refs/heads/master | <file_sep>.PHONY: all clean
CC = g++
CFLAGS = -std=c++17 -O2 -Wall
OBJS = Neuron.o CSVReader.o Perceptron.o Adaline.o MLP.o DigitAdalineNetwork.o DigitPerceptronNetwork.o Interpolator.o DigitMLPNetwork.o
all: MLPDigitTester DigitTester PolyTester clean
MLPDigitTester: src/MLPDigitTester.cpp $(OBJS)
$(CC) $(CFLAGS) -o $@ $< $(OBJS)
DigitTester: src/DigitTester.cpp $(OBJS)
$(CC) $(CFLAGS) -o $@ $< $(OBJS)
PolyTester: src/PolyTester.cpp $(OBJS)
$(CC) $(CFLAGS) -o $@ $< $(OBJS)
Neuron.o: src/Neuron.cpp src/Neuron.hpp
$(CC) $(CFLAGS) -c -o $@ $<
CSVReader.o: src/CSVReader.cpp src/CSVReader.hpp
$(CC) $(CFLAGS) -c -o $@ $<
Perceptron.o: src/Perceptron.cpp src/Perceptron.hpp src/ActivationFunctions.hpp
$(CC) $(CFLAGS) -c -o $@ $<
Adaline.o: src/Adaline.cpp src/Adaline.hpp src/ActivationFunctions.hpp
$(CC) $(CFLAGS) -c -o $@ $<
MLP.o: src/MLP.cpp src/MLP.hpp src/ActivationFunctions.hpp
$(CC) $(CFLAGS) -c -o $@ $<
Interpolator.o: src/Interpolator.cpp src/Interpolator.hpp src/Adaline.hpp
$(CC) $(CFLAGS) -c -o $@ $<
DigitPerceptronNetwork.o: src/DigitPerceptronNetwork.cpp src/DigitPerceptronNetwork.hpp
$(CC) $(CFLAGS) -c -o $@ $<
DigitAdalineNetwork.o: src/DigitAdalineNetwork.cpp src/DigitAdalineNetwork.hpp
$(CC) $(CFLAGS) -c -o $@ $<
DigitMLPNetwork.o: src/DigitMLPNetwork.cpp src/DigitMLPNetwork.hpp
$(CC) $(CFLAGS) -c -o $@ $<
clean:
rm *.o
<file_sep>/*
* Handwritten digit classifier
*
* A Neural Network of adaline neurons to classify
* handwritten digits.
*
* Author: <NAME>
*/
#pragma once
#include <random>
#include "Adaline.hpp"
namespace artnn
{
class DigitAdalineNet
{
public:
// Constructor
DigitAdalineNet(double tEtha)
{
for(uint i = 0; i < 10; i++)
{
mNeurons[i] = new Adaline<double>(785, tEtha);
mNeurons[i]->randomizeWeights(randomInitializer);
}
}
// Train this network with a data point
// Returns mean squared error of all neurons
double train(const std::vector<double>& X, int answer);
// Train this network with data set for an epoch
// Returns mean squared error of all data
double trainEpoch(std::vector<std::pair<std::vector<double>, int>>& input);
// Train for a given number of epochs or until
// mean squared error is less than epsilon
// Returns number of epochs trained
int trainFull(std::vector<std::pair<std::vector<double>, int>>& input,
const uint maxEpoch = 50, const double eps = 0.1);
// Feed input to Network and return classification
// Returns -1 if it doesn't recognize any digit
int evaluate(std::vector<double>& X);
// Test a batch of data and return the number of
// samples classified correctly
int test(std::vector<std::pair<std::vector<double>, int>>& input);
private:
Adaline<double>* mNeurons[10]; // Output Neurons
static double randomInitializer(); // Helper function to init weights
};
};<file_sep>/*
* Handwritten digit classifier
*
* A handwritten digit classifier implemented
* with multi-layer perceptron
*
* Author: <NAME>
*/
#pragma once
#include <fstream>
#include "MLP.hpp"
namespace artnn
{
class DigitMLPNet
{
public:
DigitMLPNet(uint hiddenNodes, double tEtha, double tAlpha)
{
std::vector<uint> sizes = { 784, hiddenNodes, 10 };
network = new MLP<double>(sizes, tEtha, tAlpha);
network->randomizeWeights(randomInitializer);
}
// Classify the given image
// Returns -1 if it didn't recognize any digit
int evaluate(const std::vector<double>& X);
// Same as evaluate but different criteria
int evaluateAux(const std::vector<double>& X);
// Train for a specified number of epochs
// or until error is less than some epsilon
// Return number of epochs trained
int trainFull(const std::vector<std::pair<std::vector<double>, int>>& trainingData,
const std::vector<std::pair<std::vector<double>, int>>& validationData,
const uint maxEpochs = 50, const double epsilon = 0.0,
const std::string trainLogFileName = "trainError.csv",
const std::string validLogFileName = "validError.csv");
// Count the number of correctly classified digits
int test(const std::vector<std::pair<std::vector<double>, int>>& testingData);
// Count the number of correctly classified digits
int testAux(const std::vector<std::pair<std::vector<double>, int>>& testingData);
private:
MLP<double>* network;
// Transform digit into canonical vector of size 10
// with 1 on the digit index and 0 everywhere else
std::vector<double> digitToVector(int d);
// Helper function to init weights
static double randomInitializer();
};
};<file_sep>#include "Neuron.hpp"
#ifdef WARNINGS_ENABLED
#include <iostream>
#endif
namespace artnn
{
template <typename T>
T Neuron<T>::dotProduct(const std::vector<T>& X, const std::vector<T>& Y)
{
#ifdef WARNINGS_ENABLED
if(X.size() != Y.size())
{
std::cerr << "Warning: Evaluating dot product of Vectors of different sizes\n";
}
#endif
T answer = 0;
for(uint i = 0; i < std::min(X.size(), Y.size()); i++)
{
answer += X[i] * Y[i];
}
return answer;
}
template <typename T>
T Neuron<T>::evaluate(const std::vector<T>& X)
{
return mSigma(dotProduct(mWeights, X));
}
template <typename T>
void Neuron<T>::randomizeWeights(std::function<T()> randFunc)
{
for(T& w : mWeights)
{
w = randFunc();
}
}
template class Neuron<float>;
template class Neuron<double>;
template class Neuron<long double>;
template class Neuron<int>;
template class Neuron<long long>;
};<file_sep>/*
* Function Interpolator
*
* A Function Polynomial Interpolator usign Adaline
* Neural Network.
*
*/
#pragma once
#include <vector>
#include <random>
#include <algorithm>
#include <fstream>
#include <string>
#include "Adaline.hpp"
namespace artnn
{
template <typename T>
class Interpolator : Adaline<T>
{
public:
// Constructor
Interpolator(uint degree, T etha)
: Adaline<T>(degree + 1, etha) {}
// Train a single epoch with a complete data set
// Return mean squared error
T trainEpoch(std::vector<std::pair<std::vector<T>,T>>& input);
// Train for given number of epochs or until error
// is less than epsilon
// Return mean squared error after last epoch
T trainFull(std::vector<std::pair<T, T>>& input,
uint maxEpoch = 50, T epsilon = 0.0);
// Evaluates polynomial in x
inline T eval(T x) { return this->evaluate(createPolyVector(x)); }
// Plot into a CSV file
void plotPoints(std::vector<T>& X, std::string filename);
private:
// Helper functions
// Create vector { 1, x^1, x^2, x^3, ... }
std::vector<T> createPolyVector(T x);
};
};<file_sep>#include "DigitMLPNetwork.hpp"
#include <iostream>
namespace artnn
{
int DigitMLPNet::evaluate(const std::vector<double>& X)
{
std::vector<double> Y = network->evaluate(X);
int answer = -1;
for(int i = 0; i < 10; i++)
{
if(Y[i] > 0.9)
{
if(answer == -1) { answer = i; }
else { answer = -1; break; }
}
else if(Y[i] > 0.1)
{
answer = -1;
break;
}
}
return answer;
}
int DigitMLPNet::evaluateAux(const std::vector<double>& X)
{
std::vector<double> Y = network->evaluate(X);
int answer = -1;
for(int i = 0; i < 10; i++)
{
if(Y[i] > 0.5)
{
if(answer == -1) { answer = i; }
else { answer = -1; break; }
}
}
return answer;
}
std::vector<double> DigitMLPNet::digitToVector(int d)
{
std::vector<double> v(10, 0.0);
v[d] = 1.0;
return v;
}
int DigitMLPNet::trainFull(const std::vector<std::pair<std::vector<double>, int>>& rawData,
const std::vector<std::pair<std::vector<double>, int>>& rawValidData,
const uint maxEpochs, const double epsilon,
const std::string trainLogFileName,
const std::string validLogFileName)
{
std::vector<std::pair<std::vector<double>, std::vector<double>>> trainingData(rawData.size());
std::vector<std::pair<std::vector<double>, std::vector<double>>> validationData(rawValidData.size());
std::ofstream trainLog(trainLogFileName);
std::ofstream validLog(validLogFileName);
int totEpochs = maxEpochs;
for(uint i = 0; i < rawData.size(); i++)
{
auto& [X, d] = rawData[i];
trainingData[i] = { X, digitToVector(d) };
}
for(uint i = 0; i < rawValidData.size(); i++)
{
auto& [X, d] = rawValidData[i];
validationData[i] = { X, digitToVector(d) };
}
for(uint i = 0; i < maxEpochs; i++)
{
double avgTrainError = network->trainEpoch(trainingData);
trainLog << i << "," << avgTrainError << std::endl;
double avgValidationError = network->validateEpoch(validationData);
validLog << i << "," << avgValidationError << std::endl;
if(avgTrainError < epsilon) { totEpochs = i; break; }
}
trainLog.close();
validLog.close();
return totEpochs;
}
int DigitMLPNet::test(const std::vector<std::pair<std::vector<double>, int>>& testingData)
{
int answer = 0;
for(auto& [X, d] : testingData)
{
int y = evaluate(X);
if(y == d) { answer++; }
}
return answer;
}
int DigitMLPNet::testAux(const std::vector<std::pair<std::vector<double>, int>>& testingData)
{
int answer = 0;
for(auto& [X, d] : testingData)
{
int y = evaluateAux(X);
if(y == d) { answer++; }
}
return answer;
}
double DigitMLPNet::randomInitializer()
{
static std::random_device rd;
static std::mt19937 e2(rd());
static std::uniform_real_distribution<double> dist(-0.05, 0.05);
return dist(e2);
}
};<file_sep># ArtNN
Implementations of basic Artificial Neural Networks like Perceptrons and Adalines for the course "Introduction to Neural Networks"
<file_sep>/*
* Perceptron neuron
*
* A simple perceptron implementation using
* a templated general neuron
*
* Author: <NAME>
*/
#pragma once
#include "Neuron.hpp"
#include "ActivationFunctions.hpp"
namespace artnn
{
template <typename T>
class Perceptron : public Neuron<T>
{
public:
// Constructor
Perceptron(uint tSize, T tEtha)
: Neuron<T>(tSize, sgn<T>, tEtha) {}
// Perceptron training function
bool train(const std::vector<T>& X, const T desiredOutput);
};
};<file_sep>#include "Adaline.hpp"
namespace artnn
{
template <typename T>
bool Adaline<T>::train(const std::vector<T>& X, T desiredOutput)
{
T y = Neuron<T>::evaluate(X);
if(y != desiredOutput)
{
for(uint i = 0; i < Neuron<T>::mSize; i++)
{
Neuron<T>::mWeights[i] += Neuron<T>::mEtha * (desiredOutput - y) * X[i];
}
return true;
}
return false;
}
template class Adaline<float>;
template class Adaline<double>;
template class Adaline<long double>;
template class Adaline<int>;
template class Adaline<long long>;
};<file_sep>#include "DigitPerceptronNetwork.hpp"
namespace artnn
{
double DigitPerceptronNet::randomInitializer()
{
static std::random_device rd;
static std::mt19937 e2(rd());
static std::uniform_real_distribution<double> dist(-0.05, 0.05);
return dist(e2);
}
double DigitPerceptronNet::train(const std::vector<double>& X, int d)
{
double acumError = 0.0;
for(int i = 0; i < 10; i++)
{
mNeurons[i]->train(X, i == d ? 1.0 : 0.0);
double y = mNeurons[i]->evaluate(X);
double dd = i == d ? 1.0 : 0.0;
double sqError = (dd - y) * (dd - y);
acumError += sqError;
}
return acumError / 10.0;
}
double DigitPerceptronNet::trainEpoch(std::vector<std::pair<std::vector<double>, int>>& input)
{
// Randomize input
std::random_shuffle(input.begin(), input.end());
double acumError = 0.0;
for(auto& [X, d] : input)
{
acumError += train(X, d);
}
return acumError / (double) input.size();
}
int DigitPerceptronNet::trainFull(std::vector<std::pair<std::vector<double>, int>>& input,
const uint maxEpoch, const double eps)
{
for(uint i = 0; i < maxEpoch; i++)
{
if(trainEpoch(input) <= eps) return i+1;
}
return maxEpoch;
}
int DigitPerceptronNet::evaluate(std::vector<double>& X)
{
int answer = -1;
int count = 0;
for(uint i = 0; i < 10; i++)
{
double y = mNeurons[i]->evaluate(X);
if(y == 1.0)
{
count++;
answer = i;
}
}
return count == 1 ? answer : -1;
}
int DigitPerceptronNet::test(std::vector<std::pair<std::vector<double>, int>>& input)
{
int count = 0;
for(auto& [X, d] : input)
{
if(evaluate(X) == d)
{
count++;
}
}
return count;
}
};<file_sep>#include <iostream>
#include <fstream>
#include "CSVReader.hpp"
#include "DigitMLPNetwork.hpp"
void storeData(std::vector<std::pair<std::vector<double>, int>>& finalData,
std::vector<std::vector<std::string>> rawData)
{
finalData.clear();
for(auto &line : rawData)
{
std::vector<double> v;
int digit = -1;
for(auto& s : line)
{
if(digit == -1)
{
digit = std::stoi(s);
}
else
{
v.push_back(std::stod(s) / 255.0);
}
}
finalData.push_back({v, digit});
}
}
int main(int argc, char* argv[])
{
if(argc < 3)
{
std::cout << "Usage: ./DigitTester <training_data_csv> <testing_data_csv>\n";
return 0;
}
srand(time(0));
int hitCount = -1;
std::string trainingFilename = argv[1];
std::string testingFilename = argv[2];
artnn::CSVReader trainingReader(trainingFilename);
artnn::CSVReader testingReader(testingFilename);
std::vector<std::pair<std::vector<double>, int>> trainingData;
std::vector<std::pair<std::vector<double>, int>> testingData;
std::vector<std::pair<std::vector<double>, int>> trainingData6;
std::vector<std::pair<std::vector<double>, int>> trainingData7;
std::cout << "Reading Training Data...\n";
storeData(trainingData, trainingReader.getData());
std::cout << "Reading Testing Data...\n";
storeData(testingData, testingReader.getData());
random_shuffle(trainingData.begin(), trainingData.end());
for(uint i = 0; i < trainingData.size() / 4; i++)
{
trainingData6.push_back(trainingData[i]);
}
random_shuffle(trainingData.begin(), trainingData.end());
for(uint i = 0; i < trainingData.size() / 2; i++)
{
trainingData7.push_back(trainingData[i]);
}
artnn::DigitMLPNet net0(20, 0.1, 0.9);
artnn::DigitMLPNet net1(50, 0.1, 0.9);
artnn::DigitMLPNet net2(100, 0.1, 0.9);
artnn::DigitMLPNet net3(100, 0.1, 0.0);
artnn::DigitMLPNet net4(100, 0.1, 0.25);
artnn::DigitMLPNet net5(100, 0.1, 0.5);
artnn::DigitMLPNet net6(100, 0.1, 0.9);
artnn::DigitMLPNet net7(100, 0.1, 0.9);
// -------------------- Network 0 ---------------------- //
std::cout << "\nTraining Network 0 for 50 epochs (n = 20, etha = 0.1, alpha = 0.9)...\n";
net0.trainFull(trainingData, testingData, 50, 0, "Logs/MLP/1/trainError0.csv", "Logs/MLP/1/validError0.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 0 (n = 20, etha = 0.1, alpha = 0.9)...\n";
hitCount = net0.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 0 second criteria (n = 20, etha = 0.1, alpha = 0.9)...\n";
hitCount = net0.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 0 ---------------------- //
// -------------------- Network 1 ---------------------- //
std::cout << "\nTraining Network 1 for 50 epochs (n = 50, etha = 0.1, alpha = 0.9)...\n";
net1.trainFull(trainingData, testingData, 50, 0, "Logs/MLP/1/trainError1.csv", "Logs/MLP/1/validError1.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 1 (n = 50, etha = 0.1, alpha = 0.9)...\n";
hitCount = net1.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 1 second criteria (n = 50, etha = 0.1, alpha = 0.9)...\n";
hitCount = net1.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 1 ---------------------- //
// -------------------- Network 2 ---------------------- //
std::cout << "\nTraining Network 2 for 50 epochs (n = 100, etha = 0.1, alpha = 0.9)...\n";
net2.trainFull(trainingData, testingData, 50, 0, "Logs/MLP/1/trainError2.csv", "Logs/MLP/1/validError2.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 2 (n = 100, etha = 0.1, alpha = 0.9)...\n";
hitCount = net2.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 2 second criteria (n = 100, etha = 0.1, alpha = 0.9)...\n";
hitCount = net2.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 2 ---------------------- //
// -------------------- Network 3 ---------------------- //
std::cout << "\nTraining Network 3 for 50 epochs (n = 100, etha = 0.1, alpha = 0.0)...\n";
net3.trainFull(trainingData, testingData, 50, 0, "Logs/MLP/2/trainError3.csv", "Logs/MLP/2/validError3.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 3 (n = 100, etha = 0.1, alpha = 0.0)...\n";
hitCount = net3.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 3 second criteria (n = 100, etha = 0.1, alpha = 0.0)...\n";
hitCount = net3.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 3 ---------------------- //
// -------------------- Network 4 ---------------------- //
std::cout << "\nTraining Network 4 for 50 epochs (n = 100, etha = 0.1, alpha = 0.25)...\n";
net4.trainFull(trainingData, testingData, 50, 0, "Logs/MLP/2/trainError4.csv", "Logs/MLP/2/validError4.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 4 (n = 100, etha = 0.1, alpha = 0.25)...\n";
hitCount = net4.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 4 second criteria (n = 100, etha = 0.1, alpha = 0.25)...\n";
hitCount = net4.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 4 ---------------------- //
// -------------------- Network 5 ---------------------- //
std::cout << "\nTraining Network 5 for 50 epochs (n = 100, etha = 0.1, alpha = 0.5)...\n";
net5.trainFull(trainingData, testingData, 50, 0, "Logs/MLP/2/trainError5.csv", "Logs/MLP/2/validError5.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 5 (n = 100, etha = 0.1, alpha = 0.5)...\n";
hitCount = net5.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 5 second criteria (n = 100, etha = 0.1, alpha = 0.5)...\n";
hitCount = net5.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 5 ---------------------- //
// -------------------- Network 6 ---------------------- //
std::cout << "\nTraining Network 6 for 50 epochs and 1/4 of the data (n = 100, etha = 0.1, alpha = 0.9)...\n";
net6.trainFull(trainingData6, testingData, 50, 0, "Logs/MLP/3/trainError6.csv", "Logs/MLP/3/validError6.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 6 (n = 100, etha = 0.1, alpha = 0.9)...\n";
hitCount = net6.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 6 second criteria (n = 100, etha = 0.1, alpha = 0.9)...\n";
hitCount = net6.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 6 ---------------------- //
// -------------------- Network 7 ---------------------- //
std::cout << "\nTraining Network 7 for 50 epochs and 1/2 of the data (n = 100, etha = 0.1, alpha = 0.9)...\n";
net7.trainFull(trainingData7, testingData, 50, 0, "Logs/MLP/3/trainError7.csv", "Logs/MLP/3/validError7.csv");
std::cout << "Training finished succesfully\n";
std::cout << "\nTesting Network 7 (n = 100, etha = 0.1, alpha = 0.9)...\n";
hitCount = net7.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Network 7 second criteria (n = 100, etha = 0.1, alpha = 0.9)...\n";
hitCount = net7.testAux(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
// -------------------- Network 7 ---------------------- //
return 0;
}<file_sep>#include "MLP.hpp"
#include <iostream>
namespace artnn
{
template <typename T>
std::vector<T> MLPNeuron<T>::train(const std::vector<T>& X, const T errorSignal, const T y)
{
// Return vector (we ommit the bias)
std::vector<T> backResult(Neuron<T>::mSize - 1);
T activationDerivate = mLogisticConst * y * (1 - y);
T localGradient = errorSignal * activationDerivate;
for(uint i = 0; i < backResult.size(); i++)
{
backResult[i] = Neuron<T>::mWeights[i] * localGradient;
}
for(uint i = 0; i < Neuron<T>::mSize; i++)
{
mLastDeltaW[i] = mAlpha * mLastDeltaW[i] + Neuron<T>::mEtha * localGradient * X[i];
Neuron<T>::mWeights[i] += mLastDeltaW[i];
}
return backResult;
}
template <typename T>
std::vector<T> MLPLayer<T>::evaluate(const std::vector<T>& X)
{
std::vector<T> output(mOutputSize);
for(uint i = 0; i < mOutputSize; i++)
{
output[i] = mNeuron[i].evaluate(X);
}
return output;
}
template <typename T>
std::vector<T> MLPLayer<T>::train(const std::vector<T>& X, const std::vector<T>& errorSignal,
const std::vector<T>& Y)
{
std::vector<T> backResult(mInputSize - 1, 0);
for(uint i = 0; i < mOutputSize; i++)
{
std::vector<T> localErrorSignal = mNeuron[i].train(X, errorSignal[i], Y[i]);
for(uint j = 0; j < backResult.size(); j++)
{
backResult[j] += localErrorSignal[j];
}
}
return backResult;
}
template <typename T>
std::vector<T> MLP<T>::evaluate(const std::vector<T>& X)
{
std::vector<T> Y = X;
for(uint i = 0; i < mLayer.size(); i++)
{
Y.push_back(1);
Y = mLayer[i]->evaluate(Y);
}
return Y;
}
template <typename T>
T MLP<T>::train(const std::vector<T>& X, const std::vector<T>& D)
{
std::vector<std::vector<T>> Y(mSize);
std::vector<T> e(D.size());
T sqError = 0;
Y[0] = X;
for(uint i = 0; i < mLayer.size(); i++)
{
Y[i].push_back(1);
Y[i+1] = mLayer[i]->evaluate(Y[i]);
}
for(uint i = 0; i < D.size(); i++)
{
e[i] = D[i] - Y[mSize-1][i];
sqError += e[i] * e[i];
}
for(uint i = mLayer.size(); i >= 1; i--)
{
std::vector<T> err;
err = mLayer[i-1]->train(Y[i-1], e, Y[i]);
e = err;
}
return 0.5 * sqError;
}
template <typename T>
T MLP<T>::validate(const std::vector<T>& X, const std::vector<T>& D)
{
T sqError = 0;
std::vector<T> Y = evaluate(X);
for(uint i = 0; i < D.size(); i++)
{
T e = D[i] - Y[i];
sqError += e * e;
}
return 0.5 * sqError;
}
template <typename T>
void MLP<T>::randomizeWeights(std::function<T()> randFunc)
{
for(auto& L : mLayer)
{
L->randomizeWeights(randFunc);
}
}
template <typename T>
void MLPLayer<T>::randomizeWeights(std::function<T()> randFunc)
{
for(auto& N : mNeuron)
{
N.randomizeWeights(randFunc);
}
}
template <typename T>
T MLP<T>::trainEpoch(std::vector<std::pair<std::vector<T>, std::vector<T>>>& trainingData)
{
random_shuffle(trainingData.begin(), trainingData.end());
T avgError = 0.0;
for(auto& [X, D] : trainingData)
{
avgError += train(X, D);
}
return avgError / (double) trainingData.size();
}
template <typename T>
T MLP<T>::validateEpoch(std::vector<std::pair<std::vector<T>, std::vector<T>>>& validationData)
{
T avgError = 0.0;
for(auto& [X, D] : validationData)
{
avgError += validate(X, D);
}
return avgError / (double) validationData.size();
}
template class MLPNeuron<float>;
template class MLPNeuron<double>;
template class MLPNeuron<long double>;
template class MLPLayer<float>;
template class MLPLayer<double>;
template class MLPLayer<long double>;
template class MLP<float>;
template class MLP<double>;
template class MLP<long double>;
};<file_sep>#include <iostream>
#include "CSVReader.hpp"
#include "DigitAdalineNetwork.hpp"
#include "DigitPerceptronNetwork.hpp"
void storeData(std::vector<std::pair<std::vector<double>, int>>& finalData,
std::vector<std::vector<std::string>> rawData)
{
finalData.clear();
for(auto &line : rawData)
{
std::vector<double> v;
int digit = -1;
for(auto& s : line)
{
if(digit == -1)
{
digit = std::stoi(s);
v.push_back(1.0); // Bias extra spot
}
else
{
v.push_back(std::stod(s) / 255.0);
}
}
finalData.push_back({v, digit});
}
}
int main(int argc, char* argv[])
{
if(argc < 3)
{
std::cout << "Usage: ./DigitTester <training_data_csv> <testing_data_csv>\n";
return 0;
}
std::string trainingFilename = argv[1];
std::string testingFilename = argv[2];
artnn::CSVReader trainingReader(trainingFilename);
artnn::CSVReader testingReader(testingFilename);
std::vector<std::pair<std::vector<double>, int>> trainingData;
std::vector<std::pair<std::vector<double>, int>> testingData;
std::cout << "Reading Training Data...\n";
storeData(trainingData, trainingReader.getData());
std::cout << "Reading Testing Data...\n";
storeData(testingData, testingReader.getData());
artnn::DigitPerceptronNet perceptron0(0.001);
artnn::DigitPerceptronNet perceptron1(0.01);
artnn::DigitPerceptronNet perceptron2(0.1);
artnn::DigitAdalineNet adaline0(0.0001);
artnn::DigitAdalineNet adaline1(0.001);
artnn::DigitAdalineNet adaline2(0.01);
std::cout << "\nTraining Perceptron Network 0 for 50 epochs (etha = 0.001)...\n";
perceptron0.trainFull(trainingData, 50, 0);
std::cout << "Training finished succesfully\n";
std::cout << "\nTraining Perceptron Network 1 for 50 epochs (etha = 0.01)...\n";
perceptron1.trainFull(trainingData, 50, 0);
std::cout << "Training finished succesfully\n";
std::cout << "\nTraining Perceptron Network 2 for 50 epochs (etha = 0.1)...\n";
perceptron2.trainFull(trainingData, 50, 0);
std::cout << "Training finished succesfully\n";
std::cout << "\nTraining Adaline Network 0 for 50 epochs (etha = 0.0001)...\n";
adaline0.trainFull(trainingData, 50, 0);
std::cout << "Training finished succesfully\n";
std::cout << "\nTraining Adaline Network 1 for 50 epochs (etha = 0.001)...\n";
adaline1.trainFull(trainingData, 50, 0);
std::cout << "Training finished succesfully\n";
std::cout << "\nTraining Adaline Network 2 for 50 epochs (etha = 0.01)...\n";
adaline2.trainFull(trainingData, 50, 0);
std::cout << "Training finished succesfully\n";
int hitCount = -1;
std::cout << "\nTesting Perceptron Network 0 (etha = 0.001)...\n";
hitCount = perceptron0.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Perceptron Network 1 (etha = 0.01)...\n";
hitCount = perceptron1.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Perceptron Network 2 (etha = 0.1)...\n";
hitCount = perceptron2.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Adaline Network 0 (etha = 0.0001)...\n";
hitCount = adaline0.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Adaline Network 1 (etha = 0.001)...\n";
hitCount = adaline1.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
std::cout << "\nTesting Adaline Network 2 (etha = 0.01)...\n";
hitCount = adaline2.test(testingData);
std::cout << "Classified correctly " << hitCount << " out of " << testingData.size() << "\n";
}
<file_sep>/*
* CSV reader
*
* Class to abstract reading from a csv file
*
* Author: <NAME>
*/
#pragma once
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
namespace artnn
{
class CSVReader
{
public:
CSVReader(std::string filename, std::string delim = ",")
: filename(filename), delimiter(delim) {}
// Get the contents of the file
std::vector<std::vector<std::string>> getData();
private:
std::string filename;
std::string delimiter;
// Helper Functions
std::vector<std::string> parseLine(std::string& line);
bool isDelimiter(char c);
};
};<file_sep>#include "Perceptron.hpp"
namespace artnn
{
template <typename T>
bool Perceptron<T>::train(const std::vector<T>& X, T desiredOutput)
{
T y = Neuron<T>::evaluate(X);
if(y != desiredOutput)
{
for(uint i = 0; i < Neuron<T>::mSize; i++)
{
Neuron<T>::mWeights[i] += Neuron<T>::mEtha * (desiredOutput - y) * X[i];
}
return true;
}
return false;
}
template class Perceptron<float>;
template class Perceptron<double>;
template class Perceptron<long double>;
template class Perceptron<int>;
template class Perceptron<long long>;
};<file_sep>#include <iostream>
#include "CSVReader.hpp"
#include "Interpolator.hpp"
void storeData(std::vector<std::pair<double, double>>& finalData,
std::vector<std::vector<std::string>> rawData)
{
finalData.clear();
for(auto& line : rawData)
{
finalData.push_back({std::stod(line[0]), std::stod(line[1])});
}
}
int main(int argc, char* argv[])
{
if(argc != 2)
{
std::cout << "Usage: ./PolyTester <data_csv>\n";
return 0;
}
std::string dataFilename = argv[1];
artnn::CSVReader dataReader(dataFilename);
std::vector<std::pair<double, double>> data;
std::vector<double> dataX;
std::cout << "Reading data..\n";
storeData(data, dataReader.getData());
for(auto& [x, y] : data)
{
dataX.push_back(x);
}
artnn::Interpolator<double> interpol0(3, 0.001);
artnn::Interpolator<double> interpol1(4, 0.001);
artnn::Interpolator<double> interpol2(5, 0.001);
artnn::Interpolator<double> interpol3(3, 0.0001);
artnn::Interpolator<double> interpol4(4, 0.0001);
artnn::Interpolator<double> interpol5(5, 0.0001);
artnn::Interpolator<double> interpol6(3, 0.00001);
artnn::Interpolator<double> interpol7(4, 0.00001);
artnn::Interpolator<double> interpol8(5, 0.00001);
double sqError;
// Network 0
std::cout << "\nTraining Network 0 (degree = 3, etha = 0.001)\n";
sqError = interpol0.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol0.plotPoints(dataX, "Plots/plot0-100.csv");
sqError = interpol0.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol0.plotPoints(dataX, "Plots/plot0-1000.csv");
sqError = interpol0.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol0.plotPoints(dataX, "Plots/plot0-10000.csv");
// Network 1
std::cout << "\nTraining Network 1 (degree = 4, etha = 0.001)\n";
sqError = interpol1.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol1.plotPoints(dataX, "Plots/plot1-100.csv");
sqError = interpol1.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol1.plotPoints(dataX, "Plots/plot1-1000.csv");
sqError = interpol1.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol1.plotPoints(dataX, "Plots/plot1-10000.csv");
// Network 2
std::cout << "\nTraining Network 2 (degree = 5, etha = 0.001)\n";
sqError = interpol2.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol2.plotPoints(dataX, "Plots/plot2-100.csv");
sqError = interpol2.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol2.plotPoints(dataX, "Plots/plot2-1000.csv");
sqError = interpol2.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol2.plotPoints(dataX, "Plots/plot2-10000.csv");
// Network 3
std::cout << "\nTraining Network 3 (degree = 3, etha = 0.0001)\n";
sqError = interpol3.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol3.plotPoints(dataX, "Plots/plot3-100.csv");
sqError = interpol3.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol3.plotPoints(dataX, "Plots/plot3-1000.csv");
sqError = interpol3.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol3.plotPoints(dataX, "Plots/plot3-10000.csv");
// Network 4
std::cout << "\nTraining Network 4 (degree = 4, etha = 0.0001)\n";
sqError = interpol4.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol4.plotPoints(dataX, "Plots/plot4-100.csv");
sqError = interpol4.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol4.plotPoints(dataX, "Plots/plot4-1000.csv");
sqError = interpol4.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol4.plotPoints(dataX, "Plots/plot4-10000.csv");
// Network 5
std::cout << "\nTraining Network 5 (degree = 5, etha = 0.0001)\n";
sqError = interpol5.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol5.plotPoints(dataX, "Plots/plot5-100.csv");
sqError = interpol5.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol5.plotPoints(dataX, "Plots/plot5-1000.csv");
sqError = interpol5.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol5.plotPoints(dataX, "Plots/plot5-10000.csv");
// Network 6
std::cout << "\nTraining Network 6 (degree = 3, etha = 0.00001)\n";
sqError = interpol6.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol6.plotPoints(dataX, "Plots/plot6-100.csv");
sqError = interpol6.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol6.plotPoints(dataX, "Plots/plot6-1000.csv");
sqError = interpol6.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol6.plotPoints(dataX, "Plots/plot6-10000.csv");
// Network 7
std::cout << "\nTraining Network 7 (degree = 4, etha = 0.00001)\n";
sqError = interpol7.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol7.plotPoints(dataX, "Plots/plot7-100.csv");
sqError = interpol7.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol7.plotPoints(dataX, "Plots/plot7-1000.csv");
sqError = interpol7.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol7.plotPoints(dataX, "Plots/plot7-10000.csv");
// Network 8
std::cout << "\nTraining Network 8 (degree = 5, etha = 0.00001)\n";
sqError = interpol8.trainFull(data, 100, 0.0);
std::cout << "Error after 100 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol8.plotPoints(dataX, "Plots/plot8-100.csv");
sqError = interpol8.trainFull(data, 900, 0.0);
std::cout << "Error after 1000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol8.plotPoints(dataX, "Plots/plot8-1000.csv");
sqError = interpol8.trainFull(data, 9000, 0.0);
std::cout << "Error after 10000 epochs: " << sqError << std::endl;
std::cout << "Plotting points...\n";
interpol8.plotPoints(dataX, "Plots/plot8-10000.csv");
}
<file_sep>/*
* Common Activation Functions for Neurons
*
* Implementation to some of the most common
* Activation Functions used in Artificial
* Neural Networks
*
* Author: <NAME>
*/
#pragma once
#include <cmath>
namespace artnn
{
// Sign function: 0 if x < 0 and 1 otherwise
template <typename T>
inline T sgn(T x)
{
return x < 0 ? 0 : 1;
}
// Identity function
template <typename T>
inline T id(T x)
{
return x;
}
// Logistic function (a = num / den)
template <typename T, int num = 1, int den = 1>
inline T logistic(T x)
{
T a = static_cast<T>(num) / static_cast<T>(den);
return 1 / (1 + exp(-a*x));
}
};<file_sep>#include "Interpolator.hpp"
namespace artnn
{
template <typename T>
T Interpolator<T>::trainEpoch(std::vector<std::pair<std::vector<T>,T>>& input)
{
// Randomize input
std::random_shuffle(input.begin(), input.end());
T acumError = 0;
for(auto& [X, d] : input)
{
this->train(X, d);
T y = this->evaluate(X);
T sqError = (d - y) * (d - y);
acumError += sqError;
}
return acumError / static_cast<T>(input.size());
}
template <typename T>
T Interpolator<T>::trainFull(std::vector<std::pair<T,T>>& input,
uint maxEpoch, T epsilon)
{
std::vector<std::pair<std::vector<T>, T>> processedInput;
for(auto& [x, y] : input)
{
processedInput.push_back({createPolyVector(x), y});
}
T sqError = 0;
for(uint i = 0; i < maxEpoch; i++)
{
sqError = trainEpoch(processedInput);
if(sqError <= epsilon)
return sqError;
}
return sqError;
}
template <typename T>
std::vector<T> Interpolator<T>::createPolyVector(T x)
{
std::vector<T> polyVector(this->mSize);
polyVector[0] = static_cast<T>(1);
for(uint i = 1; i < this->mSize; i++)
{
polyVector[i] = polyVector[i-1] * x;
}
return polyVector;
}
template <typename T>
void Interpolator<T>::plotPoints(std::vector<T>& X, std::string filename)
{
std::ofstream file(filename);
for(auto& x : X)
{
file << x << "," << eval(x) << "\n";
}
file.close();
}
template class Interpolator<float>;
template class Interpolator<double>;
template class Interpolator<long double>;
};<file_sep>#include "CSVReader.hpp"
namespace artnn
{
std::vector<std::vector<std::string>> CSVReader::getData()
{
std::ifstream file(filename);
std::vector<std::vector<std::string>> dataList;
std::string line = "";
while(getline(file, line))
{
dataList.push_back(parseLine(line));
}
file.close();
return dataList;
}
std::vector<std::string> CSVReader::parseLine(std::string& line)
{
std::vector<std::string> parsed;
std::string currentValue = "";
for(char c : line)
{
if(!isDelimiter(c))
{
currentValue += c;
}
else if(!currentValue.empty())
{
parsed.push_back(currentValue);
currentValue.clear();
}
}
if(!currentValue.empty())
{
parsed.push_back(currentValue);
currentValue.clear();
}
return parsed;
}
bool CSVReader::isDelimiter(char c)
{
return delimiter.find(c) != std::string::npos;
}
};<file_sep>/*
* A General Neuron model implementation
*
* Abstract template class of a Neuron that
* can be used as a super class for specific
* neurons like perceptrons
*
* Author: <NAME>
*/
#pragma once
#include <vector>
#include <functional>
#include <algorithm>
namespace artnn
{
template <typename T>
class Neuron
{
public:
// Constructor
Neuron(uint tSize, std::function<T(T)> tSigma, T tEtha)
: mSize(tSize), mSigma(tSigma), mWeights(mSize), mEtha(tEtha) {}
// Get output of feeding input Vector X to the neuron
T evaluate(const std::vector<T>& X);
// Randomize Synaptic Weights Vector
void randomizeWeights(std::function<T()> randFunc);
protected:
uint mSize; // Size of the Weights Vector
std::function<T(T)> mSigma; // Activation Function
std::vector<T> mWeights; // Synaptic Weights
T mEtha; // Learning Factor
// Dot product between two vectors
static T dotProduct(const std::vector<T>& X, const std::vector<T>& Y);
};
};<file_sep>/*
* Adaline Neuron
*
* Simple implementation of an Adaline Neuron
* using templated neuron super class
*
* Author: <NAME>
*/
#pragma once
#include "Neuron.hpp"
#include "ActivationFunctions.hpp"
namespace artnn
{
template <typename T>
class Adaline : public Neuron<T>
{
public:
// Constructor
Adaline(uint tSize, T tEtha)
: Neuron<T>(tSize, id<T>, tEtha) {}
// Adaline training function
bool train(const std::vector<T>& X, const T desiredOutput);
};
};<file_sep>/*
* A Multi-Layer Perceptron implementation
*
* Template class of Multi-Layer perceptron
* implemented using the abstract class
* Neuron.
*
* Author: <NAME>
*/
#pragma once
#include <random>
#include "Neuron.hpp"
#include "ActivationFunctions.hpp"
namespace artnn
{
template <typename T>
class MLPNeuron : public Neuron<T>
{
public:
MLPNeuron(uint tSize, T tEtha, T tAlpha = 0)
: Neuron<T>(tSize, logistic<T,1,1>, tEtha),
mAlpha(tAlpha), mLastDeltaW(tSize, 0),
mLogisticConst(1)
{}
// Train this neuron given input and error signals
// Return Vector of local gradient times weights
std::vector<T> train(const std::vector<T>& X, const T errorSignal, const T y);
private:
T mAlpha; // Momentum factor
std::vector<T> mLastDeltaW; // Last change to weights
T mLogisticConst; // Constant of the logistic function
};
template <typename T>
class MLPLayer
{
public:
MLPLayer(uint tInputSize, uint tOutputSize, T tEtha, T tAlpha = 0)
: mInputSize(tInputSize), mOutputSize(tOutputSize),
mNeuron(tOutputSize, MLPNeuron<T>(tInputSize, tEtha, tAlpha))
{}
// Get the output of feeding X to this layer
std::vector<T> evaluate(const std::vector<T>& X);
// Train this layer given input and error signals
// Return Vector of sumation of local gradients times weights
std::vector<T> train(const std::vector<T>& X, const std::vector<T>& errorSignal,
const std::vector<T>& Y);
// Initialize with random weights given by random
// generating function
void randomizeWeights(std::function<T()> randFunc);
private:
uint mInputSize; // Size of input
uint mOutputSize; // Number of neurons
std::vector<MLPNeuron<T>> mNeuron; // Neurons
};
template <typename T>
class MLP
{
public:
MLP(std::vector<uint>& tSizes, T tEtha, T tAlpha = 0)
: mSize(tSizes.size()), mLayer(tSizes.size() - 1, nullptr)
{
for(uint i = 1; i < tSizes.size(); i++)
{
mLayer[i-1] = new MLPLayer<T>(tSizes[i-1] + 1, tSizes[i], tEtha, tAlpha);
}
}
// Feed input to the network and get result
std::vector<T> evaluate(const std::vector<T>& X);
// Train with input vector X and desired output D
// Returns mean square error
T train(const std::vector<T>& X, const std::vector<T>& D);
// Train this Network for a complete epoch
// Return average mean square error
T trainEpoch(std::vector<std::pair<std::vector<T>, std::vector<T>>>& trainingData);
// Return mean square error
T validate(const std::vector<T>& X, const std::vector<T>& D);
// Return average mean square error
T validateEpoch(std::vector<std::pair<std::vector<T>, std::vector<T>>>& validationData);
// Initialize with random weights given by random
// generating function
void randomizeWeights(std::function<T()> randFunc);
private:
uint mSize; // Number of layers
std::vector<MLPLayer<T>*> mLayer; // Layers
};
}; | be2ce08e46f936b8c7afc0dc4f0c6be8d8f72043 | [
"Markdown",
"Makefile",
"C++"
] | 22 | Makefile | MarcosJLR/ArtNN | 1a0cc0a5f168246bb1e3e9f77cc073dde13615be | 9939d70a0435404a7b02f96d49096a4196fe37fd |
refs/heads/master | <file_sep>const fs = require('fs');
const webapp = require('./webapp.js');
const data = require('./data/usersdata.json');
const User = require('./src/model/user.js');
let head = fs.readFileSync('./src/headTodo.txt');
let tail = fs.readFileSync('./src/tailTodo.txt');
let users = ['bhanutv','harshab','madhu'];
let registered_users = users.map((user)=>{
let newUser = new User(user);
return newUser;
});
const loadSession = (req,res)=>{
req.session = app.sessionManager.loadSession(req.cookies.sessionid);
};
const contentType = {
"html" : "text/html",
"txt" : "text/plain",
"css" : "text/css",
"js" : "text/javascript",
"jpg" : "image/jpg",
"ico" : "image/jpg",
"gif" : "image/gif",
"pdf" : "application/pdf"
};
const getExtension = (filePath)=>{
return filePath.substr(filePath.lastIndexOf('.')+1);
}
const addTodo = function(user,title,desc){
user.addTodo(title,desc);
}
const serveStaticFile = function(filePath){
return function(req,res){
res.setHeader("Content-Type",contentType[getExtension(filePath)]);
res.statusCode = 200;
res.write(fs.readFileSync(filePath));
res.end();
}
}
const createUser = function(name){
let user = registered_users.find(user=>user.name == name);
if(!user){
registered_users.push(new User(name));
data[name] = [];
}
};
const redirectLoggedOutUserToLogin = function(req,res){
if(!req.urlIsOneOf(['/login']) && !req.user) res.redirect('/login');
}
const redirectLoggedInUserToHome = function(req,res){
if(req.urlIsOneOf(['/login','/login.html']) && req.user) res.redirect('/index');
}
let staticHTMLPages = ['/index','/addTodo','/'];
let staticCSSPages = ['/styles.css']
let images = ['/edit.jpg','/delete.jpg'];
let app = webapp.create();
staticHTMLPages.forEach((url)=>{
app.get(url,serveStaticFile(`./src/${(url == '/' ? '/index' : url)}.html`));
})
staticCSSPages.forEach((url)=>{
app.get(url,serveStaticFile(`./src/${url}`));
})
images.forEach((url)=>{
app.get(url,serveStaticFile(`./src/images${url}`))
})
app.use(loadSession);
app.use(redirectLoggedInUserToHome);
app.use(redirectLoggedOutUserToLogin);
app.get('/requests.js',serveStaticFile('./src/requests.js'));
app.get('/getTodos',(req,res)=>{
let todos = JSON.stringify(req.user.toHtmlRow());
res.write(todos);
res.end();
})
app.get('/getUserName',(req,res)=>{
res.write(req.user.name);
res.end();
})
app.get('/login',(req,res)=>{
res.setHeader('Content-type','text/html');
if(req.cookies.logInFailed) res.write('<p>logIn Failed</p>');
res.write('<form method="POST"> <input name="userName"><input name="place"> <input type="submit"></form>');
res.end();
});
app.post('/login',(req,res)=>{
let user = registered_users.find(u=>u.name==req.body.userName);
if(!user) {
res.setHeader('Set-Cookie',`logInFailed=true`);
res.redirect('/login');
return;
}
let userName = user.name;
user.loggedin();
let session = app.sessionManager.create(user);
res.setHeader('Set-Cookie',[`sessionId=${session.Id}`,`loggedin=true`,`loggedin=false`]);
user.allTodos.forEach((todo)=>{
app.get(`${todo.id}`,(req,res)=>{
res.write(`${head}
${todo.toHtml()}
${tail}`);
res.end();
});
})
res.redirect('/index');
});
app.get('/logout',(req,res)=>{
user = req.user;
user.loggedout();
res.setHeader('Set-Cookie',[''])
app.sessionManager.remove(req.session);
res.redirect('/login');
res.end();
});
app.post('/addTodo',(req,res)=>{
let user = req.user;
let title = req.body.title.replace(/\+/g,' ');
let desc = req.body.desc.replace(/\+/g,' ');
addTodo(user,title,desc);
let todo = user.getTodo(title);
app.get(`/${title}`,(req,res)=>{
res.write(`${head}
${todo.toHtml()}
${tail}`);
res.end();
})
res.redirect('/index');
})
module.exports = app;
<file_sep>const http = require('http');
const SessionManager = require('./src/sessionManager');
const port = process.argv[process.argv.length - 1];
const app = require('./app.js');
app.sessionManager = SessionManager.createFrom('./data/sessions.json');
let server = http.createServer(app).listen(port);
<file_sep>const assert = require('chai').assert;
let app = require('../app.js');
let testHelper = require('../src/utils/testHelper.js');
let request = require('../src/utils/requestSimulator.js');
let session = {Id:1234};
let create = (user)=> {
session.user = user;
return session;
}
let load = (sessionId)=> sessionId==1234&&session;
let remove;
app.sessionManager = {load,remove,create};
describe('app',()=>{
describe('redirect to /login when user is not loggedin',()=>{
it('responds with 302 when asked for existing page',(done)=>{
request(app,{method:'GET',url:'/index'},(res)=>{
testHelper.should_be_redirected_to(res,'/login');
testHelper.body_should_empty(res);
done();
});
});
it('responds with 302 when asked for bad page',(done)=>{
request(app,{method:'GET',url:'/bad'},(res)=>{
testHelper.should_be_redirected_to(res,'/login');
testHelper.body_should_empty(res);
done();
});
});
});
describe('GET /login',()=>{
it('responds with 200',()=>{
request(app,{method:"GET",url:"/login"},(res)=>{
testHelper.status_is_ok(res);
testHelper.body_contains(res,'</form>');
});
});
});
describe('POST /login',()=>{
it('redirect to GET /login if user details are invalid',()=>{
request(app,{method:'POST',url:'/login',body:'username=bhanu'},(res)=>{
testHelper.should_be_redirected_to(res,'/login');
});
})
it('redirect to /index if user details are valid',()=>{
request(app,{method:'POST',url:'/login',body:'userName=bhanutv'},(res)=>{
testHelper.should_not_have_cookie(res,'logInFailed');
testHelper.should_be_redirected_to(res,'/index');
testHelper.should_have_cookie(res,'sessionid')
});
})
});
});
<file_sep>const TodoList = require('./todolist.js');
class User {
constructor(name) {
this.userName = name;
this.todos = {};
}
get name(){
return this.userName;
}
get allTodos(){
let todos = [];
Object.keys(this.todos).forEach((title)=>{
todos.push(this.todos[title]);
});
return todos;
};
get noOfTodos(){
return this.allTodos.length;
}
toHtmlRow(){
let html = `
<tr>
<th>Title</th>
<th>Description</th>
<th>edit</th>
<th>delete</th>
</tr>`;
this.allTodos.forEach((todo)=>{html += todo.toHtmlRow()});
return html;
}
addTodo(title,desc=""){
this.todos[title] = new TodoList(title,desc);
}
getTodo(todoId){
return this.todos[todoId];
}
addTodoItem(todoID,itemTitle,desc){
let todo = this.getTodo(todoID);
todo.addItem(itemTitle,desc);
}
getTodoItem(title,itemId){
return this.getTodo(title).getItem(itemId);
}
markDone(title,itemId){
let todo = this.getTodo(title);
todo.getItem(itemId).markDone();
}
markUndone(title,itemId){
let todo = this.getTodo(title);
todo.getItem(itemId).markUndone();
}
editTodo(title,fieldToEdit,newContent){
let todo = this.getTodo(title);
todo.edit(fieldToEdit,newContent);
}
deleteItem(title,itemId){
let todo = this.getTodo(title);
todo.deleteItem(itemId);
}
deleteTodo(title){
delete this.todos[title];
}
}
module.exports = User;
<file_sep>writeName = function(){
let userName = this.responseText;
document.getElementById('userName').innerText = `Welcome ${userName}`;
};
writeTodos = function(){
let todos = JSON.parse(this.responseText);
let table = document.getElementById('todos');
table.innerHTML = todos;
}
getName = function(){
let userNameRequest = new XMLHttpRequest();
userNameRequest.onload = writeName;
userNameRequest.open("GET","/getUserName");
userNameRequest.send();
};
populateTodos = function(){
let todoRequest = new XMLHttpRequest();
todoRequest.onload = writeTodos;
todoRequest.open("GET","/getTodos");
todoRequest.send();
};
<file_sep>class fs {
constructor(validFiles) {
this.validFiles = validFiles || [];
}
addValidFile(filePath){
this.validFiles.push(filePath);
}
existsSync(filePath){
return this.validFiles(filePath);
}
}
| 75ed5bd49d4103ce2e363529ce7f32db11146a73 | [
"JavaScript"
] | 6 | JavaScript | step-archive/todo-TPKalyan | 8600f95eda9a1010b2fa1748d5df2cb035fbcb19 | a49423b0709d40ce88082d03c5f199ee93311fe1 |
refs/heads/master | <repo_name>m2wasabi/SpeechGoUnity<file_sep>/Assets/RotCube/Scripts/rotate.cs
using HoloToolkit.Unity.InputModule;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Windows.Speech;
public class rotate : MonoBehaviour, IFocusable
{
public float Speed = 100.0f;
private bool isRotate = false;
public AudioClip TargetFeedbackSound;
private AudioSource audioSource;
public AudioClip TargetFeedbackSound2;
public Vector3 RotateVector3;
private GameObject _cubeMesh;
private GameObject HoloLensCamera;
private Vector3 _targetPos;
private ReactionManager _reactioManager;
// Windows KeywordRecognizer
private KeywordRecognizer keywordRecognizer;
delegate void KeywordAction(PhraseRecognizedEventArgs args);
Dictionary<string, KeywordAction> keywordCollection;
private speech _speech;
// Use this for initialization
void Start () {
_speech = GameObject.Find("InputManager").GetComponent<speech>();
if(TargetFeedbackSound != null)
{
audioSource = GetComponent<AudioSource>();
if(audioSource == null)
{
audioSource = gameObject.AddComponent<AudioSource>();
}
audioSource.clip = TargetFeedbackSound;
audioSource.playOnAwake = false;
audioSource.spatialBlend = 1;
audioSource.dopplerLevel = 0;
}
// KeywordRecognizer
keywordCollection = new Dictionary<string, KeywordAction>();
keywordCollection.Add("Cube Come Here", CubeMoveInCamera);
keywordCollection.Add("Switch", ToggleBulletSource);
keywordRecognizer = new KeywordRecognizer(keywordCollection.Keys.ToArray());
keywordRecognizer.OnPhraseRecognized += KeywordRecognizer_OnPhraseRecognized;
keywordRecognizer.Start();
// Find Camera
HoloLensCamera = GameObject.Find("HoloLensCamera");
_targetPos = HoloLensCamera.transform.position;
// Find cubemesh
_cubeMesh = transform.Find("CubeMesh").gameObject;
// Find ReactionManager
_reactioManager = GameObject.Find("InputManager").GetComponent<ReactionManager>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Z))
{
_reactioManager.BulletSourceIndex = (_reactioManager.BulletSourceIndex == 0) ? 1 : 0;
}
if (isRotate)
{
_cubeMesh.transform.Rotate(RotateVector3 * Time.deltaTime * Speed);
}
transform.position = Vector3.Slerp(transform.position, _targetPos, Time.deltaTime);
}
void BeginRotate()
{
if(audioSource != null && !audioSource.isPlaying)
{
audioSource.clip = TargetFeedbackSound;
audioSource.Play();
}
this.RotateVector3 = new Vector3(Random.Range(-10.0f, 10.0f), Random.Range(-10.0f, 10.0f), Random.Range(-10.0f, 10.0f)).normalized;
isRotate = true;
}
void StopRotate()
{
if (audioSource != null && !audioSource.isPlaying)
{
audioSource.clip = TargetFeedbackSound2;
audioSource.Play();
}
isRotate = false;
}
public void OnFocusEnter()
{
if (!isRotate)
{
BeginRotate();
_speech.StartRecordButtonOnClickHandler();
}
}
public void OnFocusExit()
{
if (isRotate)
{
_speech.StopRecordButtonOnClickHandler();
StopRotate();
}
}
private void KeywordRecognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
KeywordAction keywordAction;
if (keywordCollection.TryGetValue(args.text, out keywordAction))
{
keywordAction.Invoke(args);
}
}
private void CubeMoveInCamera(PhraseRecognizedEventArgs args)
{
_targetPos = HoloLensCamera.transform.position + (HoloLensCamera.transform.forward * 1);
}
private void ToggleBulletSource(PhraseRecognizedEventArgs args)
{
_reactioManager.BulletSourceIndex = (_reactioManager.BulletSourceIndex == 0) ? 1 : 0;
}
}
<file_sep>/Assets/RotCube/Scripts/SoundManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : MonoBehaviour {
public enum State { Stop, Busy, Loop }
public State Status { get; private set; }
private AudioSource _audioSource;
public AudioClip[] Sounds;
// Use this for initialization
void Start () {
_audioSource = GetComponent<AudioSource>();
if (_audioSource == null)
{
_audioSource = gameObject.AddComponent<AudioSource>();
}
_audioSource.playOnAwake = false;
_audioSource.spatialBlend = 1;
_audioSource.dopplerLevel = 0;
}
// Update is called once per frame
void Update () {
}
public void Play(int index)
{
if (Sounds.Length > index && Sounds[index] != null)
{
_audioSource.Stop();
_audioSource.clip = Sounds[index];
_audioSource.Play();
}
}
}
<file_sep>/Assets/RotCube/Scripts/ReactionManager.cs
using System.Collections;
using System.Collections.Generic;
using FrostweepGames.Plugins.GoogleCloud.SpeechRecognition;
using UnityEngine;
using HoloToolkit.Unity;
public class ReactionManager : Singleton<ReactionManager>
{
public AudioClip SpeechFeedbackSound;
private AudioSource reactionAudioSource;
public GameObject TextObject;
public GameObject TextBombObject;
public float BulletSpeed = 1000;
public int BulletSourceIndex = 0;
public GameObject[] BulletSources;
// Use this for initialization
void Start () {
if (SpeechFeedbackSound != null)
{
reactionAudioSource = GetComponent<AudioSource>();
if (reactionAudioSource == null)
{
reactionAudioSource = gameObject.AddComponent<AudioSource>();
}
reactionAudioSource.clip = SpeechFeedbackSound;
reactionAudioSource.playOnAwake = false;
reactionAudioSource.priority = 1;
reactionAudioSource.spatialBlend = 1;
reactionAudioSource.dopplerLevel = 0;
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GenerateTextObject("Hello!", TextBombObject);
}
}
public void Action (RecognitionResponse obj)
{
string text = obj.results[0].alternatives[0].transcript;
//RaycastHit hit;
//if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
//{
// Instantiate(TextObject, hit.point, Quaternion.identity);
//}
if (text.IndexOf("爆発") != -1)
{
GenerateTextObject(text, TextBombObject);
}
else
{
GenerateTextObject(text, TextObject);
}
if (text.IndexOf("最高") != -1)
{
reactionAudioSource.Play();
}
}
private void GenerateTextObject(string word, GameObject prefab)
{
GameObject wordBullet = GameObject.Instantiate(prefab);
Vector3 force;
force = BulletSources[BulletSourceIndex].transform.forward * BulletSpeed;
wordBullet.GetComponent<Rigidbody>().AddForce(force);
wordBullet.transform.position = BulletSources[BulletSourceIndex].transform.position;
TextMesh _text = wordBullet.GetComponent<TextMesh>();
_text.text = word;
}
}
<file_sep>/Assets/RotCube/Scripts/GazeSwitch.cs
using System.Collections;
using System.Collections.Generic;
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using UnityEngine.Windows.Speech;
public class GazeSwitch : MonoBehaviour, IFocusable
{
private GameObject HoloLensCamera;
private Vector3 _targetPos;
private Vector3 _targetLookAt;
// Stat of Switch
public enum SwitchState { Off, On }
public SwitchState SwitchStatus { get; private set; }
// clolor material
public Material[] Materials;
//private int _materialIndex = 0;
public GameObject SwitchObject;
// Action Driver
private speech _speech;
private SoundManager _soundManager;
private ReactionManager _reactioManager;
// Use this for initialization
void Start () {
_speech = GameObject.Find("InputManager").GetComponent<speech>();
_soundManager = GetComponent<SoundManager>();
_reactioManager = GameObject.Find("InputManager").GetComponent<ReactionManager>();
// Find Camera
HoloLensCamera = GameObject.Find("HoloLensCamera");
_targetPos = HoloLensCamera.transform.position + (HoloLensCamera.transform.TransformDirection(Vector3.forward) * 2);
_targetLookAt = HoloLensCamera.transform.position + (HoloLensCamera.transform.TransformDirection(Vector3.forward) * 4);
SwitchStatus = SwitchState.Off;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.X))
{
MoveInCamera(new PhraseRecognizedEventArgs());
}
if (Input.GetKeyDown(KeyCode.C))
{
EffectSwitchOn();
}
if (Input.GetKeyDown(KeyCode.V))
{
EffectSwitchOff();
}
transform.position = Vector3.Slerp(transform.position, _targetPos, Time.deltaTime);
transform.LookAt(_targetLookAt);
}
public void MoveInCamera(PhraseRecognizedEventArgs args)
{
_targetPos = HoloLensCamera.transform.position + (HoloLensCamera.transform.TransformDirection(Vector3.forward) * 2);
_targetLookAt = HoloLensCamera.transform.position + (HoloLensCamera.transform.TransformDirection(Vector3.forward) * 4);
}
public void EffectSwitchOn()
{
Renderer _renderer = SwitchObject.GetComponent<Renderer>();
_renderer.material = Materials[1];
}
public void EffectSwitchOff()
{
Renderer _renderer = SwitchObject.GetComponent<Renderer>();
_renderer.material = Materials[0];
}
public void OnFocusEnter()
{
if (SwitchStatus == SwitchState.Off && _speech.Status == speech.State.Stop)
{
EffectSwitchOn();
_soundManager.Play(0);
_speech.StartRecordButtonOnClickHandler();
_reactioManager.BulletSourceIndex = 1;
SwitchStatus = SwitchState.On;
}
}
public void OnFocusExit()
{
if (SwitchStatus == SwitchState.On)
{
if (_speech.Status == speech.State.Recording)
{
_speech.StopRecordButtonOnClickHandler();
}
_soundManager.Play(1);
EffectSwitchOff();
SwitchStatus = SwitchState.Off;
}
}
}
<file_sep>/Assets/RotCube/Scripts/VoiceCommandManager.cs
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using UnityEngine.Windows.Speech;
public class VoiceCommandManager : MonoBehaviour {
// Windows KeywordRecognizer
private KeywordRecognizer keywordRecognizer;
delegate void KeywordAction(PhraseRecognizedEventArgs args);
Dictionary<string, KeywordAction> keywordCollection;
private GazeSwitch _gazeSwitch;
// Use this for initialization
void Start () {
_gazeSwitch = GameObject.Find("MagicCube").GetComponent<GazeSwitch>();
// KeywordRecognizer
keywordCollection = new Dictionary<string, KeywordAction>();
keywordCollection.Add("Cannon Come Here", _gazeSwitch.MoveInCamera);
//keywordCollection.Add("Switch", ToggleBulletSource);
keywordRecognizer = new KeywordRecognizer(keywordCollection.Keys.ToArray());
keywordRecognizer.OnPhraseRecognized += KeywordRecognizer_OnPhraseRecognized;
keywordRecognizer.Start();
}
// Update is called once per frame
void Update () {
}
private void KeywordRecognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
KeywordAction keywordAction;
if (keywordCollection.TryGetValue(args.text, out keywordAction))
{
keywordAction.Invoke(args);
}
}
}
<file_sep>/Assets/RotCube/Scripts/bomb.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bomb : MonoBehaviour {
public float ExplodeTimer = 2.5f;
public GameObject Explosion;
// Use this for initialization
void Start () {
StartCoroutine("Explode");
}
// Update is called once per frame
void Update () {
}
IEnumerator Explode()
{
yield return new WaitForSeconds(ExplodeTimer);
Instantiate(Explosion, this.transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
<file_sep>/Assets/RotCube/Scripts/SelfDestroy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelfDestroy : MonoBehaviour {
public float EliminateTimer = 1.5f;
// Use this for initialization
void Start () {
StartCoroutine("Eliminate");
}
// Update is called once per frame
void Update () {
}
IEnumerator Eliminate()
{
yield return new WaitForSeconds(EliminateTimer);
Destroy(gameObject);
}
}
<file_sep>/Assets/RotCube/Scripts/speech.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using FrostweepGames.Plugins.GoogleCloud.SpeechRecognition;
using System;
public class speech : MonoBehaviour
{
public TextMesh InformationMesh;
private GCSpeechRecognition _speechRecognition;
//private InputField _contextPhrases;
private ReactionManager _reactionManager;
public UnityEngine.XR.WSA.Input.GestureRecognizer InputActionRecognizer { get; private set; }
public enum State { Stop, Recording, Analyzing }
public State Status { get; private set; }
// 仮
private AudioSource _audioSource;
public AudioClip ChargeSound;
public AudioClip FireSound;
public AudioClip ThinkSound;
public AudioClip FailSound;
// 仮
void Awake()
{
InputActionRecognizer = new UnityEngine.XR.WSA.Input.GestureRecognizer();
InputActionRecognizer.SetRecognizableGestures(UnityEngine.XR.WSA.Input.GestureSettings.Hold);
InputActionRecognizer.HoldStartedEvent += InputActionRecognizer_HoldStartEvent;
InputActionRecognizer.HoldCompletedEvent += InputActionRecognizer_HoldCompletedEvent;
}
private void InputActionRecognizer_HoldStartEvent(UnityEngine.XR.WSA.Input.InteractionSourceKind source, Ray headRay)
{
_audioSource.clip = ChargeSound;
_audioSource.Play();
//StartRecordButtonOnClickHandler();
}
private void InputActionRecognizer_HoldCompletedEvent(UnityEngine.XR.WSA.Input.InteractionSourceKind source, Ray headRay)
{
_audioSource.clip = FireSound;
_audioSource.Play();
//StopRecordButtonOnClickHandler();
}
// Use this for initialization
void Start()
{
_speechRecognition = GCSpeechRecognition.Instance;
_speechRecognition.SetLanguage(Enumerators.LanguageCode.ja_JP);
_speechRecognition.RecognitionSuccessEvent += SpeechRecognizedSuccessEventHandler;
_speechRecognition.NetworkRequestFailedEvent += SpeechRecognizedFailedEventHandler;
_reactionManager = ReactionManager.Instance;
// 仮
_audioSource = GetComponent<AudioSource>();
if (_audioSource == null)
{
_audioSource = gameObject.AddComponent<AudioSource>();
}
_audioSource.playOnAwake = false;
_audioSource.spatialBlend = 1;
_audioSource.dopplerLevel = 0;
// 仮
Status = State.Stop;
}
// Update is called once per frame
void Update()
{
}
private void OnDestroy()
{
_speechRecognition.RecognitionSuccessEvent -= SpeechRecognizedSuccessEventHandler;
_speechRecognition.NetworkRequestFailedEvent -= SpeechRecognizedFailedEventHandler;
}
//private void ApplySpeechContextPhrases()
//{
// string[] phrases = _contextPhrases.text.Trim().Split(","[0]);
// if (phrases.Length > 0)
// _speechRecognition.SetSpeechContext(phrases);
//}
private void SpeechRecognizedFailedEventHandler(string obj, long l)
{
InformationMesh.text = "Speech Recognition failed with error: " + obj;
_audioSource.clip = FailSound;
_audioSource.Play();
Status = State.Stop;
}
private void SpeechRecognizedSuccessEventHandler(RecognitionResponse obj, long l)
{
if (obj != null && obj.results.Length > 0)
{
// InformationMesh.text = "Speech Recognition succeeded! Detected Most useful: " + obj.results[0].alternatives[0].transcript;
InformationMesh.text = "" + obj.results[0].alternatives[0].transcript;
/*
string other = "\nDetected alternative: ";
foreach (var result in obj.results)
{
foreach (var alternative in result.alternatives)
{
if (obj.results[0].alternatives[0] != alternative)
other += alternative.transcript + ", ";
}
}
InformationMesh.text += other;
*/
SpeechReaction(obj);
}
else
{
InformationMesh.text = "Speech Recognition succeeded! Words are no detected.";
_audioSource.clip = FailSound;
_audioSource.Play();
}
Status = State.Stop;
}
private void SpeechReaction(RecognitionResponse obj)
{
_reactionManager.Action(obj);
}
private void StopRuntimeDetectionButtonOnClickHandler()
{
_speechRecognition.StopRecord();
InformationMesh.text = "";
}
public void StartRecordButtonOnClickHandler()
{
if (Status == State.Stop)
{
InformationMesh.text = "";
_speechRecognition.StartRecord(false);
Status = State.Recording;
}
}
public void StopRecordButtonOnClickHandler()
{
if (Status == State.Recording)
{
//ApplySpeechContextPhrases();
_speechRecognition.StopRecord();
Status = State.Analyzing;
}
}
}
<file_sep>/Assets/RotCube/Scripts/SpaceTapInputManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using Cursor = HoloToolkit.Unity.InputModule.Cursor;
public class SpaceTapInputManager : MonoBehaviour
{
public enum TapSpeechState { Stop, Active }
public TapSpeechState TapSpeechStatus { get; private set; }
private AnimatedCursor _cursor;
private CursorStateEnum _cursorState;
public TextMesh InformationMesh;
private bool _isCharge = false;
// Action Driver
private speech _speech;
private SoundManager _soundManager;
private ReactionManager _reactioManager;
// Use this for initialization
void Start () {
_speech = GameObject.Find("InputManager").GetComponent<speech>();
_soundManager = GetComponent<SoundManager>();
_reactioManager = GameObject.Find("InputManager").GetComponent<ReactionManager>();
_cursor = GameObject.Find("DefaultCursor").GetComponent<AnimatedCursor>();
TapSpeechStatus = TapSpeechState.Stop;
}
// Update is called once per frame
void Update ()
{
//InformationMesh.text = "CursorStare: " + (int)_cursor.CursorState;
// 無空間注視:2 あたり注視:3 クリック:4
if (_cursor.CursorState != CursorStateEnum.None && _cursorState != _cursor.CursorState)
{
OnCursorChanged(_cursorState, _cursor.CursorState);
_cursorState = _cursor.CursorState;
}
}
private void OnCursorChanged(CursorStateEnum oldVal, CursorStateEnum newVal)
{
InformationMesh.text = "CurSor old:" + oldVal + " NewVal:" + newVal;
if (_isCharge == false && oldVal != CursorStateEnum.Select && newVal == CursorStateEnum.Select)
{
if (TapSpeechStatus == TapSpeechState.Stop && _speech.Status == speech.State.Stop)
{
_soundManager.Play(0);
_speech.StartRecordButtonOnClickHandler();
_reactioManager.BulletSourceIndex = 0;
TapSpeechStatus = TapSpeechState.Active;
}
else
{
_soundManager.Play(2);
}
_isCharge = true;
}
else if (_isCharge == true && oldVal == CursorStateEnum.Select && newVal != CursorStateEnum.Select)
{
if (TapSpeechStatus == TapSpeechState.Active && _speech.Status == speech.State.Recording)
{
_speech.StopRecordButtonOnClickHandler();
TapSpeechStatus = TapSpeechState.Stop;
}
_isCharge = false;
_soundManager.Play(3);
}
}
public void OnInputDown(InputEventData eventData)
{
if (TapSpeechStatus == TapSpeechState.Stop && _speech.Status == speech.State.Stop)
{
_speech.StartRecordButtonOnClickHandler();
_reactioManager.BulletSourceIndex = 0;
TapSpeechStatus = TapSpeechState.Active;
}
else
{
_soundManager.Play(2);
}
}
public void OnInputUp(InputEventData eventData)
{
if (TapSpeechStatus == TapSpeechState.Active && _speech.Status == speech.State.Recording)
{
_speech.StopRecordButtonOnClickHandler();
}
_soundManager.Play(3);
}
public void OnInputClicked(InputClickedEventData eventData)
{
//
}
}
<file_sep>/README.md
# SpeechGoUnity -言霊発射装置-
HoloLensで言霊を発射するアプリです。
[](https://www.youtube.com/watch?v=CfBzbpxRcrA)
## 動作環境
Unity 2017.2.0f3
## ビルド方法
1. ソースのダウンロード
例えば以下のようなコマンドでソースを入手する
```
git clone <EMAIL>:m2wasabi/SpeechGoUnity.git
```
2. アセットの組み込み
以下のアセットを入手してプロジェクトに追加する。
Google Cloud Speech Recognition は有料アセット($20)なので気を付けよう。
+ [Google Cloud Speech Recognition(V3.1)](https://www.assetstore.unity3d.com/jp/#!/content/72625)
+ [Cannon on a Platform](https://www.assetstore.unity3d.com/jp/#!/content/57534)
+ [HoloToolkit-Unity(v1.2017.2.0)](https://github.com/Microsoft/HoloToolkit-Unity)
+ StandardAssets/ParticleSystems
3. プロジェクト・シーンの再読み込みを行う
4. Google Croud Speech API が利用できるAPIキーを入手する
参考URL: [クイックスタート Speech API – 音声認識 | Google Cloud Platform](https://cloud.google.com/speech/docs/getting-started?hl=ja)
`Hierarchy`内の`GCSpeechRecognition` オブジェクトの `Api Key` プロパティに入手したキーを記入する
5. Universal Windows Platform 用にアプリをビルドする
参考URL: [ホログラム 100 | Holographic Academyの日本語訳](https://github.com/HoloMagicians/HolographicAcademyJP/blob/master/Academy/holograms_100.md)
4章を読むと良い
## 遊び方
### 基本的な操作法
|アクション|操作|
|---|---|
|視線の方向に言霊を飛ばす|エアタップしたまま喋る→指を離す|
|砲台から言霊を飛ばす|砲台の底に向けて話しかける→目をそらす|
|砲台を視線の正面に呼ぶ|「Cannon, come here」と喋る|
### 言霊エフェクト
|台詞|効果|
|---|---|
|爆発|一定時間後に言霊が爆発する|
|最高|歓声に包まれながら言霊が発射される|
| da96faab4f1bd52693919d24aaa00125214531a9 | [
"Markdown",
"C#"
] | 10 | C# | m2wasabi/SpeechGoUnity | 8ee53370543fd69ae5857b7fc6444b86c1e9f140 | 38b2c85406da1957df6d1a29d825bc4955e9276f |
refs/heads/master | <file_sep>BucleWhile
==========
Estructura sencilla del bucle while en python
<file_sep>i = 1
while i < 5:
print (i)
i += 1
print "terminado"
| 33c3c9cb717725f8554a9237d96fe884f1a80928 | [
"Markdown",
"Python"
] | 2 | Markdown | CodeFluid/BucleWhile | f2f88c0e3f38fd5a1419c2de23f080c8fe009c73 | 41a51f50cbd2e30c38b51322e3c895bc5108018e |
refs/heads/main | <repo_name>lucasrc98/arena_react<file_sep>/src/components/Enemy.jsx
import React from "react"
function Enemy(props) {
console.log(props)
return(
<div >
<h1>I'm the enemy {props.name}</h1>
<img src={props.image} height="100px" alt="imageEnemy"/>
</div>
)
}
export default Enemy;<file_sep>/src/util/constants.js
import img1 from '../images/hero.jpg'
import img2 from '../images/enemy.jpg'
export const HERO_IMAGE=img1
export const ENEMY_IMAGE=img2
export const TESTE="TESTE CONSTANTE"<file_sep>/src/components/Arena.jsx
import { render } from "@testing-library/react";
import Enemy from "./Enemy";
import Hero from "./Hero";
import * as constants from '../util/constants'
const imgHero = constants.HERO_IMAGE
const imgEnemy = constants.ENEMY_IMAGE
const text = constants.TESTE
function Arena(){
render()
return(
<div>
<h1>{text}</h1>
<Hero name="Saitama" image={imgHero}/>
<Enemy name="Boros" image={imgEnemy}/>
</div>
)
}
export default Arena;<file_sep>/src/components/Hero.jsx
import React from "react"
function Hero (props) {
console.log(props)
return(
<div >
<h1>I'm the hero {props.name}</h1>
<img src={props.image} height="100px" alt="imageHero"/>
</div>
)
}
export default Hero; | 6b324ccaa6a760c1ad17049ea35662cfe510d035 | [
"JavaScript"
] | 4 | JavaScript | lucasrc98/arena_react | 99342f7f0a17daf85b8e368f7d4e4c01e0ef67e4 | a5072108c0e9872d3e08abb0788cfd4420739af0 |
refs/heads/master | <repo_name>antspengy/CleaningDataProject<file_sep>/README.md
### Introduction
This project was developed as part of the Coursera 'Getting and Cleaning Data Course Project'.
The purpose of this project was to demonstrate my ability to collect, work with, and clean a data set. The goal was to prepare tidy data that can be used for later analysis.
### Information about the raw data that was collected and cleaned
The raw data that is processed being collected, relates to wearable computing.
The data analysed represents data collected from the accelerometers from the Samsung Galaxy S smartphone.
A full description is available at the site where the data was obtained:
http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
Here are the data for the project:
https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip
### Information about the process used to clean and analyse the data
An R script called run_analysis.R which was created and is available in this repository that
automatically does all the steps required to download, clean, and analyse the data.
The output of the R script is a file called 'variable_averages.txt' that is an independent, tidy data set containing
the average of each variable for each activity and each subject from the raw data.
A codebook Codebook.MD is also in the repository and contains more information about each of the variables in the 'variable_averages.txt' data set:
The high level steps undertaken by the run_analysis.R script are:
Step 0 - Downloads and unzips the dataset from the website link above.
Step 1 - Merges the training and the test sets to create one data set.
Step 2 - Extracts only the measurements on the mean and standard deviation for each measurement.
Step 3 - Uses descriptive activity names to name the activities in the data set
Step 4 - Appropriately labels the data set with descriptive variable names.
Step 5 - From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
### Detailed information about each step undertaken by the run_analysis.R script:
The detailed steps undertaken by the run_analysis.R file are described below. This information is also provided as
commnets within the run_analysis.R file as well to assist people reading the code:
STEP 0 - DOWNLOADS AND UNZIPS DATA SET FILES
In this step the script checks to see whether an '/assignmentdata' folder is in the
current working directory, and creates one if there isn't. The zip file is downloaded
to the folder and is then unzipped.
STEP 1 - MERGING DATA SET FILES INTO ONE FILE
During this step the script merges the various training and test sets of the dataset to
create one data set.
- It creates dataframes for each of the three test files
- It then creates dataframes for each of the three training files
- It then merges each of the test and training dataframes together and then merge them
into one dataframe "fullmerged"
- Each of the variables in the 'fullmerged' dataframe aren't labelled so the scripts need to
get the variable names from the features.txt file and then assign
them to each column of the 'fullmerged' dataframe. It also adds
labels for the first two columns ('subject' and 'activity').
STEP 2 - EXTRACT MEASUREMENTS OF MEAN AND STANDARD DEVIATION
The script identifies the columns that have "Mean()", "mean()", "Std()", or "std()"
in the column labels and then extracts these columns and the 'subject' and 'activity'
columns into a new data set 'extracteddata'
STEP 3 - USE DESCRIPTIVE ACTIVITY NAMES IN DATASET
The script loads the activity description file and then replaces the numeric values
in the activityid column with activity descriptions that are more meaningful.
e.g. All '1' values are replaced with 'WALKING'.
STEP 4 - MAKE VARIABLE NAMES MORE MEANINGFUL
The script replaces the variable names in the dataset to more meaningful names
by:
- making them lower case
- substituting abbreviations with descriptions (e.g. 'std' become 'standarddeviation')
- removing hyphens and brackets
STEP 5 - CREATE NEW, TIDY DATA SET WITH VARIABLE AVERAGES BY ACTIVITY AND SUBJECT
The script creates a new dataframe 'variableaverages' with the average of each variable for
each activity and for each subject. It then writes the dataframe to a text file called
'variable_averages.txt' that is saved in the 'assignmentdata' folder.
<file_sep>/CodeBook.md
### Codebook for variable_averages.txt
This codebook describes each variable and its values in the tidy data set
'variable_aveages.txt' generated by the run_analysis.R script. More information about the
script and the context of this data set is available in the README.md
file contained within this repository.
Each of the 180 observations within the file displays the average of 66 variables
extracted from the raw smartphone data set that related to measurements in the
raw data relating to the mean and standard deviation of movements of a
Samsung Galaxy S smartphone by 30 subjects undertaking 6 different activities.
The first two columns of the data set show the subject ID and the activity.
### Variables and Descriptions
subject - an integer between 1 and 30 representing the id of the subject
activity - a factor field showing which of the 6 activities were being undertaken.
Allowed values were (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LYING)
tbodyaccelerometermeanx - a number between -1 and 1 showing the average value of the tbodyaccelerometermeanx variable
tbodyaccelerometermeany - a number between -1 and 1 showing the average value of the tbodyaccelerometermeany variable
tbodyaccelerometermeanz - a number between -1 and 1 showing the average value of the tbodyaccelerometermeanz variable
tbodyaccelerometerstandarddeviationx - a number between -1 and 1 showing the average value of the tbodyaccelerometerstandarddeviationx variable
tbodyaccelerometerstandarddeviationy - a number between -1 and 1 showing the average value of the tbodyaccelerometerstandarddeviationy variable
tbodyaccelerometerstandarddeviationz - a number between -1 and 1 showing the average value of the tbodyaccelerometerstandarddeviationz variable
tgravityaccelerometermeanx - a number between -1 and 1 showing the average value of the tgravityaccelerometermeanx variable
tgravityaccelerometermeany - a number between -1 and 1 showing the average value of the tgravityaccelerometermeany variable
tgravityaccelerometermeanz - a number between -1 and 1 showing the average value of the tgravityaccelerometermeanz variable
tgravityaccelerometerstandarddeviationx - a number between -1 and 1 showing the average value of the tgravityaccelerometerstandarddeviationx variable
tgravityaccelerometerstandarddeviationy - a number between -1 and 1 showing the average value of the tgravityaccelerometerstandarddeviationy variable
tgravityaccelerometerstandarddeviationz - a number between -1 and 1 showing the average value of the tgravityaccelerometerstandarddeviationz variable
tbodyaccelerometerjerkmeanx - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkmeanx variable
tbodyaccelerometerjerkmeany - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkmeany variable
tbodyaccelerometerjerkmeanz - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkmeanz variable
tbodyaccelerometerjerkstandarddeviationx - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkstandarddeviationx variable
tbodyaccelerometerjerkstandarddeviationy - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkstandarddeviationy variable
tbodyaccelerometerjerkstandarddeviationz - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkstandarddeviationz variable
tbodygyroscopemeanx - a number between -1 and 1 showing the average value of the tbodygyroscopemeanx variable
tbodygyroscopemeany - a number between -1 and 1 showing the average value of the tbodygyroscopemeany variable
tbodygyroscopemeanz - a number between -1 and 1 showing the average value of the tbodygyroscopemeanz variable
tbodygyroscopestandarddeviationx - a number between -1 and 1 showing the average value of the tbodygyroscopestandarddeviationx variable
tbodygyroscopestandarddeviationy - a number between -1 and 1 showing the average value of the tbodygyroscopestandarddeviationy variable
tbodygyroscopestandarddeviationz - a number between -1 and 1 showing the average value of the tbodygyroscopestandarddeviationz variable
tbodygyroscopejerkmeanx - a number between -1 and 1 showing the average value of the tbodygyroscopejerkmeanx variable
tbodygyroscopejerkmeany - a number between -1 and 1 showing the average value of the tbodygyroscopejerkmeany variable
tbodygyroscopejerkmeanz - a number between -1 and 1 showing the average value of the tbodygyroscopejerkmeanz variable
tbodygyroscopejerkstandarddeviationx - a number between -1 and 1 showing the average value of the tbodygyroscopejerkstandarddeviationx variable
tbodygyroscopejerkstandarddeviationy - a number between -1 and 1 showing the average value of the tbodygyroscopejerkstandarddeviationy variable
tbodygyroscopejerkstandarddeviationz - a number between -1 and 1 showing the average value of the tbodygyroscopejerkstandarddeviationz variable
tbodyaccelerometermagmean - a number between -1 and 1 showing the average value of the tbodyaccelerometermagmean variable
tbodyaccelerometermagstandarddeviation - a number between -1 and 1 showing the average value of the tbodyaccelerometermagstandarddeviation variable
tgravityaccelerometermagmean - a number between -1 and 1 showing the average value of the tgravityaccelerometermagmean variable
tgravityaccelerometermagstandarddeviation - a number between -1 and 1 showing the average value of the tgravityaccelerometermagstandarddeviation variable
tbodyaccelerometerjerkmagmean - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkmagmean variable
tbodyaccelerometerjerkmagstandarddeviation - a number between -1 and 1 showing the average value of the tbodyaccelerometerjerkmagstandarddeviation variable
tbodygyroscopemagmean - a number between -1 and 1 showing the average value of the tbodygyroscopemagmean variable
tbodygyroscopemagstandarddeviation - a number between -1 and 1 showing the average value of the tbodygyroscopemagstandarddeviation variable
tbodygyroscopejerkmagmean - a number between -1 and 1 showing the average value of the tbodygyroscopejerkmagmean variable
tbodygyroscopejerkmagstandarddeviation - a number between -1 and 1 showing the average value of the tbodygyroscopejerkmagstandarddeviation variable
fbodyaccelerometermeanx - a number between -1 and 1 showing the average value of the fbodyaccelerometermeanx variable
fbodyaccelerometermeany - a number between -1 and 1 showing the average value of the fbodyaccelerometermeany variable
fbodyaccelerometermeanz - a number between -1 and 1 showing the average value of the fbodyaccelerometermeanz variable
fbodyaccelerometerstandarddeviationx - a number between -1 and 1 showing the average value of the fbodyaccelerometerstandarddeviationx variable
fbodyaccelerometerstandarddeviationy - a number between -1 and 1 showing the average value of the fbodyaccelerometerstandarddeviationy variable
fbodyaccelerometerstandarddeviationz - a number between -1 and 1 showing the average value of the fbodyaccelerometerstandarddeviationz variable
fbodyaccelerometerjerkmeanx - a number between -1 and 1 showing the average value of the fbodyaccelerometerjerkmeanx variable
fbodyaccelerometerjerkmeany - a number between -1 and 1 showing the average value of the fbodyaccelerometerjerkmeany variable
fbodyaccelerometerjerkmeanz - a number between -1 and 1 showing the average value of the fbodyaccelerometerjerkmeanz variable
fbodyaccelerometerjerkstandarddeviationx - a number between -1 and 1 showing the average value of the fbodyaccelerometerjerkstandarddeviationx variable
fbodyaccelerometerjerkstandarddeviationy - a number between -1 and 1 showing the average value of the fbodyaccelerometerjerkstandarddeviationy variable
fbodyaccelerometerjerkstandarddeviationz - a number between -1 and 1 showing the average value of the fbodyaccelerometerjerkstandarddeviationz variable
fbodygyroscopemeanx - a number between -1 and 1 showing the average value of the fbodygyroscopemeanx variable
fbodygyroscopemeany - a number between -1 and 1 showing the average value of the fbodygyroscopemeany variable
fbodygyroscopemeanz - a number between -1 and 1 showing the average value of the fbodygyroscopemeanz variable
fbodygyroscopestandarddeviationx - a number between -1 and 1 showing the average value of the fbodygyroscopestandarddeviationx variable
fbodygyroscopestandarddeviationy - a number between -1 and 1 showing the average value of the fbodygyroscopestandarddeviationy variable
fbodygyroscopestandarddeviationz - a number between -1 and 1 showing the average value of the fbodygyroscopestandarddeviationz variable
fbodyaccelerometermagmean - a number between -1 and 1 showing the average value of the fbodyaccelerometermagmean variable
fbodyaccelerometermagstandarddeviation - a number between -1 and 1 showing the average value of the fbodyaccelerometermagstandarddeviation variable
fbodybodyaccelerometerjerkmagmean - a number between -1 and 1 showing the average value of the fbodybodyaccelerometerjerkmagmean variable
fbodybodyaccelerometerjerkmagstandarddeviation - a number between -1 and 1 showing the average value of the fbodybodyaccelerometerjerkmagstandarddeviation variable
fbodybodygyroscopemagmean - a number between -1 and 1 showing the average value of the fbodybodygyroscopemagmean variable
fbodybodygyroscopemagstandarddeviation - a number between -1 and 1 showing the average value of the fbodybodygyroscopemagstandarddeviation variable
fbodybodygyroscopejerkmagmean - a number between -1 and 1 showing the average value of the fbodybodygyroscopejerkmagmean variable
fbodybodygyroscopejerkmagstandarddeviation - a number between -1 and 1 showing the average value of the fbodybodygyroscopejerkmagstandarddeviation variable
<file_sep>/run_analysis.R
run_analysis <- function() {
## This run_analysis function downloads, cleans, and summarises
## data collected from the accelerometers from the Samsung Galaxy S smartphone
## It has been developed for the Coursera 'Getting and Cleaning Data Course Project'
## More information is available in the readme file.
## Step 0 - DOWNLOADS AND UNZIPS DATA SET FILES
## In this step we check to see whether an '/assignmentdata' folder is in the
## current working directory, and creates one if there isn't. The zip file is downloaded
## to the folder and is then unzipped.
if(!file.exists("./assignmentdata")){dir.create("./assignmentdata")}
fileurl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(fileurl,destfile="./assignmentdata/dataset.zip",method="auto")
unzip(zipfile="./assignmentdata/dataset.zip", exdir="./assignmentdata")
files_location <- "./assignmentdata/UCI HAR Dataset/"
## STEP 1 - MERGING DATA SET FILES INTO ONE FILE
## During this step we merge the various training and test sets of the dataset to
## create one data set. I
## creates dataframes for each of the three test files
subjecttest <- read.table(paste(files_location, "test/subject_test.txt", sep=""))
xtest <- read.table(paste(files_location, "test/X_test.txt", sep=""))
ytest <- read.table(paste(files_location, "test/y_test.txt", sep=""))
## creates dataframes for each of the three training files
subjecttrain <- read.table(paste(files_location, "train/subject_train.txt", sep=""))
xtrain <- read.table(paste(files_location, "train/X_train.txt", sep=""))
ytrain <- read.table(paste(files_location, "train/y_train.txt", sep=""))
## merges each of the test and training dataframes together and then merges them
## into one dataframe "fullmerged".
subjectmerged <- rbind(subjecttrain, subjecttest)
xmerged <- rbind(xtrain, xtest)
ymerged <- rbind(ytrain, ytest)
fullmerged <- cbind(subjectmerged, ymerged, xmerged)
## Each of the variables in the 'fullmerged' dataframe aren't labelled so we need to
## get the variable names from the features.txt file and then assign
## them to each column of the 'fullmerged' dataframe. We have to also add our own
## labels for the first two columns ('subject' and 'activity').
columnnames <- read.table(paste(files_location, "features.txt", sep=""))
variablenames<- as.character(columnnames$V2)
names(fullmerged) <- c("subject", "activity", variablenames)
## STEP 2 - EXTRACT MEASUREMENTS OF MEAN AND STANDARD DEVIATION
## This code identifies the columns that have "Mean()", "mean()", "Std()", or "std()"
## in the column labels and then extracts these columns and the subjectid and activityid
## columns into a new data set 'extracteddata'
columnstoselect <- grep("[Mm]ean\\(\\)|[Ss]td\\(\\)", names(fullmerged))
extracteddata <- fullmerged[,c(1, 2, columnstoselect)]
## STEP 3 - USE DESCRIPTIVE ACTIVITY NAMES IN DATASET
## This code loads the activity description file and then replaces the numeric values
## in the activityid column with activity descriptions that are more meaningful.
## e.g. All '1' values are replaced with 'WALKING'.
activitydescriptions <- read.table(paste(files_location, "activity_labels.txt", sep=""))
activitynames<- as.character(activitydescriptions$V2)
extracteddata$activity <- activitynames[extracteddata$activity]
extracteddata$activity <- as.factor(extracteddata$activity)
## STEP 4 - MAKE VARIABLE NAMES MORE MEANINGFUL
## This code replaces the variable names in the dataset to more meaningful names
## by:
## - making them lower case
## - substituting abbreviations with descriptions (e.g. 'std' become 'standarddeviation')
## - removing hyphens and brackets
names(extracteddata) <- tolower(names(extracteddata))
names(extracteddata) <- gsub("std","standarddeviation",names(extracteddata))
names(extracteddata) <- gsub("acc","accelerometer",names(extracteddata))
names(extracteddata) <- gsub("gyro","gyroscope",names(extracteddata))
names(extracteddata) <- gsub("-","",names(extracteddata))
names(extracteddata) <- gsub("\\(\\)","",names(extracteddata))
## STEP 5 - CREATE NEW, TIDY DATA SET WITH VARIABLE AVERAGES BY ACTIVITY AND SUBJECT
## This code creates a new dataframe 'variableaverages' with the average of each variable for
## each activity and for each subject. It then writes the dataframe to a text file called
## 'variable_averages.txt' that is saved in the 'assignmentdata' folder.
variableaverages <- aggregate(extracteddata[,(3:ncol(extracteddata))], by=list(subject=extracteddata$subject,activity=extracteddata$activity), FUN=mean, na.rm=TRUE)
write.table(variableaverages, row.names = FALSE, file = "./assignmentdata/variable_averages.txt")
}
| 9e3aa90a69e35ef2c7f2e2f3caf4322ba54eebf4 | [
"Markdown",
"R"
] | 3 | Markdown | antspengy/CleaningDataProject | ad2327f95c3531fac1d07c346fc0871a9761ec59 | 99ddc092763e83fab0cc2278f3a04c5f03109648 |
refs/heads/master | <repo_name>cecula-vereafy/php-library<file_sep>/balance.php
<?php
require_once 'Vereafy.php';
// Copy your API Key from the Cecula Developer Platform and paste below
$apiKey = '';
$vereafyClient = new Vereafy($apiKey);
echo $vereafyClient->getBalance()->balance;<file_sep>/complete.php
<?php
require_once 'Vereafy.php';
// Copy your API Key from the Cecula Developer Platform and paste below
$apiKey = '';
// The PIN REF that was initiated during the Init Request
$pinref = '';
// The token that your form user received on their mobile phone.
$token = '';
$vereafyClient = new Vereafy($apiKey);
echo $vereafyClient->complete($pinref, $token);<file_sep>/README.md
# Vereafy PHP Library
- [Vereafy PHP Library](#vereafy-php-library)
- [Introduction](#introduction)
- [Installation](#installation)
- [Installing with Composer](#installing-with-composer)
- [Installing from GitHub](#installing-from-github)
- [Including Library in Project](#including-library-in-project)
- [How to Get API Key](#how-to-get-api-key)
- [Initialization](#initialization)
- [Completion](#completion)
- [Resend](#resend)
- [Get Balance](#get-balance)
- [Error Responses](#error-responses)
----------
## Introduction
Vereafy is an SMS based 2-factor authentication services that uses machine learning to understand the causes of OTP delivery failures and resolves them instantly to ensure your login and sign up OTPs deliver.
## Installation
The Vereafy PHP Library Project was created to enable PHP Developers integrate seamlessly with the Vereafy API.
To use the Vereafy PHP library, you just need to clone this repo into your existing project directory and require the Vereafy class file (Vereafy.php) or install with composer.
#### Installing with Composer
composer require cecula/vereafy
#### Installing from GitHub
git clone https://github.com/cecula-vereafy/php-library vereafy
##Including Library in Project
If you installed the Vereafy Library using composer, use the following line to include project:
require_once "/path/to/vendor/autoload.php";
otherwise, if you cloned the GitHub repo you can simply require the project from the directory you save it to
require_once "/path/to/vereafy/Vereafy.php"
## How to Get API Key
Your API Key is first generated when you register an app. To register an app,
Login to the Developers Dashboard, Navigate to **Apps > Add**, Type the name of your app and click **Submit**. The app will be registered and a new API Key will be generated. Copy the API key into your project.
OR
Click [developer.cecula.com](https://developer.cecula.com/docs/introduction/generating-api-key) to get started.
## Initialization
The Vereafy 2FA initialization can be as simple as the following lines of code:
$vereafyInstance = new Vereafy(<your_APIKEY>);
$vereafyInstance->init(<your_MOBILE>);
The initialization method returns a response that should look like this:
{
"status":"success",
"pinRef": "1293488527"
}
## Completion
The Vereafy 2FA completion can be as simple as the following lines of code:
$vereafyInstance = new Vereafy(<your_APIKEY>);
$vereafyInstance->complete(<pinRef>, <VERIFICATION_CODE>);
The completion method returns a response that should look like this if the parameters are correct:
{
"response":"success"
}
## Resend
In a case where your app users get impatient and hits the retry link on your app form, just call the resend method this way:
$vereafyInstance = new Vereafy(<your_APIKEY>);
$vereafyInstance->resend(<your_MOBILE>, <pinRef>);
The resend method returns a response that should look like this:
{
"status": "success",
"pinRef": 1293488527
}
## Get Balance
To get your balance on Vereafy, the getbalance method is used this way:
$vereafyInstance = new Vereafy(<your_APIKEY>);
$vereafyInstance->getBalance();
The method requires no parameter, and the returned response should look like this:
{
"balance":1507
}
## Error Responses
In a case where the request fails due to one reason or another you should get an error response from the requested endpoint that looks like this:
{
"error":"Invalid PIN Ref",
"code":"CE2000"
}
The table below shows a list of error codes and their descriptions
| Error Code | Description |
|-------------------------------|----------------------|
| CE1001 | Missing Fields |
| CE1002 | Empty Fields |
| CE1006 | Not a Nigerian Number |
| CE2000 | Invalid PIN Ref|
| CE2002 | PIN does not reference any verification request|
| CE2003 | Mobile number does not match original request|
| CE2001 | Invalid PIN|
| CE2004 | Request Not Found |
| CE7000 | Verification already succeeded |
| CE7001 | Verification already failed |
| CE6000 | Insufficient Balance |
| CE5000 | Invalid Template ID |
| CE5001 | Could not find referenced template |
<file_sep>/Vereafy.php
<?php
/**
* Vereafy
* This library is manages all request to Cecula Vereafy services: Initialization,
* Completion and Resends.
*
* @category Two-Factor_Authentication
* @package Cecula_Vereafy
* @author <NAME> <<EMAIL>>
* @copyright 2019 Cecula Ltd.
* @license MIT https://vereafy.com/license
* @link https://vereafy.com
*/
class Vereafy
{
private $_host = 'https://api.cecula.com';
// The API KEY Generated at the Cecula Developer Platform
private $_apiKey = null;
// Replace the <api key> string with API Key generated on the cecula developer platform.
private $_header = [];
/**
* Constructor
*/
public function __construct($apiKey)
{
$this->_apiKey = $apiKey;
$this->_header = [
"Authorization: Bearer {$this->_apiKey}",
"Content-Type: application/json",
"cache-control: no-cache"
];
}
/**
* Resend OTP
* Some times for one reason or another your website or app users may not receive
* the code as soon as they expect. Use this method to submit their resend
* retry link to prevent double billing.
*
* @param int $pinRef The pinRef that was generated during init.
* @param string $mobile The mobile number that initialized the request.
*
* @return object
*/
public function resend($pinRef, $mobile)
{
$payload = [
'pinRef' => $pinRef,
'mobile' => $mobile
];
return $this->_makePostRequest('twofactor/resend', $payload);
}
/**
* Complete Verification
* This method is called when for completion of verification. At this stage the
* user must have provided the received OTP (token) on your website.
*
* @param int $pinRef A reference code for the token
* @param int $token Then token that was sent during init
*
* @return object
*/
public function complete($pinRef, $token)
{
$payload = [
'pinRef' => $pinRef,
'token' => $token
];
return $this->_makePostRequest('twofactor/complete', $payload);
}
/**
* Initialize Verification
* This method is the first to be called in any initialization request.
* It receives a mobile number, sends the mobile number to Vereafy Initialization
* endpoint, and returns a pinRef which will be used in subsequent calls.
*
* @param string $mobile The mobile number to be verified.
*
* @return object
*/
public function init($mobile)
{
$payload = [
'mobile' => $mobile
];
return $this->_makePostRequest('twofactor/init', $payload);
}
/**
* Get Balance
* This method can be used for querying Vereafy for account balance. Knowing
* balances in realtime can help you prevent service outage. A situation where
* Verification codes do not deliver due to insufficient credit.
*
* @return object
*/
public function getBalance()
{
return $this->_makeGetRequest('account/tfabalance');
}
/**
* Make POST Request.
* This is a private method that handles all http POST connection to Vereafy.
*
* @param string $endpoint The endpoint where request should be submitted to.
* @param array $payload An array of data that will be submitted to Vereafy.
*
* @return void
*/
private function _makePostRequest($endpoint, $payload)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_host.'/'.$endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
return $error ? $error : json_decode($response);
}
/**
* Make GET Request
* This is a private method that will handles all HTTP GET Request to Vereafy.
*
* @param string $endpoint The URL where request will be sent.
*
* @return object
*/
private function _makeGetRequest($endpoint)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_host.'/'.$endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
return $error ? $error : json_decode($response);
}
}<file_sep>/init.php
<?php
require_once 'Vereafy.php';
// Copy your API Key from the Cecula Developer Platform and paste below
$apiKey = '';
// The mobile number that your form user submitted.
$mobile = '';
$vereafyClient = new Vereafy($apiKey);
echo $vereafyClient->init($mobile);<file_sep>/resend.php
<?php
require_once 'Vereafy.php';
// Copy your API Key from the Cecula Developer Platform and paste below
$apiKey = '';
// The PIN REF that was initiated during the Init Request
$pinref = '';
// The mobile number that your form user submitted.
$mobile = '';
$vereafyClient = new Vereafy($apiKey);
echo $vereafyClient->resend($pinref, $mobile); | 16f30628831723fe5626a64fb255ba993741ba96 | [
"Markdown",
"PHP"
] | 6 | PHP | cecula-vereafy/php-library | dfb11e3886b1ce6d1401fdee2bc91626e25e3479 | a5d0b81198988742786bc00a9fa24d82c630c9e3 |
refs/heads/master | <file_sep><?php
/****************************** Temporal Expressions ******************************/
/**
*
*/
class BusinessHoursTEDay implements iBusinessHoursTemporalExpression {
/**
* @var
*/
private $_day;
/**
* @param $day
*/
public function __construct( $day ) {
$this->_day = $day;
}
/**
* @param $date
*
* @return bool
*/
public function includes( $date ) {
if ( $this->_day === 'every' )
return true;
if ( $this->_day === 'monfri' && !$this->is_weekend( $date ) )
return true;
if ( $this->_day === 'satsun' && $this->is_weekend( $date ) )
return true;
if ( intval( $this->_day ) === intval( date( 'j', strtotime( $date ) ) ) )
return true;
return false;
}
/**
* @param $date
*
* @return bool
*/
private function is_weekend( $date ) {
$weekDay = date( 'w', strtotime( $date ) );
return ( $weekDay == 0 || $weekDay == 6 );
}
}
/**
*
*/
class BusinessHoursTEMonth implements iBusinessHoursTemporalExpression {
/**
* @var
*/
private $_month;
/**
* @param $month
*/
public function __construct( $month ) {
$this->_month = $month;
}
/**
* @param $date
*
* @return bool
*/
public function includes( $date ) {
if ( $this->_month === 'every' )
return true;
if ( intval( $this->_month ) === intval( date( 'n', strtotime( $date ) ) ) )
return true;
return false;
}
}
/**
*
*/
class BusinessHoursTEYear implements iBusinessHoursTemporalExpression {
/**
* @var
*/
private $_year;
/**
* @param $year
*/
public function __construct( $year ) {
$this->_year = $year;
}
/**
* @param $date
*
* @return bool
*/
public function includes( $date ) {
if ( $this->_year === 'every' )
return true;
if ( intval( $this->_year ) === intval( date( 'Y', strtotime( $date ) ) ) )
return true;
return false;
}
}
/****************************** SETS ******************************/
/**
*
*/
class BusinessHoursSetIntersection extends BusinessHoursSet {
/**
* @param $method
* @param $arguments
*
* @return bool
* @throws Exception
*/
public function __call( $method, $arguments ) {
if ( !method_exists( $this->_setInterface, $method ) ) {
throw new Exception( "$method is not defined in $this->_setInterface" );
}
if ( empty( $this->_elements ) )
return false;
foreach ( $this->_elements as $element )
if ( !call_user_func_array( array( $element, $method ), $arguments ) )
return false;
return $this->_storage;
}
}
/**
*
*/
class BusinessHoursSetUnion extends BusinessHoursSet {
/**
* @param $method
* @param $arguments
*
* @return bool
* @throws Exception
*/
public function __call( $method, $arguments ) {
if ( !method_exists( $this->_setInterface, $method ) ) {
throw new Exception( "$method is not defined in $this->_setInterface" );
}
if ( empty( $this->_elements ) )
return false;
foreach ( $this->_elements as $element )
if ( call_user_func_array( array( $element, $method ), $arguments ) )
return $element->_storage;
return false;
}
}
/****************************** HELPERS ******************************/
/**
*
*/
abstract class BusinessHoursSet {
protected $_setInterface = null;
protected $_elements = array();
protected $_storage = true;
public function __construct( $setInterface ) {
if ( !is_string( $setInterface ) ) {
throw new Exception( "Interface must be a string." );
}
if ( !interface_exists( $setInterface, true ) ) {
throw new Exception( "$setInterface is not a valid interface." );
}
$this->_setInterface = $setInterface;
}
/**
* @param $element
*
* @param $storage
*
* @throws Exception
*/
public function addElement( $element, $storage = array() ) {
if ( $element instanceof $this->_setInterface || $element instanceof BusinessHoursSet ) {
$this->_elements[] = $element;
if ( !empty( $storage ) )
$this->_storage = $storage;
} else {
throw new Exception( "Element must implement $this->_setInterface or Set" );
}
}
public function setStorage( $storage = array() ) {
if ( !empty( $storage ) )
$this->_storage = $storage;
}
}
/**
*
*/
interface iBusinessHoursTemporalExpression {
/**
* @abstract
*
* @param $date
*
* @return mixed
*/
public function includes( $date );
}
<file_sep>jQuery( document ).ready( function ( $ ) {
$( "#exception_add" ).on( 'click', function ( e ) {
var $item = $( ".exception_date" ).first().clone();
var $count = $( '.exception_date' ).length;
var $new_id = $count + 1;
$item.attr( 'id', 'exception_' + $new_id );
$item.find( '.exception_remove' ).attr( 'data-id', $new_id );
$item.find( '.exception_number' ).val( $new_id );
$item.hide().appendTo( '#exceptions_wrapper' ).slideDown( '150' );
} );
$( '#exceptions_wrapper' ).on( 'click', '.exception_remove', function ( e ) {
var $id = $( this ).attr( 'data-id' );
$( '.exception_remove_label' ).attr( 'disabled', 'disabled' );
$( '#exception_' + $id ).slideUp( '150', function () {
$( '#exception_' + $id ).remove();
} );
$( '.exception_remove_label' ).removeAttr( 'disabled' );
} );
function toggle_remove_buttons() {
var $count = $( '.exception_date' ).length;
if ( $count > 1 ) {
$( '.exception_remove_label' ).show();
} else {
$( '.exception_remove_label' ).hide();
}
}
} );
<file_sep><?php if ( $collapsible_link ) { ?>
<div class="business_hours_collapsible_handler_container">
<a class="business_hours_collapsible_handler" href="#"><?php _e( $collapsible_link_anchor, "business-hours" );?></a>
</div>
<div class="business_hours_collapsible">
<?php } ?>
<table width='100%'>
<tr>
<th><?php _e( "Day", "business-hours" );?></th>
<th class='business_hours_table_heading'><?php _e( "Open", "business-hours" );?></th>
<th class='business_hours_table_heading'><?php _e( "Close", "business-hours" );?></th>
</tr>
<?php
foreach ( $days as $id => $day ) {
$this->_table_row( $id, $day );
}
?>
</table>
<?php if ( $collapsible_link ) { ?>
</div>
<?php } ?><file_sep><div class="exception_date" id="exception_<?php echo $exception_number;?>">
<label for="exception_day"><?php _e( 'Day:', 'business-hours' );?>
<select name="exception_day[]" id='exception_day'>
<?php $this->_show_exception_days( $day ); ?>
</select>
</label>
<label for="exception_month"><?php _e( 'Month:', 'business-hours' );?>
<select name="exception_month[]" id='exception_month'>
<?php $this->_show_exception_months( $month ); ?>
</select>
</label>
<label for="exception_month"><?php _e( 'Year:', 'business-hours' );?>
<select name="exception_year[]" id='exception_year'>
<?php $this->_show_exception_years( $year ); ?>
</select>
</label>
<label for="exception_open"><?php _e( 'Open:', 'business-hours' );?>
<input name="exception_open[]" id="exception_open"
class="business_hours_exception_hour_field" type="text" value="<?php echo $open; ?>"/>
</label>
<label for="exception_close"><?php _e( 'Close:', 'business-hours' );?>
<input name="exception_close[]" id="exception_close"
class="business_hours_exception_hour_field" type="text" value="<?php echo $close; ?>"/>
</label>
<label class="exception_remove_label" for="exception_remove">
<input type="button" name="exception_remove" class="exception_remove bh-button"
data-id='<?php echo $exception_number;?>' value="<?php _e( 'Remove', 'business-hours' );?>"/>
</label>
<div class="bh_clear"></div>
</div><file_sep><?php
class BusinessHoursExceptions {
const SETTINGS_EXCEPTIONS = 'exceptions';
private static $_instance;
private static $_today_id = null;
private static $_today_exception = null;
private static $_today_date = null;
private static $_actual_dates = array();
/**
* @var BusinessHoursSet
*/
private $_exceptions = null;
public function __construct() {
require_once 'BusinessHoursTemporalExpressionsEngine.class.php';
add_action( 'business-hours-settings-page', array( $this, 'show_exceptions_settings' ), 2 );
add_filter( 'business-hours-save-settings', array( $this, 'maybe_save_settings_exceptions' ), 2 );
add_filter( 'business-hours-row-class', array( $this, 'maybe_add_exception_class' ), 2, 3 );
add_action( 'business-hours-before-row', array( $this, 'maybe_setup_exception' ), 1, 5 );
add_action( 'business-hours-after-row', array( $this, 'maybe_show_exception' ), 1, 5 );
}
/**
* @param $date
*
* @return mixed
*/
public function get_exceptions_for_date( $date ) {
if ( !$this->_exceptions )
$this->_build_exceptions_rules();
return $this->_exceptions->includes( $date );
}
/**
* @param $id
*
* @return mixed
*/
public function get_exceptions_for_day_id( $id ) {
$dates = $this->_pre_compute_this_week_actual_dates();
$day = date_i18n( get_option( 'date_format' ), $dates[$id] );
return $this->get_exceptions_for_date( $day );
}
public function get_localized_date_for_day_id( $id ) {
$dates = $this->_pre_compute_this_week_actual_dates();
return date_i18n( get_option( 'date_format' ), $dates[$id] );
}
/**
* @param $id
* @param $day_name
* @param $open
* @param $close
* @param $is_open_today
*/
public function maybe_setup_exception( $id, $day_name, $open, $close, $is_open_today ) {
$dates = $this->_pre_compute_this_week_actual_dates();
self::$_today_date = date_i18n( get_option( 'date_format' ), $dates[$id] );
self::$_today_exception = $this->get_exceptions_for_date( self::$_today_date );
}
/**
* @param $id
* @param $day_name
* @param $open
* @param $close
* @param $is_open_today
*/
public function maybe_show_exception( $id, $day_name, $open, $close, $is_open_today ) {
if ( !self::$_today_exception )
return;
$day_name = self::$_today_date;
$open = self::$_today_exception['open'];
$close = self::$_today_exception['close'];
$is_open_today = !empty( $open ) && !empty( $close );
$closed_text = business_hours()->settings()->get_default_closed_text();
$class = 'business_hours_table_day_exception';
include business_hours()->locate_view( 'table-row.php' );
self::$_today_exception = null;
self::$_today_date = null;
self::$_today_id = null;
}
public function maybe_add_exception_class( $class, $id, $day_name ) {
if ( !self::$_today_exception )
return $class;
return $class . ' business_hours_has_exception';
}
/************ HELPERS ***********/
/**
* @param null $exceptions
*
* @return BusinessHoursSet
*/
private function _build_exceptions_rules( $exceptions = null ) {
if ( !$exceptions )
$exceptions = $this->_get_exceptions();
$union = new BusinessHoursSetUnion( 'iBusinessHoursTemporalExpression' );
foreach ( (array) $exceptions as $exception ) {
$day = new BusinessHoursTEDay( $exception['day'] );
$month = new BusinessHoursTEMonth( $exception['month'] );
$year = new BusinessHoursTEYear( $exception['year'] );
$intersection = new BusinessHoursSetIntersection( 'iBusinessHoursTemporalExpression' );
$intersection->addElement( $day );
$intersection->addElement( $month );
$intersection->addElement( $year );
$intersection->setStorage( array( 'open' => $exception['open'], 'close' => $exception['close'] ) );
$union->addElement( $intersection );
}
$this->_exceptions = $union;
}
/**
* Populates a cache array with the actual dates for this week days. It takes into
* account what days are displayed after and before today to generate the dates, so
* the dates are always consecutive.
*
* Oh boy, it'd be so much easier to assume Sunday=0, Saturday=6 and be done with it
* But I commited to honor custom "Week Starts On" settings, so, we need to do this.
*
* @return string
*/
private function _pre_compute_this_week_actual_dates() {
if ( !empty( self::$_actual_dates ) )
return self::$_actual_dates;
$today = key( business_hours()->get_day_using_timezone() );
$days = business_hours()->get_week_days();
$modifier = "Last";
foreach ( $days as $did => $name ) {
if ( $did == $today ) {
$modifier = "Next";
$today_date = business_hours()->get_timestamp_using_timezone();
} else {
$today_date = strtotime( $modifier . ' ' . $name );
}
self::$_actual_dates[$did] = $today_date;
}
return self::$_actual_dates;
}
/**
* @return mixed
*/
private function _get_exceptions() {
$settings = business_hours()->settings()->get_full_settings();
return $settings[self::SETTINGS_EXCEPTIONS];
}
/************ SETTINGS ***********/
/**
*
*/
public function show_exceptions_settings() {
include business_hours()->locate_view( 'settings-exceptions.php' );
}
/**
* @param $cache
*
* @return array
*/
public function maybe_save_settings_exceptions( $cache ) {
$cache[self::SETTINGS_EXCEPTIONS] = array();
if ( empty( $_POST['exception_day'] ) )
return $cache;
$days = $_POST['exception_day'];
$months = $_POST['exception_month'];
$years = $_POST['exception_year'];
$open = $_POST['exception_open'];
$close = $_POST['exception_close'];
/* No exceptions */
if ( empty( $days ) )
return $cache;
foreach ( $days as $index => $day ) {
/* The first one is the model jQuery uses to clone.
* It's invisible to the user and we dont' care about it */
if ( $index === 0 )
continue;
$cache[self::SETTINGS_EXCEPTIONS][] = array( 'day' => $day,
'month' => $months[$index],
'year' => $years[$index],
'open' => $open[$index],
'close' => $close[$index] );
}
$this->_build_exceptions_rules( $cache[self::SETTINGS_EXCEPTIONS] );
return $cache;
}
/************ SETTINGS HELPERS ***********/
/**
*
*/
private function _show_exceptions() {
$exceptions = $this->_get_exceptions();
// Include hidden base rule, for jQuery to clone
$exception_number = 0;
$day = $month = $year = $open = $close = '';
include business_hours()->locate_view( 'settings-exception-single.php', false );
foreach ( (array) $exceptions as $exception_number => $exception ) {
// 0 is reserverd for the base rule
$exception_number++;
$day = esc_attr( $exception['day'] );
$month = esc_attr( $exception['month'] );
$year = esc_attr( $exception['year'] );
$open = esc_attr( $exception['open'] );
$close = esc_attr( $exception['close'] );
include business_hours()->locate_view( 'settings-exception-single.php', false );
}
}
/**
*
*/
private function _show_exceptions_instructions() {
$exception_number = 0;
include business_hours()->locate_view( 'settings-exception-instructions.php' );
}
/**
* @param $selected
*/
private function _show_exception_days( $selected ) {
echo sprintf( '<option %s value="%s">%s</option>', selected( $selected, 'every', false ), 'every', __( 'Every day', 'business-hours' ) );
echo sprintf( '<option %s value="%s">%s</option>', selected( $selected, 'monfri', false ), 'monfri', __( 'Mondays to Fridays', 'business-hours' ) );
echo sprintf( '<option %s value="%s">%s</option>', selected( $selected, 'satsun', false ), 'satsun', __( 'Saturdays and Sundays', 'business-hours' ) );
for ( $i = 1; $i < 32; $i++ ) {
echo sprintf( '<option %s value="%2$d">%2$d</option>', selected( intval( $selected ), intval( $i ), false ), $i );
}
}
/**
* @param $selected
*/
private function _show_exception_months( $selected ) {
echo sprintf( '<option %s value="%s">%s</option>', selected( $selected, 'every', false ), 'every', __( 'Every month', 'business-hours' ) );
global $wp_locale;
foreach ( $wp_locale->month as $id => $month ) {
echo sprintf( '<option %s value="%d">%s</option>', selected( intval( $selected ), intval( $id ), false ), $id, $month );
}
}
/**
* @param $selected
*/
private function _show_exception_years( $selected ) {
echo sprintf( '<option %s value="%s">%s</option>', selected( $selected, 'every', false ), 'every', __( 'Every year', 'business-hours' ) );
$this_year = date( 'Y', time() );
$limit = apply_filters( 'business-hours-exceptions-how-many-years', 10 );
for ( $i = 0; $i < $limit; $i++ ) {
echo sprintf( '<option %s value="%d">%s</option>', selected( intval( $selected ), intval( $this_year ), false ), $this_year, $this_year );
$this_year++;
}
}
/**
* @static
* @return BusinessHoursExceptions
*/
public static function instance() {
if ( !isset( self::$_instance ) ) {
$className = __CLASS__;
self::$_instance = new $className;
}
return self::$_instance;
}
}
<file_sep><table class="form-table">
<tr>
<td>
<div>
<h3><?php _e( 'Business hours for each day of the week', 'business-hours' );?></h3>
<p><?php _e( "Leave the fields empty for the days your business is closed.", 'business-hours' );?></p>
</div>
<div>
<table id='business_hours_days_table'>
<thead>
<tr>
<td><?php _e( 'Day', 'business-hours' ) ?></td>
<td><?php _e( 'Open', 'business-hours' ) ?></td>
<td><?php _e( 'Close', 'business-hours' ) ?></td>
</tr>
</thead>
<tbody>
<?php $this->_show_days_controls(); ?>
</tbody>
</table>
</div>
</td>
</tr>
</table><file_sep><tr class='<?php echo $class;?>'>
<td class='business_hours_table_day'><?php echo ucwords( $day_name );?></td>
<?php if ( $is_open_today ) { ?>
<td class='business_hours_table_open'><?php echo ucwords( $open );?></td>
<td class='business_hours_table_close'><?php echo ucwords( $close );?></td>
<?php } else { ?>
<td class='business_hours_table_closed' colspan='2' align='center'><?php echo $closed_text; ?></td>
<?php } ?>
</tr><file_sep><div class="wrap">
<div id="icon-options-business-hours" class="icon32"><br></div>
<h2><?php _e( 'Business Hours', 'business-hours' ) ?></h2>
<br/>
<?php $this->_maybe_show_updated_notice(); ?>
<div class="bh_main_container">
<form id="bh-form" class="bh-form" action="" method="post">
<input type='hidden' name='page' value='<?php echo BusinessHours::SLUG; ?>'/>
<input type="hidden" name="action" value="update"/>
<?php wp_nonce_field( BusinessHours::SLUG, 'bh_nonce' ); ?>
<?php do_action( 'business-hours-settings-page' ) ?>
<table class="form-table">
<tr>
<td>
<p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary"
value="<?php _e( 'Save Changes' );?>"></p>
<div class="bh_clear"></div>
</td>
</tr>
</table>
</form>
</div>
<div class="bh_support_container">
<?php $this->_show_support_form(); ?>
</div>
<div class="bh_clear"></div>
</div>
<file_sep><div class="bh_support">
<h3><?php _e( 'Support / Contact', 'business-hours' ); ?></h3>
<ul>
<li><hr/></li>
<li><?php _e( 'Need support? Have an idea? Create a <a href="https://github.com/MZAWeb/business-hours-plugin/issues">new issue in GitHub</a> or in the <a href="http://wordpress.org/support/plugin/business-hours-plugin">support forums</a> at WordPress.org', 'business-hours' ); ?></li>
<li><hr/></li>
<li><?php _e( '<a href="https://github.com/MZAWeb/business-hours-plugin/wiki">Documentation</a>', 'business-hours' ); ?></li>
<li><?php _e( '<a href="http://twitter.com/MZAWeb">Tweet to me</a>', 'business-hours' ); ?></li>
<li><?php _e( '<a href="http://danieldvork.in/?utm_source=business_hours&utm_medium=settings&utm_campaign=plugin">My blog</a>', 'business-hours' ); ?></li>
<li><?php _e( '<a href="http://mzaweb.com/?utm_source=business_hours&utm_medium=settings&utm_campaign=plugin">MZAWeb - WordPress Development</a>', 'business-hours' ); ?></li>
<li><hr/></li>
<li><?php _e( 'I promise to keep this plugin free for ever. If it makes you happy and you want to make me happy, you can donate a few bucks to me via PayPal at <EMAIL>', 'business-hours' ); ?></li>
</ul>
</div><file_sep><?php
if ( class_exists( 'BusinessHoursSettings' ) )
return;
class BusinessHoursSettings {
const SETTINGS = 'business_hours_settings';
const PRE_20_SETTINGS = 'working-hours_settings';
const SETTING_HOURS = 'hours';
const SETTING_EXCEPTIONS = 'exceptions';
private static $saved = false;
private $cache = false;
private $page;
private $path;
private $url;
public function __construct() {
$this->path = trailingslashit( dirname( dirname( __FILE__ ) ) );
$this->url = trailingslashit( dirname( plugins_url( '', __FILE__ ) ) );
$this->_load_settings();
add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
add_action( 'init', array( $this, 'maybe_upgrade' ) );
add_action( 'business-hours-settings-page', array( $this, 'show_days_settings' ), 1 );
add_filter( 'business-hours-save-settings', array( $this, 'maybe_save_settings_hours' ), 1 );
}
/**
* @param $day
*
* @return mixed|void
*/
public function get_open_hour( $day ) {
$open = apply_filters( "business-hours-open-hour", $this->_get_business_hours( $day, "open" ), $day );
return $open;
}
/**
* @param $day
*
* @return mixed|void
*/
public function get_close_hour( $day ) {
$close = apply_filters( "business-hours-close-hour", $this->_get_business_hours( $day, "close" ), $day );
return $close;
}
/**
* @return bool
*/
public function get_full_settings() {
if ( empty( $this->cache ) )
$this->_load_settings();
return $this->cache;
}
/**
* @param $day
*
* @return mixed|void
*/
public function is_open( $day ) {
$open = $this->get_open_hour( $day );
$close = $this->get_close_hour( $day );
$is_open = !empty( $open ) && !empty( $close );
return apply_filters( 'business-hours-is-open-today', $is_open, $day );
}
/**
* @return mixed|void
*/
public function get_default_closed_text() {
return apply_filters( "business-hours-closed-text", __( "Closed", "business-hours" ) );
}
/**** ADMIN PAGE ****/
/**
*
*/
public function enqueue_resources() {
wp_enqueue_style( 'business_hours_admin_style', $this->url . 'resources/business-hours-admin.css' );
wp_enqueue_script( 'business_hours_admin_script', $this->url . 'resources/business-hours-admin.js', array( 'jquery' ) );
}
/**
*
*/
public function add_settings_page() {
$this->page = add_options_page( __( 'Business Hours', 'business-hours' ), __( 'Business Hours', 'business-hours' ), 'manage_options', BusinessHours::SLUG, array( $this,
'do_settings_page' ) );
add_action( 'admin_print_scripts-' . $this->page, array( $this, 'enqueue_resources' ) );
}
/**
*
*/
public function do_settings_page() {
$this->_maybe_save_settings();
business_hours()->log( $this->cache );
include business_hours()->locate_view( 'settings.php', false );
}
/**
*
*/
private function _maybe_save_settings() {
if ( empty( $_POST['action'] ) || $_POST['action'] != 'update' )
return;
if ( empty( $_POST['bh_nonce'] ) || !wp_verify_nonce( $_POST['bh_nonce'], BusinessHours::SLUG ) )
return;
$this->cache = array();
$this->cache = apply_filters( 'business-hours-save-settings', $this->cache );
$this->_save_settings();
self::$saved = true;
}
/**
* @param $cache
*
* @return mixed
*/
public function maybe_save_settings_hours( $cache ) {
$days = business_hours()->get_week_days();
foreach ( $days as $id => $day ) {
$open = $close = '';
if ( !empty( $_POST['open_' . $id] ) && !empty( $_POST['close_' . $id] ) ) {
$open = sanitize_text_field( ( $_POST['open_' . $id] ) );
$close = sanitize_text_field( ( $_POST['close_' . $id] ) );
}
$cache[self::SETTING_HOURS][$id]['open'] = $open;
$cache[self::SETTING_HOURS][$id]['close'] = $close;
}
return $cache;
}
/***** HELPERS *****/
/**
*
*/
private function _load_settings() {
$this->cache = get_option( BusinessHoursSettings::SETTINGS );
}
/**
*
*/
private function _save_settings() {
if ( !isset( $this->cache[self::SETTING_HOURS] ) )
$this->cache[self::SETTING_HOURS] = array();
if ( !isset( $this->cache[self::SETTING_EXCEPTIONS] ) )
$this->cache[self::SETTING_EXCEPTIONS] = array();
update_option( BusinessHoursSettings::SETTINGS, $this->cache );
}
/**
* @param null $day
* @param null $key
*
* @return bool|null
*/
private function _get_business_hours( $day = null, $key = null ) {
if ( empty( $this->cache ) )
$this->_load_settings();
if ( $day === null )
return $this->cache;
if ( empty( $this->cache[self::SETTING_HOURS][$day] ) )
return null;
if ( $key === null )
return $this->cache[$day];
return $this->cache[self::SETTING_HOURS][$day][$key];
}
/*********** HELPERS: ADMIN SCREEN ***************/
/**
*
*/
private function _maybe_show_updated_notice() {
if ( !self::$saved )
return;
echo '<div id="setting-error-settings_updated" class="updated settings-error">';
echo '<p><strong>' . __( 'Settings saved.' ) . '</strong></p></div>';
}
/**
*
*/
public function show_days_settings() {
include business_hours()->locate_view( 'settings-days.php' );
}
/**
*
*/
private function _show_days_controls() {
$days = business_hours()->get_week_days();
foreach ( $days as $id => $day ) {
$this->_show_day_controls( $id, esc_html( $day ) );
}
}
/**
* @param $id
* @param $name
*/
private function _show_day_controls( $id, $name ) {
$open = $this->get_open_hour( $id );
$close = $this->get_close_hour( $id );
include business_hours()->locate_view( 'settings-day-single.php', false );
}
/**
*
*/
private function _show_support_form() {
include business_hours()->locate_view( 'settings-support.php' );
}
/***************** Upgrades *****************/
public function maybe_upgrade() {
$upgraded = false;
if ( get_option( self::PRE_20_SETTINGS ) )
$upgraded = $this->upgrade_1x_20();
if ( $upgraded )
add_action( 'admin_notices', array( $this, 'upgrade_notice' ) );
}
public function upgrade_notice() {
$message = sprintf( __( 'Thanks for upgrading <strong>Business Hours</strong> to the %s version. Go to the <a href="%s">settings page</a> to check the new features. If you have any suggestion or issue, <a href="">create a support ticket</a>.', 'business-hours' ), BusinessHours::VERSION, get_admin_url( null, 'options-general.php?page=' . BusinessHours::SLUG ), 'https://github.com/MZAWeb/business-hours-plugin/issues' );
echo sprintf( '<div id="message" class="updated"><p>%s</p></div>', $message );
}
public function upgrade_1x_20() {
$old_settings = get_option( self::PRE_20_SETTINGS );
$cache = array();
foreach ( business_hours()->get_week_days() as $id => $name ) {
$name = strtolower( $name );
if ( isset( $old_settings[$name] ) ) {
$cache[self::SETTING_HOURS][$id]['open'] = isset( $old_settings[$name]['open'] ) ? $old_settings[$name]['open'] : "";
$cache[self::SETTING_HOURS][$id]['close'] = isset( $old_settings[$name]['close'] ) ? $old_settings[$name]['close'] : "";
}
}
$this->cache = $cache;
$this->_save_settings();
delete_option(self::PRE_20_SETTINGS);
return true;
}
}
<file_sep><?php
class BusinessHoursWidget extends WP_Widget {
function BusinessHoursWidget() {
$widget_ops = array( 'classname' => 'workinghourswidget',
'description' => __( 'Shows your business hours by day', "business-hours" ) );
$control_ops = array( 'width' => 200, 'height' => 350, 'id_base' => 'workinghourswidget' );
$this->WP_Widget( 'workinghourswidget', __( 'Business Hours by Day', "business-hours" ), $widget_ops, $control_ops );
if ( is_active_widget( false, false, $this->id_base ) ) {
add_action( 'wp_enqueue_scripts', array( &$this, 'scripts' ) );
add_action( 'admin_enqueue_scripts', array( &$this, 'scripts' ) );
}
}
function scripts() {
business_hours()->enqueue_resources();
}
function widget( $args, $instance ) {
extract( $args );
$title = esc_html( $instance['title'] );
$day = business_hours()->get_day_using_timezone();
$id = key( $day );
$name = $day[$id];
$open = esc_html( business_hours()->settings()->get_open_hour( $id ) );
$close = esc_html( business_hours()->settings()->get_close_hour( $id ) );
$is_open_today = business_hours()->settings()->is_open( $id );
$exceptions = BusinessHoursExceptions::instance()->get_exceptions_for_day_id( $id );
if ( !empty( $exceptions ) ) {
$open = $exceptions['open'];
$close = $exceptions['close'];
$is_open_today = !empty( $open ) && !empty( $close );
$name = BusinessHoursExceptions::instance()->get_localized_date_for_day_id( $id );
}
echo $before_widget;
echo $before_title . $title . $after_title;
if ( $is_open_today ) {
$template = $instance['template_hours'];
$template = str_replace( "{{Open}}", $open, $template );
$template = str_replace( "{{Close}}", $close, $template );
} else {
$template = $instance['template_closed'];
}
if ( $instance['template_today'] != "" ) {
$today = str_replace( "{{Day}}", $name, $instance['template_today'] );
$template = $today . $template;
}
echo $template;
// To catch instances saved in old versions of the plugin
$instance['collapsible'] = isset( $instance['collapsible'] ) ? $instance['collapsible'] : '1';
if ( $instance['allweek'] === "1" )
business_hours()->show_table( ( $instance['collapsible'] === '1' ) );
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['template_today'] = $new_instance['template_today'];
$instance['template_hours'] = $new_instance['template_hours'];
$instance['template_closed'] = $new_instance['template_closed'];
$instance['allweek'] = isset( $new_instance['allweek'] ) ? '1' : '';
$instance['collapsible'] = isset( $new_instance['collapsible'] ) ? '1' : '';
return $instance;
}
function form( $instance ) {
$closed_text = business_hours()->settings()->get_default_closed_text();
$defaults = array( 'title' => "Business Hours",
'template_today' => "<div class='working_hours_title'>" . __( "Business hours on", "business-hours" ) . " {{Day}}</div>",
'template_hours' => "<span class='working_hours_open'>{{Open}}</span> - <span class='working_hours_close'>{{Close}}</span>",
'template_closed' => "<div class='working_hours_closed'>" . $closed_text . "</div>",
'allweek' => 0,
'collapsible' => 1 );
$instance = wp_parse_args( (array)$instance, $defaults );
include business_hours()->locate_view( 'widget-admin.php', false );
}
}<file_sep><?php
/*
Plugin Name: Business Hours
Plugin URI: http://danieldvork.in/
Description: Business Hours lets you show to your visitors the time you open and close your business each day of the week.
Author: MZAWeb
Author URI: http://danieldvork.in/
Version: 2.0
For documentation see: https://github.com/MZAWeb/business-hours-plugin/wiki
For bug reports, ideas or comments: https://github.com/MZAWeb/business-hours-plugin/issues?state=open
*/
require 'lib/BusinessHours.class.php';
function business_hours_init() {
load_plugin_textdomain( 'business-hours', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
business_hours();
}
add_action( 'plugins_loaded', 'business_hours_init' );
<file_sep><table class="form-table">
<tr>
<td>
<div>
<h3><?php _e( 'Exceptions', 'business-hours' );?></h3>
<p>
<?php _e( "Exceptions allow you to set different business hours for specific days (ie: Holidays, Vacations, etc).", 'business-hours' );?>
<br/>
<?php $this->_show_exceptions_instructions(); ?>
</p>
</div>
<div id="exceptions_wrapper">
<?php $this->_show_exceptions(); ?>
</div>
<label for="exception_add">
<input type="button" name="exception_add" class="bh-button" id="exception_add"
value="<?php _e( 'Add exception', 'business-hours' );?>"/>
</label>
<div class="bh_clear"></div>
</td>
</tr>
</table><file_sep><tr>
<td><?php echo esc_html($name); ?></td>
<td><input name="open_<?php echo esc_attr( $id ); ?>" class="business_hours_hour_field open" type="text" value="<?php echo esc_attr($open) ;?>"/></td>
<td><input name="close_<?php echo esc_attr( $id ); ?>" class="business_hours_hour_field close" type="text" value="<?php echo esc_attr($close) ;?>"/></td>
</tr><file_sep><p>
<small><?php echo sprintf( __( 'Go to the <a href="%s">settings</a> to setup your business hours.', 'business-hours' ), admin_url( "options-general.php?page=working-hours-settings" ) ); ?></small>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( "Widget title", "business-hours" );?>
:</label><br/>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>"
name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $instance["title"] ); ?>"
type="text"/>
</p>
<p>
<input type="checkbox"
id="<?php echo $this->get_field_id( 'allweek' ); ?>"
value="1" <?php checked( $instance["allweek"] == "1" ); ?>
name="<?php echo $this->get_field_name( 'allweek' ); ?>"/>
<label
for="<?php echo $this->get_field_id( 'allweek' ); ?>"><?php _e( "Show a table with the business hours for all weekdays", "business-hours" );?> </label>
</p>
<p>
<input type="checkbox" id="<?php echo $this->get_field_id( 'collapsible' ); ?>"
value="1" <?php checked( $instance["collapsible"] == "1" ); ?>
name="<?php echo $this->get_field_name( 'collapsible' ); ?>"/>
<label
for="<?php echo $this->get_field_id( 'collapsible' ); ?>"><?php _e( "Make the list collapsible", "business-hours" );?> </label>
</p>
<p>
<a href='#'
class="business_hours_collapsible_handler"><?php _e( 'Toggle templating options', 'business-hours' );?></a>
</p>
<div class="business_hours_collapsible">
<p>
<label
for="<?php echo $this->get_field_id( 'template_today' ); ?>"><?php _e( "Template for heading", "business-hours" );?>
:</label><br/>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'template_today' ); ?>"
name="<?php echo $this->get_field_name( 'template_today' ); ?>" type="text"
rows="6"><?php echo esc_textarea( $instance["template_today"] ); ?></textarea>
<small>The tag {{Day}} will be replaced with the weekday name.</small>
</p>
<p>
<label
for="<?php echo $this->get_field_id( 'template_hours' ); ?>"><?php _e( "Template for working hours", "business-hours" );?>
:</label><br/>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'template_hours' ); ?>"
name="<?php echo $this->get_field_name( 'template_hours' ); ?>" type="text"
rows="6"><?php echo esc_textarea( $instance["template_hours"] ); ?></textarea>
<small><?php _e( "The tags {{Open}} and {{Close}} will be replaced with the correct values.", "business-hours" );?></small>
</p>
<p>
<label
for="<?php echo $this->get_field_id( 'template_closed' ); ?>"><?php _e( "Template for \"closed\" text", "business-hours" );?>
:</label><br/>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'template_closed' ); ?>"
name="<?php echo $this->get_field_name( 'template_closed' ); ?>" type="text"
rows="6"><?php echo esc_textarea( $instance["template_closed"] ); ?></textarea>
</p>
</div><file_sep><?php
class BusinessHours {
const VERSION = '2.0';
const SLUG = 'business-hours';
/**
* @var BusinessHours
*/
private static $instance;
/**
* @var BusinessHoursSettings
*/
private $settings;
private $path;
private $url;
public function __construct() {
$this->path = trailingslashit( dirname( dirname( __FILE__ ) ) );
$this->url = trailingslashit( dirname( plugins_url( '', __FILE__ ) ) );
$this->_register_settings();
$this->_register_shortcodes();
$this->_register_widgets();
// see https://github.com/MZAWeb/wp-log-in-browser
add_filter( 'wplinb-match-wp-debug', '__return_true' );
}
/**
* Load the required styles and javascript files
*/
public function enqueue_resources() {
wp_enqueue_style ( 'business_hours_style', $this->url . 'resources/business-hours.css' );
wp_enqueue_script( 'business_hours_script', $this->url . 'resources/business-hours.js', array( 'jquery' ) );
}
/**
*
* Today's hours shortcode handler.
* See https://github.com/MZAWeb/business-hours-plugin/wiki/Shortcodes
*
* @param $atts
* @param null $content
*
* @return mixed|null
*/
public function shortcode( $atts, $content = null ) {
$closed_text = business_hours()->settings()->get_default_closed_text();
extract( shortcode_atts( array( 'closed' => $closed_text ), $atts ) );
if ( empty( $content ) )
return $content;
$day = $this->get_day_using_timezone();
$id = key( $day );
$open = esc_html( business_hours()->settings()->get_open_hour( $id ) );
$close = esc_html( business_hours()->settings()->get_close_hour( $id ) );
$is_open_today = business_hours()->settings()->is_open( $id );
if ( $is_open_today ) {
$content = str_replace( "{{TodayOpen}}", $open, $content );
$content = str_replace( "{{TodayClose}}", $close, $content );
} else {
$content = $closed;
}
return $content;
}
/**
*
* Everyday hours shortcode handler.
* See https://github.com/MZAWeb/business-hours-plugin/wiki/Shortcodes
*
* @param $atts
*
* @return mixed|null
*/
public function shortcode_table( $atts ) {
extract( shortcode_atts( array( 'collapsible' => 'false', ), $atts ) );
$collapsible = ( strtolower( $collapsible ) === "true" ) ? true : false;
if ( $collapsible )
$this->enqueue_resources();
return $this->get_table( $collapsible );
}
/**
* Get the today's day name depending on the WP setting.
* To adjust your timezone go to Settings->General
*
* @return array
*/
public function get_day_using_timezone() {
$timestamp = $this->get_timestamp_using_timezone();
$arr = array( strtolower( gmdate( 'w', $timestamp ) ) => ucwords( date_i18n( 'l', $timestamp ) ) );
return $arr;
}
/**
* @return int
*/
public function get_timestamp_using_timezone() {
if ( get_option( 'timezone_string' ) ) {
$zone = new DateTimeZone( get_option( 'timezone_string' ) );
$datetime = new DateTime( 'now', $zone );
$timestamp = time() + $datetime->getOffset();
} else {
$offset = get_option( 'gmt_offset' );
$offset = $offset * 60 * 60;
$timestamp = time() + $offset;
}
return $timestamp;
}
/**
*
* Get the internationalized days names
*
* @return array
*/
public function get_week_days() {
global $wp_locale;
$days = $wp_locale->weekday;
$start_of_week = get_option( 'start_of_week' );
if ( !$start_of_week )
return $days;
$first = array_slice( $days, 0, $start_of_week, true );
$second = array_slice( $days, $start_of_week, count( $days ), true );
$days = $second + $first;
return $days;
}
/**
* Echo the table with the open/close hours for each day of the week
*
* @param bool $collapsible_link
*
* @filter business-hours-collapsible-link-anchor
*
*/
public function show_table( $collapsible_link = true ) {
$days = $this->get_week_days();
$collapsible_link_anchor = apply_filters( 'business-hours-collapsible-link-anchor', '[Show working hours]' );
include business_hours()->locate_view( 'table.php' );
}
/**
* Returns the table with the open/close hours for each day of the week
*
* @param bool $collapsible_link
*
* @return string
*/
public function get_table( $collapsible_link = true ) {
ob_start();
$this->show_table( $collapsible_link );
return ob_get_clean();
}
/**
*
* Echo the row for the given day for the hours table.
*
* @param $id
* @param $day_name
*
* @filter business-hours-closed-text
* @filter business-hours-open-hour
* @filter business-hours-close-hour
* @filter business-hours-is-open-today
*
*/
private function _table_row( $id, $day_name ) {
$ret = "";
$open = esc_html( business_hours()->settings()->get_open_hour( $id ) );
$close = esc_html( business_hours()->settings()->get_close_hour( $id ) );
$is_open_today = business_hours()->settings()->is_open( $id );
$closed_text = business_hours()->settings()->get_default_closed_text();
do_action( 'business-hours-before-row', $id, $day_name, $open, $close, $is_open_today );
$class = apply_filters( 'business-hours-row-class', '', $id, $day_name );
include business_hours()->locate_view( 'table-row.php' );
do_action( 'business-hours-after-row', $id, $day_name, $open, $close, $is_open_today );
}
/**
*
*/
private function _register_shortcodes() {
add_shortcode( 'businesshours', array( $this, 'shortcode' ) );
add_shortcode( 'businesshoursweek', array( $this, 'shortcode_table' ) );
}
/**
*
*/
private function _register_widgets() {
include 'BusinessHoursWidget.class.php';
add_action( 'widgets_init', array( $this, 'register_widgets' ) );
}
/**
*
*/
public function register_widgets() {
register_widget( 'BusinessHoursWidget' );
}
/**
* @return BusinessHoursSettings
*/
public function settings() {
return $this->settings;
}
/**
* Register the settings to create the settings screen
*
*/
private function _register_settings() {
if ( !class_exists( 'BusinessHoursSettings' ) )
include 'BusinessHoursSettings.class.php';
$this->settings = new BusinessHoursSettings();
if ( !class_exists( 'BusinessHoursExceptions' ) )
include 'BusinessHoursExceptions.class.php';
BusinessHoursExceptions::instance();
}
/**
* Allows users to overide views templates.
*
* It'll first check if the given $template is present in a business-hours folder in the user's theme.
* If the user didn't create an overide, it'll load the default file from this plugin's views template.
*
* @param $template
* @param $overridable
*
* @return string
*/
public function locate_view( $template, $overridable = true ) {
if ( $overridable && $theme_file = locate_template( array( 'business-hours/' . $template ) ) ) {
$file = $theme_file;
} else {
$file = $this->path . 'views/' . $template;
}
return apply_filters( 'business-hours-view-template', $file, $template );
}
/**
* @param $var
*/
public function log( $var ) {
// see https://github.com/MZAWeb/wp-log-in-browser
if ( function_exists( 'browser' ) && constant( "Browser::AUTHOR" ) && Browser::AUTHOR === 'MZAWeb' )
browser()->log( $var );
}
/**
* Returns the singleton instance for this class.
*
* @static
* @return BusinessHours
*/
public static function instance() {
if ( !isset( self::$instance ) ) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
}
if ( !function_exists( 'business_hours' ) ) {
/**
* Shorthand for BusinessHours::instance()
*
* @return BusinessHours
*/
function business_hours() {
return BusinessHours::instance();
}
}<file_sep><?php _e( "<b>Instructions:</b>", 'business-hours' );?>
<br/>
<?php _e( '1) Click on "Add Exception".', 'business-hours' ); ?>
<br/>
<?php _e( "2) Select a day, month and / or year (i.e. To add an exception for every March 1st select day 1, month March and leave the year empty).", 'business-hours' ); ?>
<br/>
<?php _e( "3) Type the open and close hours for this exception. Leave empty if your business remains closed during this exception.", 'business-hours' ); ?>
<br/>
<?php _e( "4) If you want to add more exceptions, click the 'Add Exceptions' button and repeat this process in the new added row.", 'business-hours' ); ?>
<br/>
<?php _e( "5) Need help setting exceptions? <a href='https://github.com/MZAWeb/business-hours-plugin/issues'>Open a ticket in GitHub</a>", 'business-hours' ); ?><file_sep>=== Business Hours Plugin ===
Contributors: MZAWeb
Donate link: http://danieldvork.in
Tags: working hours, working, business hours, business, hours, stores, branches
Requires at least: 3.1
Tested up to: 3.5
Stable tag: 2.0
Business Hours lets you show to your visitors the time you open and close your business each day of the week.
You can setup open and close hours for each day of the week, and then create exceptions for specific dates (holidays, etc)
== Description ==
The Business Hours Plugin allows you to post your daily working hours and show it to your visitors:
* In a configurable and templatable widget.
* In a page / post using shortcodes
You'll be able to choose between showing only today's working hours, or a collapsible table with the hours for each day of the week.
If you want to show only today's working hours, the plugin will check your timezone settings to calculate which day to show.
Also, Business Hours is 100% translatable to your language.
We've included language files for:
* Spanish
* Dutch
If you want to help me translate this plugin to your language, please drop me a line or contact me in the [support forum](http://wordpress.org/tags/business-hours-plugin#postform)
== Installation ==
1. Upload the plugin to the `/wp-content/plugins/` directory
2. Activate the plugin through the 'Plugins' menu in WordPress
3. Go to Settings->Working Hours to configure your schedule
4. Go to Appearance->Widgets and add the "Working Hours" widget in the sidebar you want.
== Frequently Asked Questions ==
1. What timezone is the plugin using to determine when the day changes?
This plugins uses the timezone configured in WordPress settings. ( Settings->General )
2. Shortcodes what??
The shortcode you need to use is this:
`[businesshours closed="TEXT FOR WHEN ITS CLOSED"]TEMPLATE[/businesshours]`
As TEMPLATE you should use **{{TodayOpen}}** for today's open hours and **{{TodayClose}}** for closing hours.
For example:
`[businesshours closed="Today is closed."]Today we work from {{TodayOpen}} to {{TodayClose}}[/businesshours]`
Also there's another shortcode that allows you to show the full week table:
`[businesshoursweek]`
You can also use
`[businesshoursweek collapsible="true"]`
to have the list collapsed by default and a link to open it.
== Screenshots ==
1. Business Hours Settings
2. Exceptions Settings
3. Widget Settings
4. Front-End Widget: Closed
5. Front-End Widget: Working
6. Front-End Widget: Full week, with an exception
== Upgrade Notice ==
= 2.0 =
Introducing Exceptions (Holidays, etc). Also, this version is (almost) a complete rewrite. Faster, more secure and with a lot of improvements.
== Changelog ==
= 2.0 =
* Feature: Allow for exceptions (for holidays, etc)
* Enhancement: Allow users to overide views templates
* Enhancement: Allow to show the hours table fixed in the widget (without collapsible)
* Enhancement: Cleanup widget admin. Hide templating fields. Clarify some texts.
* Enhancement: Cleanup settings admin. Sexier and more intuitive.
* Enhancement: The plugin will respect the "Week Starts On" value from Settings->General to show the days
* Enhancement: Works with WordPress 3.5
* Enhancement: General cleaning and improve architecture.
* Enhancement: Improve code quality ( a lot! )
* Enhancement: Improve loading speed
* Bugfix: Fixed how I'm handling timezones to account for DST
* Bugfix: Fixed minor bugs for WordPress 3.4.2
* Bugfix: Added missing getText calls in hardcoded strings
* New filter: *business-hours-closed-text*
* New filter: *business-hours-open-hour*
* New filter: *business-hours-close-hour*
* New filter: *business-hours-is-open-today*
* New filter: *business-hours-view-template*
* New filter: *business-hours-collapsible-link-anchor*
* New filter: *business-hours-exceptions-how-many-years*
* New filter: *business-hours-save-settings*
* New filter: *business-hours-row-class*
* New action: *business-hours-settings-page*
* New action: *business-hours-before-row*
* New action: *business-hours-after-row*
= 1.3.2 =
* Fixed how the plugin handles weekdays names localization
* Added dutch language files
= 1.3.1 =
* Added Spanish language files
* Fixed some localization related issues
= 1.3 =
* Added the shortcodes
* Added localization and english lang file
* Added text-align=center; to: .business_hours_table_closed, .business_hours_table_heading, .business_hours_table_open and .business_hours_table_close
* Fix: Spelling collapsable for collapsible.
= 1.2 =
* Added an optional collapsable table in the widget showing the working hours for all weekdays.
* Fixed the mess of different names (working hours, open hours, etc) in favour of Business Hours.
* Added support email
* WordPress 3.3 compatible.
= 1.1 =
* Some minor bug fixes
= 1.0.2 =
* Fixed screenshots
= 1.0.1 =
* Fixed plugin info in php header
= 1.0 =
* First release | f40a4d6f6003b6e010d8c0834f9ed2624b306917 | [
"JavaScript",
"Text",
"PHP"
] | 18 | PHP | WPPlugins/business-hours-plugin | ca66193cbc1b3020b78006c13dca3268fc0720a6 | 2d999407b1bb097e0a98c7383c41f0c086ad3b20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.