index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant/usb/IButtonCallback.java
|
package com.serenegiant.usb;
public interface IButtonCallback {
void onButton(int button, int state);
}
|
0
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant/usb/IFrameCallback.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usb;
import java.nio.ByteBuffer;
/**
* Callback interface for UVCCamera class
* If you need frame data as ByteBuffer, you can use this callback interface with UVCCamera#setFrameCallback
*/
public interface IFrameCallback {
/**
* This method is called from native library via JNI on the same thread as UVCCamera#startCapture.
* You can use both UVCCamera#startCapture and #setFrameCallback
* but it is better to use either for better performance.
* You can also pass pixel format type to UVCCamera#setFrameCallback for this method.
* Some frames may drops if this method takes a time.
* When you use some color format like NV21, this library never execute color space conversion,
* just execute pixel format conversion. If you want to get same result as on screen, please try to
* consider to get images via texture(SurfaceTexture) and read pixel buffer from it using OpenGL|ES2/3
* instead of using IFrameCallback(this way is much efficient in most case than using IFrameCallback).
* @param frame this is direct ByteBuffer from JNI layer and you should handle it's byte order and limitation.
*/
public void onFrame(ByteBuffer frame);
}
|
0
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant/usb/IStatusCallback.java
|
package com.serenegiant.usb;
import java.nio.ByteBuffer;
public interface IStatusCallback {
void onStatus(int statusClass, int event, int selector, int statusAttribute, ByteBuffer data);
}
|
0
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant/usb/Size.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usb;
import java.util.Locale;
import android.os.Parcel;
import android.os.Parcelable;
public class Size implements Parcelable {
//
/**
* native側のuvc_raw_format_tの値, こっちは主にlibuvc用
* 9999 is still image
*/
public int type;
/**
* native側のraw_frame_tの値, androusb用,
* libuvcは対応していない
*/
public int frame_type;
public int index;
public int width;
public int height;
public int frameIntervalType;
public int frameIntervalIndex;
public int[] intervals;
// ここ以下はframeIntervalTypeとintervalsから#updateFrameRateで計算する
public float[] fps;
private String frameRates;
/**
* コンストラクタ
* @param _type native側のraw_format_tの値, ただし9999は静止画
* @param _frame_type native側のraw_frame_tの値
* @param _index
* @param _width
* @param _height
*/
public Size(final int _type, final int _frame_type, final int _index, final int _width, final int _height) {
type = _type;
frame_type = _frame_type;
index = _index;
width = _width;
height = _height;
frameIntervalType = -1;
frameIntervalIndex = 0;
intervals = null;
updateFrameRate();
}
/**
* コンストラクタ
* @param _type native側のraw_format_tの値, ただし9999は静止画
* @param _frame_type native側のraw_frame_tの値
* @param _index
* @param _width
* @param _height
* @param _min_intervals
* @param _max_intervals
*/
public Size(final int _type, final int _frame_type, final int _index, final int _width, final int _height, final int _min_intervals, final int _max_intervals, final int _step) {
type = _type;
frame_type = _frame_type;
index = _index;
width = _width;
height = _height;
frameIntervalType = 0;
frameIntervalIndex = 0;
intervals = new int[3];
intervals[0] = _min_intervals;
intervals[1] = _max_intervals;
intervals[2] = _step;
updateFrameRate();
}
/**
* コンストラクタ
* @param _type native側のraw_format_tの値, ただし9999は静止画
* @param _frame_type native側のraw_frame_tの値
* @param _index
* @param _width
* @param _height
* @param _intervals
*/
public Size(final int _type, final int _frame_type, final int _index, final int _width, final int _height, final int[] _intervals) {
type = _type;
frame_type = _frame_type;
index = _index;
width = _width;
height = _height;
final int n = _intervals != null ? _intervals.length : -1;
if (n > 0) {
frameIntervalType = n;
intervals = new int[n];
System.arraycopy(_intervals, 0, intervals, 0, n);
} else {
frameIntervalType = -1;
intervals = null;
}
frameIntervalIndex = 0;
updateFrameRate();
}
/**
* コピーコンストラクタ
* @param other
*/
public Size(final Size other) {
type = other.type;
frame_type = other.frame_type;
index = other.index;
width = other.width;
height = other.height;
frameIntervalType = other.frameIntervalType;
frameIntervalIndex = other.frameIntervalIndex;
final int n = other.intervals != null ? other.intervals.length : -1;
if (n > 0) {
intervals = new int[n];
System.arraycopy(other.intervals, 0, intervals, 0, n);
} else {
intervals = null;
}
updateFrameRate();
}
private Size(final Parcel source) {
// 読み取り順はwriteToParcelでの書き込み順と同じでないとダメ
type = source.readInt();
frame_type = source.readInt();
index = source.readInt();
width = source.readInt();
height = source.readInt();
frameIntervalType = source.readInt();
frameIntervalIndex = source.readInt();
if (frameIntervalType >= 0) {
if (frameIntervalType > 0) {
intervals = new int[frameIntervalType];
} else {
intervals = new int[3];
}
source.readIntArray(intervals);
} else {
intervals = null;
}
updateFrameRate();
}
public Size set(final Size other) {
if (other != null) {
type = other.type;
frame_type = other.frame_type;
index = other.index;
width = other.width;
height = other.height;
frameIntervalType = other.frameIntervalType;
frameIntervalIndex = other.frameIntervalIndex;
final int n = other.intervals != null ? other.intervals.length : -1;
if (n > 0) {
intervals = new int[n];
System.arraycopy(other.intervals, 0, intervals, 0, n);
} else {
intervals = null;
}
updateFrameRate();
}
return this;
}
public float getCurrentFrameRate() throws IllegalStateException {
final int n = fps != null ? fps.length : 0;
if ((frameIntervalIndex >= 0) && (frameIntervalIndex < n)) {
return fps[frameIntervalIndex];
}
throw new IllegalStateException("unknown frame rate or not ready");
}
public void setCurrentFrameRate(final float frameRate) {
// 一番近いのを選ぶ
int index = -1;
final int n = fps != null ? fps.length : 0;
for (int i = 0; i < n; i++) {
if (fps[i] <= frameRate) {
index = i;
break;
}
}
frameIntervalIndex = index;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeInt(type);
dest.writeInt(frame_type);
dest.writeInt(index);
dest.writeInt(width);
dest.writeInt(height);
dest.writeInt(frameIntervalType);
dest.writeInt(frameIntervalIndex);
if (intervals != null) {
dest.writeIntArray(intervals);
}
}
public void updateFrameRate() {
final int n = frameIntervalType;
if (n > 0) {
fps = new float[n];
for (int i = 0; i < n; i++) {
final float _fps = fps[i] = 10000000.0f / intervals[i];
}
} else if (n == 0) {
try {
final int min = Math.min(intervals[0], intervals[1]);
final int max = Math.max(intervals[0], intervals[1]);
final int step = intervals[2];
if (step > 0) {
int m = 0;
for (int i = min; i <= max; i+= step) { m++; }
fps = new float[m];
m = 0;
for (int i = min; i <= max; i+= step) {
final float _fps = fps[m++] = 10000000.0f / i;
}
} else {
final float max_fps = 10000000.0f / min;
int m = 0;
for (float fps = 10000000.0f / min; fps <= max_fps; fps += 1.0f) { m++; }
fps = new float[m];
m = 0;
for (float fps = 10000000.0f / min; fps <= max_fps; fps += 1.0f) {
this.fps[m++] = fps;
}
}
} catch (final Exception e) {
// ignore, なんでかminとmaxが0になってるんちゃうかな
fps = null;
}
}
final int m = fps != null ? fps.length : 0;
final StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < m; i++) {
sb.append(String.format(Locale.US, "%4.1f", fps[i]));
if (i < m-1) {
sb.append(",");
}
}
sb.append("]");
frameRates = sb.toString();
if (frameIntervalIndex > m) {
frameIntervalIndex = 0;
}
}
@Override
public String toString() {
float frame_rate = 0.0f;
try {
frame_rate = getCurrentFrameRate();
} catch (final Exception e) {
}
return String.format(Locale.US, "Size(%dx%d@%4.1f,type:%d,frame:%d,index:%d,%s)", width, height, frame_rate, type, frame_type, index, frameRates);
}
public static final Creator<Size> CREATOR = new Parcelable.Creator<Size>() {
@Override
public Size createFromParcel(final Parcel source) {
return new Size(source);
}
@Override
public Size[] newArray(final int size) {
return new Size[size];
}
};
}
|
0
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant/usb/USBMonitor.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usb;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import com.serenegiant.utils.BuildCheck;
import com.serenegiant.utils.HandlerThreadHandler;
public final class USBMonitor {
private static final boolean DEBUG = false; // TODO set false on production
private static final String TAG = "USBMonitor";
private static final String ACTION_USB_PERMISSION_BASE = "com.serenegiant.USB_PERMISSION.";
private final String ACTION_USB_PERMISSION = ACTION_USB_PERMISSION_BASE + hashCode();
public static final String ACTION_USB_DEVICE_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
/**
* openしているUsbControlBlock
*/
private final ConcurrentHashMap<UsbDevice, UsbControlBlock> mCtrlBlocks = new ConcurrentHashMap<UsbDevice, UsbControlBlock>();
private final SparseArray<WeakReference<UsbDevice>> mHasPermissions = new SparseArray<WeakReference<UsbDevice>>();
private final WeakReference<Context> mWeakContext;
private final UsbManager mUsbManager;
private final OnDeviceConnectListener mOnDeviceConnectListener;
private PendingIntent mPermissionIntent = null;
private List<DeviceFilter> mDeviceFilters = new ArrayList<DeviceFilter>();
/**
* コールバックをワーカースレッドで呼び出すためのハンドラー
*/
private final Handler mAsyncHandler;
private volatile boolean destroyed;
/**
* USB機器の状態変更時のコールバックリスナー
*/
public interface OnDeviceConnectListener {
/**
* called when device attached
* @param device
*/
public void onAttach(UsbDevice device);
/**
* called when device dettach(after onDisconnect)
* @param device
*/
public void onDettach(UsbDevice device);
/**
* called after device opend
* @param device
* @param ctrlBlock
* @param createNew
*/
public void onConnect(UsbDevice device, UsbControlBlock ctrlBlock, boolean createNew);
/**
* called when USB device removed or its power off (this callback is called after device closing)
* @param device
* @param ctrlBlock
*/
public void onDisconnect(UsbDevice device, UsbControlBlock ctrlBlock);
/**
* called when canceled or could not get permission from user
* @param device
*/
public void onCancel(UsbDevice device);
}
public USBMonitor(final Context context, final OnDeviceConnectListener listener) {
if (DEBUG) Log.v(TAG, "USBMonitor:Constructor");
if (listener == null)
throw new IllegalArgumentException("OnDeviceConnectListener should not null.");
mWeakContext = new WeakReference<Context>(context);
mUsbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
mOnDeviceConnectListener = listener;
mAsyncHandler = HandlerThreadHandler.createHandler(TAG);
destroyed = false;
if (DEBUG) Log.v(TAG, "USBMonitor:mUsbManager=" + mUsbManager);
}
/**
* Release all related resources,
* never reuse again
*/
public void destroy() {
if (DEBUG) Log.i(TAG, "destroy:");
unregister();
if (!destroyed) {
destroyed = true;
// モニターしているUSB機器を全てcloseする
final Set<UsbDevice> keys = mCtrlBlocks.keySet();
if (keys != null) {
UsbControlBlock ctrlBlock;
try {
for (final UsbDevice key: keys) {
ctrlBlock = mCtrlBlocks.remove(key);
if (ctrlBlock != null) {
ctrlBlock.close();
}
}
} catch (final Exception e) {
Log.e(TAG, "destroy:", e);
}
}
mCtrlBlocks.clear();
try {
mAsyncHandler.getLooper().quit();
} catch (final Exception e) {
Log.e(TAG, "destroy:", e);
}
}
}
/**
* register BroadcastReceiver to monitor USB events
* @throws IllegalStateException
*/
public synchronized void register() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
if (mPermissionIntent == null) {
if (DEBUG) Log.i(TAG, "register:");
final Context context = mWeakContext.get();
if (context != null) {
mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
final IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
// ACTION_USB_DEVICE_ATTACHED never comes on some devices so it should not be added here
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
context.registerReceiver(mUsbReceiver, filter);
}
// start connection check
mDeviceCounts = 0;
mAsyncHandler.postDelayed(mDeviceCheckRunnable, 1000);
}
}
/**
* unregister BroadcastReceiver
* @throws IllegalStateException
*/
public synchronized void unregister() throws IllegalStateException {
// 接続チェック用Runnableを削除
mDeviceCounts = 0;
if (!destroyed) {
mAsyncHandler.removeCallbacks(mDeviceCheckRunnable);
}
if (mPermissionIntent != null) {
// if (DEBUG) Log.i(TAG, "unregister:");
final Context context = mWeakContext.get();
try {
if (context != null) {
context.unregisterReceiver(mUsbReceiver);
}
} catch (final Exception e) {
Log.w(TAG, e);
}
mPermissionIntent = null;
}
}
public synchronized boolean isRegistered() {
return !destroyed && (mPermissionIntent != null);
}
/**
* set device filter
* @param filter
* @throws IllegalStateException
*/
public void setDeviceFilter(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.clear();
mDeviceFilters.add(filter);
}
/**
* デバイスフィルターを追加
* @param filter
* @throws IllegalStateException
*/
public void addDeviceFilter(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.add(filter);
}
/**
* デバイスフィルターを削除
* @param filter
* @throws IllegalStateException
*/
public void removeDeviceFilter(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.remove(filter);
}
/**
* set device filters
* @param filters
* @throws IllegalStateException
*/
public void setDeviceFilter(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.clear();
mDeviceFilters.addAll(filters);
}
/**
* add device filters
* @param filters
* @throws IllegalStateException
*/
public void addDeviceFilter(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.addAll(filters);
}
/**
* remove device filters
* @param filters
*/
public void removeDeviceFilter(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.removeAll(filters);
}
/**
* return the number of connected USB devices that matched device filter
* @return
* @throws IllegalStateException
*/
public int getDeviceCount() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
return getDeviceList().size();
}
/**
* return device list, return empty list if no device matched
* @return
* @throws IllegalStateException
*/
public List<UsbDevice> getDeviceList() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
return getDeviceList(mDeviceFilters);
}
/**
* return device list, return empty list if no device matched
* @param filters
* @return
* @throws IllegalStateException
*/
public List<UsbDevice> getDeviceList(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
final List<UsbDevice> result = new ArrayList<UsbDevice>();
if (deviceList != null) {
if ((filters == null) || filters.isEmpty()) {
result.addAll(deviceList.values());
} else {
for (final UsbDevice device: deviceList.values() ) {
for (final DeviceFilter filter: filters) {
if ((filter != null) && filter.matches(device)) {
// when filter matches
if (!filter.isExclude) {
result.add(device);
}
break;
}
}
}
}
}
return result;
}
/**
* return device list, return empty list if no device matched
* @param filter
* @return
* @throws IllegalStateException
*/
public List<UsbDevice> getDeviceList(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
final List<UsbDevice> result = new ArrayList<UsbDevice>();
if (deviceList != null) {
for (final UsbDevice device: deviceList.values() ) {
if ((filter == null) || (filter.matches(device) && !filter.isExclude)) {
result.add(device);
}
}
}
return result;
}
/**
* get USB device list, without filter
* @return
* @throws IllegalStateException
*/
public Iterator<UsbDevice> getDevices() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
Iterator<UsbDevice> iterator = null;
final HashMap<String, UsbDevice> list = mUsbManager.getDeviceList();
if (list != null)
iterator = list.values().iterator();
return iterator;
}
/**
* output device list to LogCat
*/
public final void dumpDevices() {
final HashMap<String, UsbDevice> list = mUsbManager.getDeviceList();
if (list != null) {
final Set<String> keys = list.keySet();
if (keys != null && keys.size() > 0) {
final StringBuilder sb = new StringBuilder();
for (final String key: keys) {
final UsbDevice device = list.get(key);
final int num_interface = device != null ? device.getInterfaceCount() : 0;
sb.setLength(0);
for (int i = 0; i < num_interface; i++) {
sb.append(String.format(Locale.US, "interface%d:%s", i, device.getInterface(i).toString()));
}
Log.i(TAG, "key=" + key + ":" + device + ":" + sb.toString());
}
} else {
Log.i(TAG, "no device");
}
} else {
Log.i(TAG, "no device");
}
}
/**
* return whether the specific Usb device has permission
* @param device
* @return true: 指定したUsbDeviceにパーミッションがある
* @throws IllegalStateException
*/
public final boolean hasPermission(final UsbDevice device) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
return updatePermission(device, device != null && mUsbManager.hasPermission(device));
}
/**
* 内部で保持しているパーミッション状態を更新
* @param device
* @param hasPermission
* @return hasPermission
*/
private boolean updatePermission(final UsbDevice device, final boolean hasPermission) {
final int deviceKey = getDeviceKey(device, true);
synchronized (mHasPermissions) {
if (hasPermission) {
if (mHasPermissions.get(deviceKey) == null) {
mHasPermissions.put(deviceKey, new WeakReference<UsbDevice>(device));
}
} else {
mHasPermissions.remove(deviceKey);
}
}
return hasPermission;
}
/**
* request permission to access to USB device
* @param device
* @return true if fail to request permission
*/
public synchronized boolean requestPermission(final UsbDevice device) {
// if (DEBUG) Log.v(TAG, "requestPermission:device=" + device);
boolean result = false;
if (isRegistered()) {
if (device != null) {
if (mUsbManager.hasPermission(device)) {
// call onConnect if app already has permission
processConnect(device);
} else {
try {
// パーミッションがなければ要求する
mUsbManager.requestPermission(device, mPermissionIntent);
} catch (final Exception e) {
// Android5.1.xのGALAXY系でandroid.permission.sec.MDM_APP_MGMTという意味不明の例外生成するみたい
Log.w(TAG, e);
processCancel(device);
result = true;
}
}
} else {
processCancel(device);
result = true;
}
} else {
processCancel(device);
result = true;
}
return result;
}
/**
* 指定したUsbDeviceをopenする
* @param device
* @return
* @throws SecurityException パーミッションがなければSecurityExceptionを投げる
*/
public UsbControlBlock openDevice(final UsbDevice device) throws SecurityException {
if (hasPermission(device)) {
UsbControlBlock result = mCtrlBlocks.get(device);
if (result == null) {
result = new UsbControlBlock(USBMonitor.this, device); // この中でopenDeviceする
mCtrlBlocks.put(device, result);
}
return result;
} else {
throw new SecurityException("has no permission");
}
}
/**
* BroadcastReceiver for USB permission
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
if (destroyed) return;
final String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
// when received the result of requesting USB permission
synchronized (USBMonitor.this) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// get permission, call onConnect
processConnect(device);
}
} else {
// failed to get permission
processCancel(device);
}
}
} else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
updatePermission(device, hasPermission(device));
processAttach(device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
// when device removed
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
UsbControlBlock ctrlBlock = mCtrlBlocks.remove(device);
if (ctrlBlock != null) {
// cleanup
ctrlBlock.close();
}
mDeviceCounts = 0;
processDettach(device);
}
}
}
};
/** number of connected & detected devices */
private volatile int mDeviceCounts = 0;
/**
* periodically check connected devices and if it changed, call onAttach
*/
private final Runnable mDeviceCheckRunnable = new Runnable() {
@Override
public void run() {
if (destroyed) return;
final List<UsbDevice> devices = getDeviceList();
final int n = devices.size();
final int hasPermissionCounts;
final int m;
synchronized (mHasPermissions) {
hasPermissionCounts = mHasPermissions.size();
mHasPermissions.clear();
for (final UsbDevice device: devices) {
hasPermission(device);
}
m = mHasPermissions.size();
}
if ((n > mDeviceCounts) || (m > hasPermissionCounts)) {
mDeviceCounts = n;
if (mOnDeviceConnectListener != null) {
for (int i = 0; i < n; i++) {
final UsbDevice device = devices.get(i);
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onAttach(device);
}
});
}
}
}
mAsyncHandler.postDelayed(this, 2000); // confirm every 2 seconds
}
};
/**
* open specific USB device
* @param device
*/
private final void processConnect(final UsbDevice device) {
if (destroyed) return;
updatePermission(device, true);
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
if (DEBUG) Log.v(TAG, "processConnect:device=" + device);
UsbControlBlock ctrlBlock;
final boolean createNew;
ctrlBlock = mCtrlBlocks.get(device);
if (ctrlBlock == null) {
ctrlBlock = new UsbControlBlock(USBMonitor.this, device);
mCtrlBlocks.put(device, ctrlBlock);
createNew = true;
} else {
createNew = false;
}
if (mOnDeviceConnectListener != null) {
mOnDeviceConnectListener.onConnect(device, ctrlBlock, createNew);
}
}
});
}
private final void processCancel(final UsbDevice device) {
if (destroyed) return;
if (DEBUG) Log.v(TAG, "processCancel:");
updatePermission(device, false);
if (mOnDeviceConnectListener != null) {
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onCancel(device);
}
});
}
}
private final void processAttach(final UsbDevice device) {
if (destroyed) return;
if (DEBUG) Log.v(TAG, "processAttach:");
if (mOnDeviceConnectListener != null) {
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onAttach(device);
}
});
}
}
private final void processDettach(final UsbDevice device) {
if (destroyed) return;
if (DEBUG) Log.v(TAG, "processDettach:");
if (mOnDeviceConnectListener != null) {
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onDettach(device);
}
});
}
}
/**
* USB機器毎の設定保存用にデバイスキー名を生成する。
* ベンダーID, プロダクトID, デバイスクラス, デバイスサブクラス, デバイスプロトコルから生成
* 同種の製品だと同じキー名になるので注意
* @param device nullなら空文字列を返す
* @return
*/
public static final String getDeviceKeyName(final UsbDevice device) {
return getDeviceKeyName(device, null, false);
}
/**
* USB機器毎の設定保存用にデバイスキー名を生成する。
* useNewAPI=falseで同種の製品だと同じデバイスキーになるので注意
* @param device
* @param useNewAPI
* @return
*/
public static final String getDeviceKeyName(final UsbDevice device, final boolean useNewAPI) {
return getDeviceKeyName(device, null, useNewAPI);
}
/**
* USB機器毎の設定保存用にデバイスキー名を生成する。この機器名をHashMapのキーにする
* UsbDeviceがopenしている時のみ有効
* ベンダーID, プロダクトID, デバイスクラス, デバイスサブクラス, デバイスプロトコルから生成
* serialがnullや空文字でなければserialを含めたデバイスキー名を生成する
* useNewAPI=trueでAPIレベルを満たしていればマニュファクチャ名, バージョン, コンフィギュレーションカウントも使う
* @param device nullなら空文字列を返す
* @param serial UsbDeviceConnection#getSerialで取得したシリアル番号を渡す, nullでuseNewAPI=trueでAPI>=21なら内部で取得
* @param useNewAPI API>=21またはAPI>=23のみで使用可能なメソッドも使用する(ただし機器によってはnullが返ってくるので有効かどうかは機器による)
* @return
*/
@SuppressLint("NewApi")
public static final String getDeviceKeyName(final UsbDevice device, final String serial, final boolean useNewAPI) {
if (device == null) return "";
final StringBuilder sb = new StringBuilder();
sb.append(device.getVendorId()); sb.append("#"); // API >= 12
sb.append(device.getProductId()); sb.append("#"); // API >= 12
sb.append(device.getDeviceClass()); sb.append("#"); // API >= 12
sb.append(device.getDeviceSubclass()); sb.append("#"); // API >= 12
sb.append(device.getDeviceProtocol()); // API >= 12
if (!TextUtils.isEmpty(serial)) {
sb.append("#"); sb.append(serial);
}
if (useNewAPI && BuildCheck.isAndroid5()) {
sb.append("#");
if (TextUtils.isEmpty(serial)) {
sb.append(device.getSerialNumber()); sb.append("#"); // API >= 21
}
sb.append(device.getManufacturerName()); sb.append("#"); // API >= 21
sb.append(device.getConfigurationCount()); sb.append("#"); // API >= 21
if (BuildCheck.isMarshmallow()) {
sb.append(device.getVersion()); sb.append("#"); // API >= 23
}
}
// if (DEBUG) Log.v(TAG, "getDeviceKeyName:" + sb.toString());
return sb.toString();
}
/**
* デバイスキーを整数として取得
* getDeviceKeyNameで得られる文字列のhasCodeを取得
* ベンダーID, プロダクトID, デバイスクラス, デバイスサブクラス, デバイスプロトコルから生成
* 同種の製品だと同じデバイスキーになるので注意
* @param device nullなら0を返す
* @return
*/
public static final int getDeviceKey(final UsbDevice device) {
return device != null ? getDeviceKeyName(device, null, false).hashCode() : 0;
}
/**
* デバイスキーを整数として取得
* getDeviceKeyNameで得られる文字列のhasCodeを取得
* useNewAPI=falseで同種の製品だと同じデバイスキーになるので注意
* @param device
* @param useNewAPI
* @return
*/
public static final int getDeviceKey(final UsbDevice device, final boolean useNewAPI) {
return device != null ? getDeviceKeyName(device, null, useNewAPI).hashCode() : 0;
}
/**
* デバイスキーを整数として取得
* getDeviceKeyNameで得られる文字列のhasCodeを取得
* serialがnullでuseNewAPI=falseで同種の製品だと同じデバイスキーになるので注意
* @param device nullなら0を返す
* @param serial UsbDeviceConnection#getSerialで取得したシリアル番号を渡す, nullでuseNewAPI=trueでAPI>=21なら内部で取得
* @param useNewAPI API>=21またはAPI>=23のみで使用可能なメソッドも使用する(ただし機器によってはnullが返ってくるので有効かどうかは機器による)
* @return
*/
public static final int getDeviceKey(final UsbDevice device, final String serial, final boolean useNewAPI) {
return device != null ? getDeviceKeyName(device, serial, useNewAPI).hashCode() : 0;
}
public static class UsbDeviceInfo {
public String usb_version;
public String manufacturer;
public String product;
public String version;
public String serial;
private void clear() {
usb_version = manufacturer = product = version = serial = null;
}
@Override
public String toString() {
return String.format("UsbDevice:usb_version=%s,manufacturer=%s,product=%s,version=%s,serial=%s",
usb_version != null ? usb_version : "",
manufacturer != null ? manufacturer : "",
product != null ? product : "",
version != null ? version : "",
serial != null ? serial : "");
}
}
private static final int USB_DIR_OUT = 0;
private static final int USB_DIR_IN = 0x80;
private static final int USB_TYPE_MASK = (0x03 << 5);
private static final int USB_TYPE_STANDARD = (0x00 << 5);
private static final int USB_TYPE_CLASS = (0x01 << 5);
private static final int USB_TYPE_VENDOR = (0x02 << 5);
private static final int USB_TYPE_RESERVED = (0x03 << 5);
private static final int USB_RECIP_MASK = 0x1f;
private static final int USB_RECIP_DEVICE = 0x00;
private static final int USB_RECIP_INTERFACE = 0x01;
private static final int USB_RECIP_ENDPOINT = 0x02;
private static final int USB_RECIP_OTHER = 0x03;
private static final int USB_RECIP_PORT = 0x04;
private static final int USB_RECIP_RPIPE = 0x05;
private static final int USB_REQ_GET_STATUS = 0x00;
private static final int USB_REQ_CLEAR_FEATURE = 0x01;
private static final int USB_REQ_SET_FEATURE = 0x03;
private static final int USB_REQ_SET_ADDRESS = 0x05;
private static final int USB_REQ_GET_DESCRIPTOR = 0x06;
private static final int USB_REQ_SET_DESCRIPTOR = 0x07;
private static final int USB_REQ_GET_CONFIGURATION = 0x08;
private static final int USB_REQ_SET_CONFIGURATION = 0x09;
private static final int USB_REQ_GET_INTERFACE = 0x0A;
private static final int USB_REQ_SET_INTERFACE = 0x0B;
private static final int USB_REQ_SYNCH_FRAME = 0x0C;
private static final int USB_REQ_SET_SEL = 0x30;
private static final int USB_REQ_SET_ISOCH_DELAY = 0x31;
private static final int USB_REQ_SET_ENCRYPTION = 0x0D;
private static final int USB_REQ_GET_ENCRYPTION = 0x0E;
private static final int USB_REQ_RPIPE_ABORT = 0x0E;
private static final int USB_REQ_SET_HANDSHAKE = 0x0F;
private static final int USB_REQ_RPIPE_RESET = 0x0F;
private static final int USB_REQ_GET_HANDSHAKE = 0x10;
private static final int USB_REQ_SET_CONNECTION = 0x11;
private static final int USB_REQ_SET_SECURITY_DATA = 0x12;
private static final int USB_REQ_GET_SECURITY_DATA = 0x13;
private static final int USB_REQ_SET_WUSB_DATA = 0x14;
private static final int USB_REQ_LOOPBACK_DATA_WRITE = 0x15;
private static final int USB_REQ_LOOPBACK_DATA_READ = 0x16;
private static final int USB_REQ_SET_INTERFACE_DS = 0x17;
private static final int USB_REQ_STANDARD_DEVICE_SET = (USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE); // 0x10
private static final int USB_REQ_STANDARD_DEVICE_GET = (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE); // 0x90
private static final int USB_REQ_STANDARD_INTERFACE_SET = (USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_INTERFACE); // 0x11
private static final int USB_REQ_STANDARD_INTERFACE_GET = (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_INTERFACE); // 0x91
private static final int USB_REQ_STANDARD_ENDPOINT_SET = (USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_ENDPOINT); // 0x12
private static final int USB_REQ_STANDARD_ENDPOINT_GET = (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_ENDPOINT); // 0x92
private static final int USB_REQ_CS_DEVICE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0x20
private static final int USB_REQ_CS_DEVICE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0xa0
private static final int USB_REQ_CS_INTERFACE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0x21
private static final int USB_REQ_CS_INTERFACE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0xa1
private static final int USB_REQ_CS_ENDPOINT_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0x22
private static final int USB_REQ_CS_ENDPOINT_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0xa2
private static final int USB_REQ_VENDER_DEVICE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0x40
private static final int USB_REQ_VENDER_DEVICE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0xc0
private static final int USB_REQ_VENDER_INTERFACE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0x41
private static final int USB_REQ_VENDER_INTERFACE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0xc1
private static final int USB_REQ_VENDER_ENDPOINT_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0x42
private static final int USB_REQ_VENDER_ENDPOINT_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0xc2
private static final int USB_DT_DEVICE = 0x01;
private static final int USB_DT_CONFIG = 0x02;
private static final int USB_DT_STRING = 0x03;
private static final int USB_DT_INTERFACE = 0x04;
private static final int USB_DT_ENDPOINT = 0x05;
private static final int USB_DT_DEVICE_QUALIFIER = 0x06;
private static final int USB_DT_OTHER_SPEED_CONFIG = 0x07;
private static final int USB_DT_INTERFACE_POWER = 0x08;
private static final int USB_DT_OTG = 0x09;
private static final int USB_DT_DEBUG = 0x0a;
private static final int USB_DT_INTERFACE_ASSOCIATION = 0x0b;
private static final int USB_DT_SECURITY = 0x0c;
private static final int USB_DT_KEY = 0x0d;
private static final int USB_DT_ENCRYPTION_TYPE = 0x0e;
private static final int USB_DT_BOS = 0x0f;
private static final int USB_DT_DEVICE_CAPABILITY = 0x10;
private static final int USB_DT_WIRELESS_ENDPOINT_COMP = 0x11;
private static final int USB_DT_WIRE_ADAPTER = 0x21;
private static final int USB_DT_RPIPE = 0x22;
private static final int USB_DT_CS_RADIO_CONTROL = 0x23;
private static final int USB_DT_PIPE_USAGE = 0x24;
private static final int USB_DT_SS_ENDPOINT_COMP = 0x30;
private static final int USB_DT_CS_DEVICE = (USB_TYPE_CLASS | USB_DT_DEVICE);
private static final int USB_DT_CS_CONFIG = (USB_TYPE_CLASS | USB_DT_CONFIG);
private static final int USB_DT_CS_STRING = (USB_TYPE_CLASS | USB_DT_STRING);
private static final int USB_DT_CS_INTERFACE = (USB_TYPE_CLASS | USB_DT_INTERFACE);
private static final int USB_DT_CS_ENDPOINT = (USB_TYPE_CLASS | USB_DT_ENDPOINT);
private static final int USB_DT_DEVICE_SIZE = 18;
/**
* 指定したIDのStringディスクリプタから文字列を取得する。取得できなければnull
* @param connection
* @param id
* @param languageCount
* @param languages
* @return
*/
private static String getString(final UsbDeviceConnection connection, final int id, final int languageCount, final byte[] languages) {
final byte[] work = new byte[256];
String result = null;
for (int i = 1; i <= languageCount; i++) {
int ret = connection.controlTransfer(
USB_REQ_STANDARD_DEVICE_GET, // USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE
USB_REQ_GET_DESCRIPTOR,
(USB_DT_STRING << 8) | id, languages[i], work, 256, 0);
if ((ret > 2) && (work[0] == ret) && (work[1] == USB_DT_STRING)) {
// skip first two bytes(bLength & bDescriptorType), and copy the rest to the string
try {
result = new String(work, 2, ret - 2, "UTF-16LE");
if (!"Љ".equals(result)) { // 変なゴミが返ってくる時がある
break;
} else {
result = null;
}
} catch (final UnsupportedEncodingException e) {
// ignore
}
}
}
return result;
}
/**
* ベンダー名・製品名・バージョン・シリアルを取得する
* @param device
* @return
*/
public UsbDeviceInfo getDeviceInfo(final UsbDevice device) {
return updateDeviceInfo(mUsbManager, device, null);
}
/**
* ベンダー名・製品名・バージョン・シリアルを取得する
* #updateDeviceInfo(final UsbManager, final UsbDevice, final UsbDeviceInfo)のヘルパーメソッド
* @param context
* @param device
* @return
*/
public static UsbDeviceInfo getDeviceInfo(final Context context, final UsbDevice device) {
return updateDeviceInfo((UsbManager)context.getSystemService(Context.USB_SERVICE), device, new UsbDeviceInfo());
}
/**
* ベンダー名・製品名・バージョン・シリアルを取得する
* @param manager
* @param device
* @param _info
* @return
*/
public static UsbDeviceInfo updateDeviceInfo(final UsbManager manager, final UsbDevice device, final UsbDeviceInfo _info) {
final UsbDeviceInfo info = _info != null ? _info : new UsbDeviceInfo();
info.clear();
if (device != null) {
if (BuildCheck.isLollipop()) {
info.manufacturer = device.getManufacturerName();
info.product = device.getProductName();
info.serial = device.getSerialNumber();
}
if (BuildCheck.isMarshmallow()) {
info.usb_version = device.getVersion();
}
if ((manager != null) && manager.hasPermission(device)) {
final UsbDeviceConnection connection = manager.openDevice(device);
final byte[] desc = connection.getRawDescriptors();
if (TextUtils.isEmpty(info.usb_version)) {
info.usb_version = String.format("%x.%02x", ((int)desc[3] & 0xff), ((int)desc[2] & 0xff));
}
if (TextUtils.isEmpty(info.version)) {
info.version = String.format("%x.%02x", ((int)desc[13] & 0xff), ((int)desc[12] & 0xff));
}
if (TextUtils.isEmpty(info.serial)) {
info.serial = connection.getSerial();
}
final byte[] languages = new byte[256];
int languageCount = 0;
// controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)
try {
int result = connection.controlTransfer(
USB_REQ_STANDARD_DEVICE_GET, // USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE
USB_REQ_GET_DESCRIPTOR,
(USB_DT_STRING << 8) | 0, 0, languages, 256, 0);
if (result > 0) {
languageCount = (result - 2) / 2;
}
if (languageCount > 0) {
if (TextUtils.isEmpty(info.manufacturer)) {
info.manufacturer = getString(connection, desc[14], languageCount, languages);
}
if (TextUtils.isEmpty(info.product)) {
info.product = getString(connection, desc[15], languageCount, languages);
}
if (TextUtils.isEmpty(info.serial)) {
info.serial = getString(connection, desc[16], languageCount, languages);
}
}
} finally {
connection.close();
}
}
if (TextUtils.isEmpty(info.manufacturer)) {
info.manufacturer = USBVendorId.vendorName(device.getVendorId());
}
if (TextUtils.isEmpty(info.manufacturer)) {
info.manufacturer = String.format("%04x", device.getVendorId());
}
if (TextUtils.isEmpty(info.product)) {
info.product = String.format("%04x", device.getProductId());
}
}
return info;
}
/**
* control class
* never reuse the instance when it closed
*/
public static final class UsbControlBlock implements Cloneable {
private final WeakReference<USBMonitor> mWeakMonitor;
private final WeakReference<UsbDevice> mWeakDevice;
protected UsbDeviceConnection mConnection;
protected final UsbDeviceInfo mInfo;
private final int mBusNum;
private final int mDevNum;
private final SparseArray<SparseArray<UsbInterface>> mInterfaces = new SparseArray<SparseArray<UsbInterface>>();
/**
* this class needs permission to access USB device before constructing
* @param monitor
* @param device
*/
private UsbControlBlock(final USBMonitor monitor, final UsbDevice device) {
if (DEBUG) Log.i(TAG, "UsbControlBlock:constructor");
mWeakMonitor = new WeakReference<USBMonitor>(monitor);
mWeakDevice = new WeakReference<UsbDevice>(device);
mConnection = monitor.mUsbManager.openDevice(device);
mInfo = updateDeviceInfo(monitor.mUsbManager, device, null);
final String name = device.getDeviceName();
final String[] v = !TextUtils.isEmpty(name) ? name.split("/") : null;
int busnum = 0;
int devnum = 0;
if (v != null) {
busnum = Integer.parseInt(v[v.length-2]);
devnum = Integer.parseInt(v[v.length-1]);
}
mBusNum = busnum;
mDevNum = devnum;
// if (DEBUG) {
if (mConnection != null) {
final int desc = mConnection.getFileDescriptor();
final byte[] rawDesc = mConnection.getRawDescriptors();
Log.i(TAG, String.format(Locale.US, "name=%s,desc=%d,busnum=%d,devnum=%d,rawDesc=", name, desc, busnum, devnum) + rawDesc);
} else {
Log.e(TAG, "could not connect to device " + name);
}
// }
}
/**
* copy constructor
* @param src
* @throws IllegalStateException
*/
private UsbControlBlock(final UsbControlBlock src) throws IllegalStateException {
final USBMonitor monitor = src.getUSBMonitor();
final UsbDevice device = src.getDevice();
if (device == null) {
throw new IllegalStateException("device may already be removed");
}
mConnection = monitor.mUsbManager.openDevice(device);
if (mConnection == null) {
throw new IllegalStateException("device may already be removed or have no permission");
}
mInfo = updateDeviceInfo(monitor.mUsbManager, device, null);
mWeakMonitor = new WeakReference<USBMonitor>(monitor);
mWeakDevice = new WeakReference<UsbDevice>(device);
mBusNum = src.mBusNum;
mDevNum = src.mDevNum;
// FIXME USBMonitor.mCtrlBlocksに追加する(今はHashMapなので追加すると置き換わってしまうのでだめ, ListかHashMapにListをぶら下げる?)
}
/**
* duplicate by clone
* need permission
* USBMonitor never handle cloned UsbControlBlock, you should release it after using it.
* @return
* @throws CloneNotSupportedException
*/
@Override
public UsbControlBlock clone() throws CloneNotSupportedException {
final UsbControlBlock ctrlblock;
try {
ctrlblock = new UsbControlBlock(this);
} catch (final IllegalStateException e) {
throw new CloneNotSupportedException(e.getMessage());
}
return ctrlblock;
}
public USBMonitor getUSBMonitor() {
return mWeakMonitor.get();
}
public final UsbDevice getDevice() {
return mWeakDevice.get();
}
/**
* get device name
* @return
*/
public String getDeviceName() {
final UsbDevice device = mWeakDevice.get();
return device != null ? device.getDeviceName() : "";
}
/**
* get device id
* @return
*/
public int getDeviceId() {
final UsbDevice device = mWeakDevice.get();
return device != null ? device.getDeviceId() : 0;
}
/**
* get device key string
* @return same value if the devices has same vendor id, product id, device class, device subclass and device protocol
*/
public String getDeviceKeyName() {
return USBMonitor.getDeviceKeyName(mWeakDevice.get());
}
/**
* get device key string
* @param useNewAPI if true, try to use serial number
* @return
* @throws IllegalStateException
*/
public String getDeviceKeyName(final boolean useNewAPI) throws IllegalStateException {
if (useNewAPI) checkConnection();
return USBMonitor.getDeviceKeyName(mWeakDevice.get(), mInfo.serial, useNewAPI);
}
/**
* get device key
* @return
* @throws IllegalStateException
*/
public int getDeviceKey() throws IllegalStateException {
checkConnection();
return USBMonitor.getDeviceKey(mWeakDevice.get());
}
/**
* get device key
* @param useNewAPI if true, try to use serial number
* @return
* @throws IllegalStateException
*/
public int getDeviceKey(final boolean useNewAPI) throws IllegalStateException {
if (useNewAPI) checkConnection();
return USBMonitor.getDeviceKey(mWeakDevice.get(), mInfo.serial, useNewAPI);
}
/**
* get device key string
* if device has serial number, use it
* @return
*/
public String getDeviceKeyNameWithSerial() {
return USBMonitor.getDeviceKeyName(mWeakDevice.get(), mInfo.serial, false);
}
/**
* get device key
* if device has serial number, use it
* @return
*/
public int getDeviceKeyWithSerial() {
return getDeviceKeyNameWithSerial().hashCode();
}
/**
* get UsbDeviceConnection
* @return
*/
public synchronized UsbDeviceConnection getConnection() {
return mConnection;
}
/**
* get file descriptor to access USB device
* @return
* @throws IllegalStateException
*/
public synchronized int getFileDescriptor() throws IllegalStateException {
checkConnection();
return mConnection.getFileDescriptor();
}
/**
* get raw descriptor for the USB device
* @return
* @throws IllegalStateException
*/
public synchronized byte[] getRawDescriptors() throws IllegalStateException {
checkConnection();
return mConnection.getRawDescriptors();
}
/**
* get vendor id
* @return
*/
public int getVenderId() {
final UsbDevice device = mWeakDevice.get();
return device != null ? device.getVendorId() : 0;
}
/**
* get product id
* @return
*/
public int getProductId() {
final UsbDevice device = mWeakDevice.get();
return device != null ? device.getProductId() : 0;
}
/**
* get version string of USB
* @return
*/
public String getUsbVersion() {
return mInfo.usb_version;
}
/**
* get manufacture
* @return
*/
public String getManufacture() {
return mInfo.manufacturer;
}
/**
* get product name
* @return
*/
public String getProductName() {
return mInfo.product;
}
/**
* get version
* @return
*/
public String getVersion() {
return mInfo.version;
}
/**
* get serial number
* @return
*/
public String getSerial() {
return mInfo.serial;
}
public int getBusNum() {
return mBusNum;
}
public int getDevNum() {
return mDevNum;
}
/**
* get interface
* @param interface_id
* @throws IllegalStateException
*/
public synchronized UsbInterface getInterface(final int interface_id) throws IllegalStateException {
return getInterface(interface_id, 0);
}
/**
* get interface
* @param interface_id
* @param altsetting
* @return
* @throws IllegalStateException
*/
public synchronized UsbInterface getInterface(final int interface_id, final int altsetting) throws IllegalStateException {
checkConnection();
SparseArray<UsbInterface> intfs = mInterfaces.get(interface_id);
if (intfs == null) {
intfs = new SparseArray<UsbInterface>();
mInterfaces.put(interface_id, intfs);
}
UsbInterface intf = intfs.get(altsetting);
if (intf == null) {
final UsbDevice device = mWeakDevice.get();
final int n = device.getInterfaceCount();
for (int i = 0; i < n; i++) {
final UsbInterface temp = device.getInterface(i);
if ((temp.getId() == interface_id) && (temp.getAlternateSetting() == altsetting)) {
intf = temp;
break;
}
}
if (intf != null) {
intfs.append(altsetting, intf);
}
}
return intf;
}
/**
* open specific interface
* @param intf
*/
public synchronized void claimInterface(final UsbInterface intf) {
claimInterface(intf, true);
}
public synchronized void claimInterface(final UsbInterface intf, final boolean force) {
checkConnection();
mConnection.claimInterface(intf, force);
}
/**
* close interface
* @param intf
* @throws IllegalStateException
*/
public synchronized void releaseInterface(final UsbInterface intf) throws IllegalStateException {
checkConnection();
final SparseArray<UsbInterface> intfs = mInterfaces.get(intf.getId());
if (intfs != null) {
final int index = intfs.indexOfValue(intf);
intfs.removeAt(index);
if (intfs.size() == 0) {
mInterfaces.remove(intf.getId());
}
}
mConnection.releaseInterface(intf);
}
/**
* Close device
* This also close interfaces if they are opened in Java side
*/
public synchronized void close() {
if (DEBUG) Log.i(TAG, "UsbControlBlock#close:");
if (mConnection != null) {
final int n = mInterfaces.size();
for (int i = 0; i < n; i++) {
final SparseArray<UsbInterface> intfs = mInterfaces.valueAt(i);
if (intfs != null) {
final int m = intfs.size();
for (int j = 0; j < m; j++) {
final UsbInterface intf = intfs.valueAt(j);
mConnection.releaseInterface(intf);
}
intfs.clear();
}
}
mInterfaces.clear();
mConnection.close();
mConnection = null;
final USBMonitor monitor = mWeakMonitor.get();
if (monitor != null) {
if (monitor.mOnDeviceConnectListener != null) {
monitor.mOnDeviceConnectListener.onDisconnect(mWeakDevice.get(), UsbControlBlock.this);
}
monitor.mCtrlBlocks.remove(getDevice());
}
}
}
@Override
public boolean equals(final Object o) {
if (o == null) return false;
if (o instanceof UsbControlBlock) {
final UsbDevice device = ((UsbControlBlock) o).getDevice();
return device == null ? mWeakDevice.get() == null
: device.equals(mWeakDevice.get());
} else if (o instanceof UsbDevice) {
return o.equals(mWeakDevice.get());
}
return super.equals(o);
}
// @Override
// protected void finalize() throws Throwable {
/// close();
// super.finalize();
// }
private synchronized void checkConnection() throws IllegalStateException {
if (mConnection == null) {
throw new IllegalStateException("already closed");
}
}
}
}
|
0
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant/usb/USBVendorId.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usb;
import android.util.SparseArray;
public class USBVendorId {
private static final SparseArray<String> IDS = new SparseArray<String>();
public static String vendorName(final int vendor_id) {
return IDS.get(vendor_id);
}
static {
IDS.put(10006, "YUEN DA ELECTRONIC PRODUCTS FACTORY");
IDS.put(10013, "Gionee Communication Equipment Co., Ltd. ShenZhen");
IDS.put(10022, "Universal Electronics Inc. (dba: TVIEW)");
IDS.put(1003, "Atmel Corporation");
IDS.put(1006, "Mitsumi");
IDS.put(1008, "HP Inc.");
IDS.put(10112, "M31 Technology Corp.");
IDS.put(10113, "Liteconn Co., Ltd.");
IDS.put(10121, "Suzhou WEIJU Electronics Technology Co., Ltd.");
IDS.put(10144, "Mondokey Limited");
IDS.put(10149, "Advantest Corporation");
IDS.put(10150, "iRobot Corporation");
IDS.put(1020, "Elitegroup Computer Systems");
IDS.put(1021, "Xilinx Inc.");
IDS.put(10226, "Sibridge Tech.");
IDS.put(1026, "ALi Corporation");
IDS.put(1027, "Future Technology Devices International Limited");
IDS.put(10275, "Dongguan Jiumutong Industry Co., Ltd.");
IDS.put(10289, "Power Integrations");
IDS.put(10291, "Oculus VR, Inc.");
IDS.put(10300, "HIGH TEK HARNESS ENTERPRISE CO., LTD.");
IDS.put(10316, "Full in Hope Co., Ltd.");
IDS.put(1032, "Quanta Computer Inc.");
IDS.put(10329, "Viconn Technology (HK) Co., Ltd.");
IDS.put(1033, "NEC Corporation");
IDS.put(1035, "Weltrend Semiconductor");
IDS.put(1037, "VIA Technologies, Inc.");
IDS.put(10374, "Seeed Technology Co., Ltd.");
IDS.put(10375, "Specwerkz");
IDS.put(1038, "MCCI Corporation");
IDS.put(10398, "Esselte Leitz GmbH & Co. KG");
IDS.put(10406, "E-SEEK Inc.");
IDS.put(1041, "BUFFALO INC.");
IDS.put(10423, "Pleora Technologies Inc.");
IDS.put(10431, "Vitetech Int'l Co., Ltd.");
IDS.put(1044, "Giga-Byte Technology Co., Ltd.");
IDS.put(10446, "Changzhou Shi Wujin Miqi East Electronic Co., Ltd.");
IDS.put(10457, "Shenzhen Ourconn Technology Co., Ltd.");
IDS.put(10458, "G.SKILL Int'l Enterprice Co., Ltd.");
IDS.put(1046, "Nuvoton Technology Corp.");
IDS.put(10466, "Surplus Electronic Technology Co., Ltd.");
IDS.put(10470, "BIAMP SYSTEMS");
IDS.put(10509, "IBCONN Technologies (Shenzhen) Co., Ltd.");
IDS.put(10510, "Fugoo Inc.");
IDS.put(10519, "Pan Xin Precision Electronics Co., Ltd.");
IDS.put(10530, "Dongguan Digi-in Digital Technology Co., Ltd.");
IDS.put(1054, "Creative Labs");
IDS.put(10540, "GENUSION, Inc.");
IDS.put(10544, "Ineda Systems Inc.");
IDS.put(10545, "Jolla Ltd.");
IDS.put(10546, "Peraso Technologies, Inc.");
IDS.put(10549, "Nanjing Magewell Electronics Co., Ltd.");
IDS.put(10560, "Shenzhen Yiwanda Electronics Co., Ltd.");
IDS.put(1057, "Nokia Corporation");
IDS.put(10575, "Dollar Connection Ltd.");
IDS.put(10595, "BIO-key International, Inc.");
IDS.put(1060, "Microchip-SMSC");
IDS.put(10603, "Xacti Corporation");
IDS.put(10615, "Shenzhen Zowee Technology Co., Ltd.");
IDS.put(10643, "ADPlaus Technology Limited");
IDS.put(10646, "Unwired Technology");
IDS.put(1065, "Cirrus Logic Inc.");
IDS.put(10657, "Union Electric Plug & Connector Corp.");
IDS.put(10674, "Canova Tech");
IDS.put(10685, "Silicon Works");
IDS.put(10695, "HANRICO ANFU ELECTRONICS CO., LTD.");
IDS.put(10700, "Kodak Alaris");
IDS.put(10702, "JGR Optics Inc.");
IDS.put(10703, "Richtek Technology Corporation");
IDS.put(10705, "Binatone Electronics Int. Ltd.");
IDS.put(1071, "Molex Inc.");
IDS.put(10715, "Shenzhen iBoard Technology Co., Ltd.");
IDS.put(10719, "SMIT(HK) Limited");
IDS.put(1072, "Fujitsu Component Limited");
IDS.put(10725, "Dongguan Kechenda Electronic Technology Co., Ltd.");
IDS.put(10726, "Fengshun Peiying Electro-Acoustic Co., Ltd.");
IDS.put(10744, "MD ELEKTRONIK GmbH");
IDS.put(10749, "Bad Elf, LLC");
IDS.put(10770, "Vreo Limited");
IDS.put(10772, "Kanex");
IDS.put(10781, "Oxford Nanopore Technologies");
IDS.put(10782, "Obsidian Technology");
IDS.put(10783, "Lucent Trans Electronics Co., Ltd.");
IDS.put(10784, "GUOGUANG GROUP CO., LTD.");
IDS.put(10788, "CNPLUS");
IDS.put(10789, "Fourstar Group");
IDS.put(10790, "Tragant International Co., Ltd.");
IDS.put(10791, "DongGuan LianGang Optoelectronic Technology Co., Ltd.");
IDS.put(10797, "Atrust Computer Corp.");
IDS.put(10798, "VIA Alliance Semiconductor Co., Ltd.");
IDS.put(10799, "BSUN Electronics Co., Ltd.");
IDS.put(1080, "Advanced Micro Devices");
IDS.put(10807, "RTD Embedded Technologies, Inc.");
IDS.put(10816, "Shenzhen Choseal Industrial Co., Ltd.");
IDS.put(10817, "Canyon Semiconductor");
IDS.put(10818, "Spectra7 Microsystems Corp.");
IDS.put(10821, "Meizu Technology Co., Ltd.");
IDS.put(10822, "Hubei Yingtong Telecommunication Cable Inc.");
IDS.put(10829, "Wilder Technologies");
IDS.put(10837, "Diodes Inc.");
IDS.put(10846, "DuPont");
IDS.put(1085, "Lexmark International Inc.");
IDS.put(10852, "Zhejiang Songcheng Electronics Co., Ltd.");
IDS.put(10859, "VSN Mobil");
IDS.put(10875, "Bellwether Electronic Corp.");
IDS.put(10878, "VAIO Corporation");
IDS.put(10879, "Perixx Computer GmbH");
IDS.put(10885, "HANK ELECTRONICS CO., LTD");
IDS.put(10892, "Sonnet Technologies, Inc.");
IDS.put(10893, "Keysight Technologies Inc.");
IDS.put(10895, "Manutronics Vietnam Joint Stock Company");
IDS.put(10900, "G2 Touch Co., Ltd.");
IDS.put(10902, "Micromax Informatics Ltd");
IDS.put(10910, "SEIKO SOLUTIONS Inc.");
IDS.put(10912, "Casco Products Corp.");
IDS.put(10922, "Virtium Technology, Inc.");
IDS.put(10923, "Field and Company LLC, dba Leef USA");
IDS.put(10928, "GM Global Technology Operations LLC");
IDS.put(10931, "Key Asic Inc.");
IDS.put(10943, "Revolabs, Inc.");
IDS.put(10945, "Lattice Semiconductor Corp");
IDS.put(10947, "Foshan Nanhai Saga Audio Equipment Co., Ltd.");
IDS.put(10957, "Silergy Corp.");
IDS.put(10963, "Shenzhen Hali-Power Industrial Co., Ltd.");
IDS.put(10971, "I-PEX (Dai-ichi Seiko)");
IDS.put(10973, "SEE-PLUS INDUSTRIAL LTD.");
IDS.put(10990, "Adapt-IP Company");
IDS.put(10997, "Libratone A/S");
IDS.put(10999, "Shenzhen Hazens Automotive Electronics (SZ) Co., Ltd.");
IDS.put(11000, "Jiangsu Toppower Automotive Electronics Co., Ltd.");
IDS.put(11001, "Drapho Electronics Technology Co., Ltd.");
IDS.put(1102, "Alps Electric Co., Ltd.");
IDS.put(11022, "Le Shi Zhi Xin Electronic Technology (Tian Jin) Limited");
IDS.put(11024, "Cardiac Insight, Inc.");
IDS.put(11028, "EverPro Technologies Company, Ltd.");
IDS.put(11029, "Rosenberger Hochfrequenztechnik");
IDS.put(11035, "Dongguan City Sanji Electronics Co., Ltd.");
IDS.put(11037, "Lintes Technology Co., Ltd.");
IDS.put(11039, "KinnexA, Inc.");
IDS.put(11042, "Metra Electronics Corp.");
IDS.put(11044, "KeepKey, LLC");
IDS.put(11047, "FluxData Incorporated");
IDS.put(1105, "Texas Instruments");
IDS.put(11061, "Assem Technology Co., Ltd.");
IDS.put(11062, "Dongguan City Jianghan Electronics Co., Ltd.");
IDS.put(11063, "Huizhou Desay SV Automotive Co., Ltd.");
IDS.put(11064, "Ningbo Rixing Electronics Co., Ltd.");
IDS.put(11069, "GuangDong YuanFeng Automotive Electroics Co., Ltd.");
IDS.put(11080, "Sounding Audio Industrial Limited");
IDS.put(11082, "Yueqing Huaxin Electronic Co., Ltd.");
IDS.put(11098, "Universal Audio, Inc.");
IDS.put(11111, "Lifesize, Inc.");
IDS.put(11123, "Pioneer DJ Corporation");
IDS.put(11124, "Embedded Intelligence, Inc.");
IDS.put(11125, "New Matter");
IDS.put(11126, "Shanghai Wingtech Electronic Technology Co., Ltd.");
IDS.put(11127, "Epiphan Systems Inc.");
IDS.put(11130, "Spin Master Far East Ltd.");
IDS.put(11131, "Gigaset Digital Technology (Shenzhen) Co., Ltd.");
IDS.put(11132, "Noveltek Semiconductor Corp.");
IDS.put(11139, "Silicon Line GmbH");
IDS.put(11140, "Ever Win International Corp.");
IDS.put(11144, "Socionext Inc.");
IDS.put(11145, "Ugreen Group Limited");
IDS.put(11146, "Shanghai Pateo Electronic Equipment Mfg. Co., Ltd.");
IDS.put(1115, "Renesas Electronics Corp.");
IDS.put(11154, "i-BLADES, Inc.");
IDS.put(11155, "Altia Systems Inc.");
IDS.put(11156, "ShenZhen Baoyuanda Electronics Co., Ltd.");
IDS.put(11157, "iST - Integrated Service Technology Inc.");
IDS.put(11158, "HYUNDAI MOBIS Co., Ltd.");
IDS.put(11161, "360fly, Inc.");
IDS.put(11162, "HUIZHOU CHENG SHUO HARDWARE PLASTIC CO., LTD.");
IDS.put(11163, "Zhongshan Aute Electronics Technology Co., Ltd.");
IDS.put(11164, "Guangdong King Link Industrial Co., Ltd.");
IDS.put(11167, "Scietera Technologies, Inc.");
IDS.put(11168, "InVue Security Products");
IDS.put(11169, "I-Sheng Electric Wire & Cable Co., Ltd.");
IDS.put(11170, "China Daheng Group Inc Beijing Image Vision Tech Branch");
IDS.put(11171, "Shenzhen FeiTianXia Technology Ltd.");
IDS.put(11172, "Shenzhen HengJia New Energy Auto Part Co., Ltd.");
IDS.put(11175, "77 Elektronika Kft.");
IDS.put(11176, "YUDU EASON ELECTRONIC CO., LTD.");
IDS.put(1118, "Microsoft Corporation");
IDS.put(11181, "XIN JI (SHENZHEN) COMPUTER PARTS CO., LTD.");
IDS.put(11189, "Silk ID Systems");
IDS.put(11190, "3D Imaging & Simulations Corp. (3DISC)");
IDS.put(11191, "Dongguan ChengXiang Industrial Co., Ltd.");
IDS.put(11192, "OCC (Zhuhai) Electronic Co., Ltd.");
IDS.put(11194, "Sinseader Electronic Co., Ltd.");
IDS.put(11195, "DONGGUAN YELLOWKNIFE Industrial Co., Ltd.");
IDS.put(11197, "RF Creations Ltd.");
IDS.put(11198, "Chengyi Semiconductors (Shanghai) Co., Ltd.");
IDS.put(11199, "Shenzhen Shinning Electronic Co., Ltd.");
IDS.put(11200, "Shenzhen WFD Electronics Co., Ltd.");
IDS.put(11201, "Dongguan Sino Syncs Industrial Co., Ltd.");
IDS.put(11202, "JNTC Co., Ltd.");
IDS.put(11208, "DONGGUAN POLIXIN ELECTRIC CO., LTD.");
IDS.put(11209, "Tama Electric (Suzhou) Co., Ltd.");
IDS.put(1121, "Primax Electronics");
IDS.put(11210, "Exvision, Inc.");
IDS.put(11216, "mophie, LLC");
IDS.put(11219, "Dongguan ULT-unite electronic technology co., LTD");
IDS.put(11220, "JL Audio, Inc.");
IDS.put(11221, "Cable Matters Inc.");
IDS.put(11222, "CoroWare, Inc.");
IDS.put(11229, "Charm Sciences Inc.");
IDS.put(1123, "EATON");
IDS.put(11230, "Pickering Interfaces Limited");
IDS.put(11231, "Hangzhou Hikvision Digital Technology Co., Ltd.");
IDS.put(11232, "FULLINK ELECTRONICS TECHNOLOGY (SZ) LTD");
IDS.put(11233, "AutoChips Inc.");
IDS.put(11234, "Electric Connector Technology Co., Ltd.");
IDS.put(11237, "LELTEK");
IDS.put(11238, "Dongguan KaiWin Electronics Co., Ltd.");
IDS.put(11239, "BEFS Co., Ltd.");
IDS.put(11240, "Archisite, Inc.");
IDS.put(11241, "Magneti Marelli S.p.A Electr BL");
IDS.put(11246, "Ventev Mobile");
IDS.put(11247, "Quanta Storage Inc.");
IDS.put(11248, "Tech-Top Technology Limited");
IDS.put(11253, "Shenzhen YOOBAO Technology Co., Ltd.");
IDS.put(11254, "Shenzhen Sinotek Technology Co., Ltd.");
IDS.put(11255, "KEYW");
IDS.put(11256, "Visual Land Inc.");
IDS.put(11264, "MEEM SL Ltd");
IDS.put(11265, "Dongguan Arin Electronics Technology Co., Ltd.");
IDS.put(11266, "DongGuan City JianNuo Electronics Co., Ltd.");
IDS.put(11268, "Shenzhen XOX Electronics Co., Ltd.");
IDS.put(11269, "Protop International Inc.");
IDS.put(11270, "Microsemi Semiconductor (US) Inc.");
IDS.put(11271, "Webcloak LLC");
IDS.put(11272, "INVECAS INC.");
IDS.put(11274, "ATANS Technology Inc.");
IDS.put(11275, "Triple Win Precision Technology Co., Ltd.");
IDS.put(11276, "IC Realtech");
IDS.put(11277, "Embrava Pty Ltd");
IDS.put(1128, "Wieson Technologies Co., Ltd.");
IDS.put(11280, "Sinotronics Co., Ltd.");
IDS.put(11281, "ALLBEST ELECTRONICS TECHNOLOGY CO., LTD.");
IDS.put(11282, "Shenzhen Xin Kai Feng Electronics Factory");
IDS.put(11283, "MOST WELL Technology Corp.");
IDS.put(11284, "Buffalo Memory Co., Ltd.");
IDS.put(11285, "Xentris Wireless");
IDS.put(11286, "Priferential Accessories Ltd");
IDS.put(11289, "Sunlike Technology Co., Ltd.");
IDS.put(11290, "Young Fast Optoelectronics Co., Ltd.");
IDS.put(11291, "ISAW Camera Inc");
IDS.put(11298, "Qanba USA, LLC");
IDS.put(11299, "Super Micro Computer Inc.");
IDS.put(11302, "Micromax International Corporation");
IDS.put(11304, "Granite River Labs Japan Ltd.");
IDS.put(11305, "Coagent Enterprise Limited");
IDS.put(11306, "LEIA Inc.");
IDS.put(11309, "Shenzhen Ebull Technology Limited");
IDS.put(1131, "American Megatrends");
IDS.put(11310, "Hualun Technology Co., Ltd.");
IDS.put(11311, "Sensel, Inc.");
IDS.put(11319, "Shenzhen Adition Audio Science & Technology Co., Ltd.");
IDS.put(11320, "Goldenconn Electronics Technology (Suzhou) Co., Ltd.");
IDS.put(11321, "JIB Electronics Technology Co., Ltd.");
IDS.put(11322, "Changzhou Shinco Automotive Electronics Co., Ltd.");
IDS.put(11323, "Shenzhen Hangsheng Electronics Corp., Ltd.");
IDS.put(11324, "Beartooth Radio, Inc.");
IDS.put(11325, "Audience, A Knowles Company");
IDS.put(11327, "Nextbit Systems, Inc.");
IDS.put(11328, "Leadtrend");
IDS.put(11329, "Adaptertek Technology Co., Ltd.");
IDS.put(1133, "Logitech Inc.");
IDS.put(11330, "Feature Integration Technology Inc.");
IDS.put(11331, "Avegant Corporation");
IDS.put(11335, "Chunghsin International Electronics Co., Ltd.");
IDS.put(11336, "Delphi Electrical Centers (Shanghai) Co., Ltd.");
IDS.put(11341, "VVETEK DOO");
IDS.put(11347, "Huizhou Foryou General Electronics Co., Ltd.");
IDS.put(11348, "LifeWatch Technologies Ltd.");
IDS.put(11349, "Magicleap");
IDS.put(11355, "Dongguan City Shenglan Electronics Co., LTD.");
IDS.put(11356, "Neusoft Corporation");
IDS.put(11357, "SIP Simya Electronics Technology Co., Ltd.");
IDS.put(11358, "GNSD Automotive Co., Ltd.");
IDS.put(11359, "YOODS Co., Ltd.");
IDS.put(11360, "Sirin Mobile Technologies AG");
IDS.put(11361, "Jadmam Corporation dba: Boytone");
IDS.put(11373, "Gibson Innovations");
IDS.put(11374, "Shen Zhen Xian Shuo Technology Co. LTD");
IDS.put(11375, "PST Eletronica LTDA");
IDS.put(11376, "PERI, Inc.");
IDS.put(11377, "Bozhou BoTong Information Technology Co., Ltd.");
IDS.put(11383, "Profindustry GmbH");
IDS.put(11384, "BRAGI GmbH");
IDS.put(11385, "WAWGD, Inc. (DBA: Foresight Sports)");
IDS.put(11390, "Dongguan Allpass Electronic Co., Ltd.");
IDS.put(11391, "SHENZHEN D-VITEC INDUSTRIAL CO., LTD.");
IDS.put(11392, "motomobile AG");
IDS.put(11393, "Indie Semiconductor");
IDS.put(11397, "Audientes");
IDS.put(11403, "Huizhou Dehong Technology Co., Ltd.");
IDS.put(11404, "PowerCenter Technology Limited");
IDS.put(11405, "Mizco International, Inc.");
IDS.put(11408, "I. AM. PLUS, LLC");
IDS.put(11409, "Corigine, Inc.");
IDS.put(11410, "Ningbo Yinzhou Shengke Electronics Co., Ltd.");
IDS.put(11417, "Prusa Research s.r.o.");
IDS.put(11423, "e-Smart Systems Pvt. Ltd.");
IDS.put(11424, "Leagtech Jiangxi Electronic Co., Ltd.");
IDS.put(11425, "Dongguan Yujia Electronics Technology Co., Ltd.");
IDS.put(11426, "GuangZhou MingPing Electronics Technology");
IDS.put(11427, "DJI Technology Co., Ltd.");
IDS.put(11428, "Shenzhen Alex Technology Co., Ltd.");
IDS.put(11433, "JITS TECHNOLOGY CO., LIMITED");
IDS.put(11434, "LIVV Brand llc");
IDS.put(11444, "Ava Enterprises, Inc. dba: Boss Audio Systems");
IDS.put(11448, "Shenzhen Sydixon Electronic Technology Co., Ltd.");
IDS.put(11449, "On-Bright Electronics (Shanghai) Co., Ltd.");
IDS.put(11450, "Dongguan Puxu Industrial Co., Ltd.");
IDS.put(11451, "Shenzhen Soling Indusrtial Co., Ltd.");
IDS.put(11453, "EGGCYTE, INC.");
IDS.put(11455, "Donggguan Yuhua Electronic Co., Ltd.");
IDS.put(11456, "Hangzhou Zero Zero Technology Co., Ltd.");
IDS.put(11462, "Prodigy Technovations Pvt Ltd");
IDS.put(11463, "EmergiTech, Inc");
IDS.put(11464, "Hewlett Packard Enterprise");
IDS.put(11465, "Monolithic Power Systems Inc.");
IDS.put(11467, "USB Memory Direct");
IDS.put(11468, "Silicon Mitus Inc.");
IDS.put(11472, "Technics Global Electronics & JCE Co., Ltd.");
IDS.put(11478, "Immersive Media");
IDS.put(11479, "Cosemi Technologies Inc.");
IDS.put(11481, "Cambrionix Ltd");
IDS.put(11482, "CXUN Co. Ltd.");
IDS.put(11483, "China Tsp Inc");
IDS.put(11490, "Yanfeng Visteon (Chongqing) Automotive Electronics Co");
IDS.put(11491, "Alcorlink Corp.");
IDS.put(11492, "ISBC Ltd.");
IDS.put(11493, "InX8 Inc dba: AKiTiO");
IDS.put(11494, "SDAN Tecchnology Co., Ltd.");
IDS.put(11495, "Lemobile Information Technology (Beijing) Co., Ltd.");
IDS.put(11496, "GongGuan HWX Electronic Technology Co., Ltd.");
IDS.put(11497, "Suzhu Jingshi Electronic Technology Co., Ltd.");
IDS.put(11498, "Zhong Shan City Richsound Electronic Industrial Ltd.");
IDS.put(11499, "Dongguang Kangbang Electronics Co., Ltd.");
IDS.put(1151, "Plantronics, Inc.");
IDS.put(1154, "Kyocera Corporation");
IDS.put(1155, "STMicroelectronics");
IDS.put(1161, "Foxconn / Hon Hai");
IDS.put(1165, "ITE Tech Inc.");
IDS.put(1177, "Yamaha Corporation");
IDS.put(1188, "Hitachi, Ltd.");
IDS.put(1191, "Visioneer");
IDS.put(1193, "Canon Inc.");
IDS.put(1200, "Nikon Corporation");
IDS.put(1201, "Pan International");
IDS.put(1204, "Cypress Semiconductor");
IDS.put(1205, "ROHM Co., Ltd.");
IDS.put(1207, "Compal Electronics, Inc.");
IDS.put(1208, "Seiko Epson Corp.");
IDS.put(1211, "I-O Data Device, Inc.");
IDS.put(1221, "Fujitsu Ltd.");
IDS.put(1227, "FUJIFILM Corporation");
IDS.put(1238, "Mentor Graphics");
IDS.put(1240, "Microchip Technology Inc.");
IDS.put(1241, "Holtek Semiconductor, Inc.");
IDS.put(1242, "Panasonic Corporation");
IDS.put(1245, "Sharp Corporation");
IDS.put(1250, "Exar Corporation");
IDS.put(1254, "Identiv, Inc.");
IDS.put(1256, "Samsung Electronics Co., Ltd.");
IDS.put(1260, "Tokyo Electron Device Limited");
IDS.put(1266, "Chicony Electronics Co., Ltd.");
IDS.put(1271, "Newnex Technology Corp.");
IDS.put(1273, "Brother Industries, Ltd.");
IDS.put(1276, "SUNPLUS TECHNOLOGY CO., LTD.");
IDS.put(1278, "PFU Limited");
IDS.put(1281, "Fujikura/DDK");
IDS.put(1282, "Acer, Inc.");
IDS.put(1287, "Hosiden Corporation");
IDS.put(1293, "Belkin International, Inc.");
IDS.put(1300, "FCI Electronics");
IDS.put(1302, "Longwell Electronics/Longwell Company");
IDS.put(1305, "Star Micronics Co., LTD");
IDS.put(1309, "American Power Conversion");
IDS.put(1314, "ACON, Advanced-Connectek, Inc.");
IDS.put(1343, "Synopsys, Inc.");
IDS.put(1356, "Sony Corporation");
IDS.put(1360, "Fuji Xerox Co., Ltd.");
IDS.put(1367, "ATEN International Co. Ltd.");
IDS.put(1369, "Cadence Design Systems, Inc.");
IDS.put(1386, "WACOM Co., Ltd.");
IDS.put(1389, "EIZO Corporation");
IDS.put(1390, "Elecom Co., Ltd.");
IDS.put(1394, "Conexant Systems, Inc.");
IDS.put(1398, "BAFO/Quality Computer Accessories");
IDS.put(1403, "Y-E Data, Inc.");
IDS.put(1404, "AVM GmbH");
IDS.put(1410, "Roland Corporation");
IDS.put(1412, "RATOC Systems, Inc.");
IDS.put(1419, "Infineon Technologies");
IDS.put(1423, "Alcor Micro, Corp.");
IDS.put(1424, "OMRON Corporation");
IDS.put(1447, "Bose Corporation");
IDS.put(1449, "OmniVision Technologies, Inc.");
IDS.put(1452, "Apple");
IDS.put(1453, "Y.C. Cable U.S.A., Inc");
IDS.put(14627, "National Instruments");
IDS.put(1470, "Tyco Electronics Corp., a TE Connectivity Ltd. company");
IDS.put(1473, "MegaChips Corporation");
IDS.put(1478, "Qualcomm, Inc");
IDS.put(1480, "Foxlink/Cheng Uei Precision Industry Co., Ltd.");
IDS.put(1482, "Ricoh Company Ltd.");
IDS.put(1498, "Microtek International Inc.");
IDS.put(1504, "Symbol Technologies");
IDS.put(1507, "Genesys Logic, Inc.");
IDS.put(1509, "Fuji Electric Co., Ltd.");
IDS.put(1525, "Unixtar Technology Inc.");
IDS.put(1529, "Datalogic ADC");
IDS.put(1535, "LeCroy Corporation");
IDS.put(1539, "Novatek Microelectronics Corp.");
IDS.put(1545, "SMK Manufacturing Inc.");
IDS.put(1551, "Joinsoon Electronics Mfg. Co., Ltd.");
IDS.put(1555, "TransAct Technologies Incorporated");
IDS.put(1561, "Seiko Instruments Inc.");
IDS.put(1582, "JPC/MAIN SUPER Inc.");
IDS.put(1583, "Sin Sheng Terminal & Machine Inc.");
IDS.put(1593, "Chrontel, Inc.");
IDS.put(1611, "Analog Devices, Inc. Development Tools");
IDS.put(1612, "Ji-Haw Industrial Co., Ltd");
IDS.put(1614, "Suyin Corporation");
IDS.put(1621, "Space Shuttle Hi-Tech Co.,Ltd.");
IDS.put(1622, "Glory Mark Electronic Ltd.");
IDS.put(1623, "Tekcon Electronics Corp.");
IDS.put(1624, "Sigma Designs, Inc.");
IDS.put(1631, "Good Way Technology Co., Ltd. & GWC technology Inc");
IDS.put(1632, "TSAY-E (BVI) International Inc.");
IDS.put(1633, "Hamamatsu Photonics K.K.");
IDS.put(1642, "Total Technologies, Ltd.");
IDS.put(1659, "Prolific Technology, Inc.");
IDS.put(16700, "Dell Inc.");
IDS.put(1680, "Golden Bridge Electech Inc.");
IDS.put(1689, "Tektronix, Inc.");
IDS.put(1690, "Askey Computer Corporation");
IDS.put(1709, "Greatland Electronics Taiwan Ltd.");
IDS.put(1710, "Eurofins Digital Testing Belgium");
IDS.put(1720, "Pixela Corporation");
IDS.put(1724, "Oki Data Corporation");
IDS.put(1727, "Leoco Corporation");
IDS.put(1732, "Bizlink Technology, Inc.");
IDS.put(1736, "SIIG, Inc.");
IDS.put(1747, "Mitsubishi Electric Corporation");
IDS.put(1758, "Heisei Technology Co., Ltd.");
IDS.put(1802, "Oki Electric Industry Co., Ltd.");
IDS.put(1805, "Comoss Electronic Co., Ltd.");
IDS.put(1809, "Magic Control Technology Corp.");
IDS.put(1816, "Imation Corp.");
IDS.put(1838, "Sunix Co., Ltd.");
IDS.put(1846, "Lorom Industrial Co., Ltd.");
IDS.put(1848, "Mad Catz, Inc.");
IDS.put(1899, "HID Global GmbH");
IDS.put(1901, "Denso Corporation");
IDS.put(1913, "Fairchild Semiconductor");
IDS.put(1921, "SanDisk Corporation");
IDS.put(1937, "Copartner Technology Corporation");
IDS.put(1954, "National Technical Systems");
IDS.put(1971, "Plustek, Inc.");
IDS.put(1972, "OLYMPUS CORPORATION");
IDS.put(1975, "TIME Interconnect Ltd.");
IDS.put(1994, "AVerMedia Technologies, Inc.");
IDS.put(1999, "Casio Computer Co., Ltd.");
IDS.put(2015, "David Electronics Company, Ltd.");
IDS.put(2039, "Century Corporation");
IDS.put(2058, "Evermuch Technology Co., Ltd.");
IDS.put(2101, "Action Star Enterprise Co., Ltd.");
IDS.put(2112, "Argosy Research Inc.");
IDS.put(2122, "Wipro Limited");
IDS.put(2159, "MEC IMEX INC/HPT");
IDS.put(2205, "Icron Technologies Corporation");
IDS.put(2247, "TAI TWUN ENTERPRISE CO., LTD.");
IDS.put(2276, "Pioneer Corporation");
IDS.put(2278, "Gemalto SA");
IDS.put(2310, "FARADAY Technology Corp.");
IDS.put(2313, "Audio-Technica Corp.");
IDS.put(2316, "Silicon Motion, Inc. - Taiwan");
IDS.put(2334, "Garmin International");
IDS.put(2352, "Toshiba Corporation");
IDS.put(2362, "Pixart Imaging, Inc.");
IDS.put(2363, "Plextor LLC");
IDS.put(2366, "J.S.T. Mfg. Co., Ltd.");
IDS.put(2385, "Kingston Technology Company");
IDS.put(2389, "NVIDIA");
IDS.put(2395, "Medialogic Corporation");
IDS.put(2397, "Polycom, Inc.");
IDS.put(2468, "Contech Research, Inc.");
IDS.put(2472, "Lin Shiung Enterprise Co., Ltd.");
IDS.put(2475, "Japan Cash Machine Co., Ltd.");
IDS.put(2498, "NISCA Corporation");
IDS.put(2511, "Electronics Testing Center, Taiwan");
IDS.put(2522, "A-FOUR TECH CO., LTD.");
IDS.put(2555, "Altera");
IDS.put(2578, "Cambridge Silicon Radio Ltd.");
IDS.put(2583, "HOYA Corporation");
IDS.put(2631, "Hirose Electric Co., Ltd.");
IDS.put(2636, "COMPUTEX Co., Ltd.");
IDS.put(2640, "Mimaki Engineering Co., Ltd.");
IDS.put(2652, "Broadcom Corp.");
IDS.put(2667, "Green House Co., Ltd.");
IDS.put(2702, "Japan Aviation Electronics Industry Ltd. (JAE)");
IDS.put(2727, "Wincor Nixdorf GmbH & Co KG");
IDS.put(2733, "Rohde & Schwarz GmbH & Co. KG");
IDS.put(2787, "Allion Labs, Inc.");
IDS.put(2821, "ASUSTek Computer Inc.");
IDS.put(2849, "Yokogawa Electric Corporation");
IDS.put(2851, "Pan-Asia Electronics Co., Ltd.");
IDS.put(2894, "Musical Electronics Ltd.");
IDS.put(2907, "Anritsu Corporation");
IDS.put(2922, "Maxim Integrated Products");
IDS.put(2965, "ASIX Electronics Corporation");
IDS.put(2967, "O2Micro, Inc.");
IDS.put(3010, "Seagate Technology LLC");
IDS.put(3034, "Realtek Semiconductor Corp.");
IDS.put(3035, "Ericsson AB");
IDS.put(3044, "Elka International Ltd.");
IDS.put(3056, "Pace Micro Technology PLC");
IDS.put(3108, "Taiyo Yuden Co., Ltd.");
IDS.put(3129, "Aeroflex");
IDS.put(3132, "Radius Co., Ltd.");
IDS.put(3141, "Sonix Technology Co., Ltd.");
IDS.put(3158, "Billion Bright (HK) Corporation Limited");
IDS.put(3161, "Dong Guan Shinko Wire Co., Ltd.");
IDS.put(3170, "Chant Sincere Co., Ltd");
IDS.put(3190, "Solid State System Co., Ltd.");
IDS.put(3209, "Honda Tsushin Kogyo Co., Ltd");
IDS.put(3245, "Motorola Solutions");
IDS.put(3255, "Singatron Enterprise Co. Ltd.");
IDS.put(3268, "emsys Embedded Systems GmbH");
IDS.put(32902, "Intel Corporation");
IDS.put(3294, "Z-Com INC.");
IDS.put(3313, "e-CONN ELECTRONIC CO., LTD.");
IDS.put(3314, "ENE Technology Inc.");
IDS.put(3351, "NALTEC, Inc.");
IDS.put(3402, "NF Corporation");
IDS.put(3403, "Grape Systems Inc.");
IDS.put(3409, "Volex (Asia) Pte Ltd");
IDS.put(3425, "MEILU ELECTRONICS (SHENZHEN) CO., LTD.");
IDS.put(3441, "Hirakawa Hewtech Corp.");
IDS.put(3452, "Taiwan Line Tek Electronic Co., Ltd.");
IDS.put(3463, "Dolby Laboratories Inc.");
IDS.put(3468, "C-MEDIA ELECTRONICS INC.");
IDS.put(3472, "Sure-Fire Electrical Corporation");
IDS.put(3495, "IOGEAR, Inc.");
IDS.put(3504, "Micro-Star International Co., Ltd.");
IDS.put(3537, "Contek Electronics Co., Ltd.");
IDS.put(3540, "Custom Engineering SPA");
IDS.put(3641, "Smart Modular Technologies, Inc.");
IDS.put(3658, "Shenzhen Bao Hing Electric Wire & Cable Mfr. Co.");
IDS.put(3673, "Bourns, Inc.");
IDS.put(3690, "Megawin Technology Co., Ltd.");
IDS.put(3698, "Hsi-Chin Electronics Co., Ltd.");
IDS.put(3714, "Ching Tai Electric Wire & Cable Co., Ltd.");
IDS.put(3724, "Well Force Electronic Co., Ltd");
IDS.put(3725, "MediaTek Inc.");
IDS.put(3728, "CRU");
IDS.put(3744, "Ours Technology Inc.");
IDS.put(3762, "Y-S ELECTRONIC CO., LTD.");
IDS.put(3778, "Sweetray Industrial Ltd.");
IDS.put(3779, "Axell Corporation");
IDS.put(3782, "InnoVISION Multimedia Limited");
IDS.put(3790, "TaiSol Electronics Co., Ltd.");
IDS.put(3812, "Sunrich Technology (H.K.) Ltd.");
IDS.put(3868, "Funai Electric Co., Ltd.");
IDS.put(3873, "IOI Technology Corporation");
IDS.put(3890, "YFC-BonEagle Electric Co., Ltd.");
IDS.put(3896, "Nien-Yi Industrial Corp.");
IDS.put(3916, "WORLDWIDE CABLE OPTO CORP.");
IDS.put(3923, "Taiyo Cable (Dongguan) Co. Ltd.");
IDS.put(3924, "Kawai Musical Instruments Mfg. Co., Ltd.");
IDS.put(3936, "GuangZhou Chief Tech Electronic Technology Co. Ltd.");
IDS.put(3944, "UQUEST, LTD.");
IDS.put(3991, "CviLux Corporation");
IDS.put(4003, "Chief Land Electronic Co., Ltd.");
IDS.put(4046, "Sony Mobile Communications");
IDS.put(4087, "CHI SHING COMPUTER ACCESSORIES CO., LTD.");
IDS.put(4096, "Speed Tech Corp.");
IDS.put(4100, "LG Electronics Inc.");
IDS.put(4101, "Apacer Technology Inc.");
IDS.put(4134, "Newly Corporation");
IDS.put(4168, "Targus Group International");
IDS.put(4172, "AMCO TEC International Inc.");
IDS.put(4183, "ON Semiconductor");
IDS.put(4184, "Western Digital Technologies, Inc.");
IDS.put(4227, "CANON ELECTRONICS INC.");
IDS.put(4235, "Grand-tek Technology Co., Ltd.");
IDS.put(4236, "Robert Bosch GmbH");
IDS.put(4238, "Lotes Co., Ltd.");
IDS.put(4266, "Cables To Go");
IDS.put(4267, "Universal Global Scientific Industrial Co., Ltd.");
IDS.put(4292, "Silicon Laboratories, Inc.");
IDS.put(4301, "Kycon Inc.");
IDS.put(4362, "Moxa Inc.");
IDS.put(4370, "Golden Bright (Sichuan) Electronic Technology Co Ltd");
IDS.put(4382, "VSO ELECTRONICS CO., LTD.");
IDS.put(4398, "Master Hill Electric Wire and Cable Co., Ltd.");
IDS.put(4477, "Santa Electronic Inc.");
IDS.put(4505, "Sierra Wireless Inc.");
IDS.put(4522, "GlobalMedia Group, LLC");
IDS.put(4528, "ATECH FLASH TECHNOLOGY");
IDS.put(4643, "SKYCABLE ENTERPRISE CO., LTD.");
IDS.put(4703, "ADATA Technology Co., Ltd.");
IDS.put(4716, "Aristocrat Technologies");
IDS.put(4717, "Bel Stewart");
IDS.put(4742, "MARVELL SEMICONDUCTOR, INC.");
IDS.put(4756, "RISO KAGAKU CORP.");
IDS.put(4792, "Zhejiang Xinya Electronic Technology Co., Ltd.");
IDS.put(4817, "Huawei Technologies Co., Ltd.");
IDS.put(4823, "Better Holdings (HK) Limited");
IDS.put(4907, "Konica Minolta, Inc.");
IDS.put(4925, "Jasco Products Company");
IDS.put(4989, "Pericom Semiconductor Corp.");
IDS.put(5008, "TomTom International B.V.");
IDS.put(5075, "AzureWave Technologies, Inc.");
IDS.put(5117, "Initio Corporation");
IDS.put(5118, "Phison Electronics Corp.");
IDS.put(5134, "Telechips, Inc.");
IDS.put(5145, "ABILITY ENTERPRISE CO., LTD.");
IDS.put(5148, "Leviton Manufacturing");
IDS.put(5271, "Panstrong Company Ltd.");
IDS.put(5293, "CTK Corporation");
IDS.put(5296, "StarTech.com Ltd.");
IDS.put(5376, "Ellisys");
IDS.put(5404, "VeriSilicon Holdings Co., Ltd.");
IDS.put(5421, "JMicron Technology Corp.");
IDS.put(5422, "HLDS (Hitachi-LG Data Storage, Inc.)");
IDS.put(5440, "Phihong Technology Co., Ltd.");
IDS.put(5451, "PNY Technologies Inc.");
IDS.put(5453, "Rapid Conn, Connect County Holdings Bhd");
IDS.put(5454, "D & M Holdings, Inc.");
IDS.put(5480, "Sunf Pu Technology Co., Ltd");
IDS.put(5488, "ALLTOP TECHNOLOGY CO., LTD.");
IDS.put(5510, "Palconn Technology Co., Ltd.");
IDS.put(5528, "Kunshan Guoji Electronics Co., Ltd.");
IDS.put(5546, "DongGuan Ya Lian Electronics Co., Ltd.");
IDS.put(5645, "Samtec");
IDS.put(5694, "HongLin Electronics Co., Ltd.");
IDS.put(5753, "Total Phase");
IDS.put(5766, "ZOOM Corporation");
IDS.put(5836, "silex technology, Inc.");
IDS.put(5946, "F. Hoffmann-La Roche AG");
IDS.put(5960, "MQP Electronics Ltd.");
IDS.put(5964, "ASMedia Technology Inc.");
IDS.put(5998, "UD electronic corp.");
IDS.put(6001, "Shenzhen Alex Connector Co., Ltd.");
IDS.put(6002, "System Level Solutions, Inc.");
IDS.put(6018, "Spreadtrum Hong Kong Limited");
IDS.put(6024, "ShenZhen Litkconn Technology Co., Ltd.");
IDS.put(6053, "Advanced Connection Technology Inc.");
IDS.put(6095, "Hip Hing Cable & Plug Mfy. Ltd.");
IDS.put(6121, "DisplayLink (UK) Ltd.");
IDS.put(6127, "Lenovo");
IDS.put(6133, "K.K. Rocky");
IDS.put(6160, "Wanshih Electronic Co., Ltd.");
IDS.put(6185, "Dongguan YuQiu Electronics Co., Ltd.");
IDS.put(6193, "Gwo Jinn Industries Co., Ltd.");
IDS.put(6297, "Linkiss Co., Ltd.");
IDS.put(6353, "Google Inc.");
IDS.put(6394, "Kuang Ying Computer Equipment Co., Ltd.");
IDS.put(6421, "Nordic Semiconductor ASA");
IDS.put(6448, "Shenzhen Xianhe Technology Co., Ltd.");
IDS.put(6449, "Ningbo Broad Telecommunication Co., Ltd.");
IDS.put(6470, "Irisguard UK Ltd");
IDS.put(6473, "Lab126");
IDS.put(6481, "Hyperstone GmbH");
IDS.put(6487, "BIOS Corporation");
IDS.put(6626, "Solomon Systech Limited");
IDS.put(6639, "Pak Heng Technology (Shenzhen) Co., Ltd.");
IDS.put(6655, "Best Buy China Ltd.");
IDS.put(6666, "USB-IF non-workshop");
IDS.put(6709, "Artesyn Technologies Inc.");
IDS.put(6720, "TERMINUS TECHNOLOGY INC.");
IDS.put(6766, "Global Unichip Corp.");
IDS.put(6786, "Proconn Technology Co., Ltd.");
IDS.put(6794, "Simula Technology Inc.");
IDS.put(6795, "SGS Taiwan Ltd.");
IDS.put(6830, "Johnson Component & Equipments Co., Ltd.");
IDS.put(6834, "Allied Vision Technologies GmbH");
IDS.put(6859, "Salcomp Plc");
IDS.put(6865, "Desan Wire Co., Ltd.");
IDS.put(6944, "MStar Semiconductor, Inc.");
IDS.put(6984, "Plastron Precision Co., Ltd.");
IDS.put(7013, "The Hong Kong Standards and Testing Centre Ltd.");
IDS.put(7048, "ShenMing Electron (Dong Guan) Co., Ltd.");
IDS.put(7086, "Vuzix Corporation");
IDS.put(7108, "Ford Motor Co.");
IDS.put(7118, "Contac Cable Industrial Limited");
IDS.put(7119, "Sunplus Innovation Technology Inc.");
IDS.put(7120, "Hangzhou Riyue Electronics Co., Ltd.");
IDS.put(7158, "Orient Semiconductor Electronics, Ltd.");
IDS.put(7207, "SHENZHEN DNS INDUSTRIES CO., LTD.");
IDS.put(7217, "LS Mtron Ltd.");
IDS.put(7229, "NONIN MEDICAL INC.");
IDS.put(7275, "Philips & Lite-ON Digital Solutions Corporation");
IDS.put(7310, "ASTRON INTERNATIONAL CORP.");
IDS.put(7320, "ALPINE ELECTRONICS, INC.");
IDS.put(7347, "Aces Electronics Co., Ltd.");
IDS.put(7348, "OPEX CORPORATION");
IDS.put(7390, "Telecommunications Technology Association (TTA)");
IDS.put(7434, "Visteon Corporation");
IDS.put(7465, "Horng Tong Enterprise Co., Ltd.");
IDS.put(7501, "Pegatron Corporation");
IDS.put(7516, "Fresco Logic Inc.");
IDS.put(7529, "Walta Electronic Co., Ltd.");
IDS.put(7543, "Yueqing Changling Electronic Instrument Corp., Ltd.");
IDS.put(7584, "Parade Technologies, Inc.");
IDS.put(7647, "L&T Technology Services");
IDS.put(7649, "Actions Microelectronics Co., Ltd.");
IDS.put(7666, "China Telecommunication Technology Labs - Terminals");
IDS.put(7668, "SHEN ZHEN FORMAN PRECISION INDUSTRY CO., LTD.");
IDS.put(7682, "GLOBEMASTER TECHNOLOGIES CO., LTD.");
IDS.put(7696, "Point Grey Research Inc.");
IDS.put(7751, "HUNG TA H.T.ENTERPRISE CO., LTD.");
IDS.put(7758, "Etron Technology, Inc.");
IDS.put(7795, "COMLINK ELECTRONICS CO., LTD.");
IDS.put(7818, "HIBEST Electronic (DongGuan) Co., Ltd.");
IDS.put(7825, "Other World Computing");
IDS.put(7863, "WIN WIN PRECISION INDUSTRIAL CO., LTD.");
IDS.put(7879, "Gefen Inc.");
IDS.put(7881, "MOSER BAER INDIA LIMITED");
IDS.put(7898, "AIRTIES WIRELESS NETWORKS");
IDS.put(7956, "Astoria Networks GmbH");
IDS.put(7969, "Scosche Industries");
IDS.put(7976, "Cal-Comp Electronics & Communications");
IDS.put(7977, "Analogix Semiconductor, Inc.");
IDS.put(7989, "Amphenol ShouhMin Industry (ShenZhen) Co., Ltd");
IDS.put(7996, "Chang Yang Electronics Company Ltd.");
IDS.put(8073, "Dongguan Goldconn Electronics Co., Ltd.");
IDS.put(8074, "Morning Star Industrial Co., Ltd.");
IDS.put(8117, "Unify Software and Solutions GmbH & Co. KG");
IDS.put(8137, "NXP Semiconductors");
IDS.put(8181, "Changzhou Wujin BEST Electronic Cables Co., Ltd.");
IDS.put(8205, "Belkin Electronic (Changzhou) Co., Ltd.");
IDS.put(8220, "Freeport Resources Enterprises Corp.");
IDS.put(8222, "Qingdao Haier Telecom Co., Ltd.");
IDS.put(8284, "Shenzhen Tronixin Electronics Co., Ltd.");
IDS.put(8294, "Unicorn Electronics Components Co., Ltd.");
IDS.put(8334, "Luxshare-ICT");
IDS.put(8341, "CE LINK LIMITED");
IDS.put(8342, "Microconn Electronic Co., Ltd.");
IDS.put(8367, "Shenzhen CARVE Electronics Co., Ltd.");
IDS.put(8382, "BURY GmbH & Co. KG");
IDS.put(8384, "FENGHUA KINGSUN CO., LTD.");
IDS.put(8386, "Sumitomo Electric Ind., Ltd., Optical Comm. R&D Lab");
IDS.put(8439, "XIMEA s.r.o.");
IDS.put(8457, "VIA Labs, Inc.");
IDS.put(8492, "Shenzhen Linoya Electronic Co., Ltd.");
IDS.put(8494, "Amphenol AssembleTech (Xiamen) Co., Ltd.");
IDS.put(8524, "Y Soft Corporation");
IDS.put(8550, "JVC KENWOOD Corporation");
IDS.put(8564, "Transcend Information, Inc.");
IDS.put(8566, "TMC/Allion Test Labs");
IDS.put(8613, "Genesis Technology USA, Inc.");
IDS.put(8627, "Dongguan Teconn Electronics Technology Co., Ltd.");
IDS.put(8644, "Netcom Technology (HK) Limited");
IDS.put(8659, "Compupack Technology Co., Ltd.");
IDS.put(8667, "G-Max Technology Co., Ltd.");
IDS.put(8679, "Sagemcom Broadband SAS");
IDS.put(8695, "Wuerth-Elektronik eiSos GmbH & Co. KG");
IDS.put(8707, "Shin Shin Co., Ltd.");
IDS.put(8709, "3eYamaichi Electronics Co., Ltd.");
IDS.put(8710, "Wiretek International Investment Ltd.");
IDS.put(8711, "Fuzhou Rockchip Electronics Co., Ltd.");
IDS.put(8752, "Plugable Technologies");
IDS.put(8756, "T-CONN PRECISION CORPORATION");
IDS.put(8831, "Granite River Labs");
IDS.put(8842, "Hotron Precision Electronic Ind. Corp.");
IDS.put(8875, "Trigence Semiconductor, Inc.");
IDS.put(8888, "Motorola Mobility Inc.");
IDS.put(8904, "Karming Electronic (Shenzhen) Co., Ltd.");
IDS.put(8981, "Avery Design Systems, Inc.");
IDS.put(8993, "iKingdom Corp. (d.b.a. iConnectivity)");
IDS.put(9051, "KangXiang Electronic Co., Ltd.");
IDS.put(9068, "ZheJiang Chunsheng Electronics Co., Ltd.");
IDS.put(9130, "DOK (HK) Trading Limited");
IDS.put(9132, "Marunix Electron Limited");
IDS.put(9165, "Avconn Precise Connector Co., Ltd.");
IDS.put(9184, "BitifEye Digital Test Solutions GmbH");
IDS.put(9205, "Speed Conn Co., Ltd.");
IDS.put(9222, "INSIDE Secure");
IDS.put(9292, "Minebea Co., Ltd.");
IDS.put(9299, "BAANTO");
IDS.put(9338, "Suzhou Jutze Technologies Co., Ltd");
IDS.put(9355, "DONGGUAN SYNCONN PRECISION INDUSTRY CO. LTD.");
IDS.put(9382, "Shenzhen Pangngai Industrial Co., Ltd.");
IDS.put(9422, "Shenzhen Deren Electronic Co., Ltd.");
IDS.put(9424, "Smith Micro Software, Inc.");
IDS.put(9453, "ZEN FACTORY GROUP (ASIA) LTD.");
IDS.put(9481, "Chain-In Electronic Co., Ltd.");
IDS.put(9514, "SUZHOU KELI TECHNOLOGY DEVELOPMENT CO., LTD.");
IDS.put(9515, "TOP Exactitude Industry (ShenZhen) Co., Ltd.");
IDS.put(9525, "ShenZhen Hogend Precision Technology Co., Ltd.");
IDS.put(9527, "Norel Systems Ltd.");
IDS.put(9556, "ASSA ABLOY AB");
IDS.put(9575, "DongGuan LongTao Electronic Co., Ltd.");
IDS.put(9577, "DongGuan City MingJi Electronics Co., Ltd.");
IDS.put(9589, "Weida Hi-Tech Co., Ltd.");
IDS.put(9593, "Dongguan Wisechamp Electronic Co., Ltd.");
IDS.put(9613, "Sequans Communications");
IDS.put(9636, "ALGOLTEK, INC.");
IDS.put(9651, "DongGuan Elinke Industrial Co., Ltd.");
IDS.put(9679, "Corning Optical Communications LLC");
IDS.put(9714, "Dongguan Jinyue Electronics Co., Ltd.");
IDS.put(9723, "RICOH IMAGING COMPANY, LTD.");
IDS.put(9742, "DongGuan HYX Industrial Co., Ltd.");
IDS.put(9753, "Advanced Silicon SA");
IDS.put(9756, "EISST Limited");
IDS.put(9771, "YTOP Electronics Technical (Kunshan) Co., Ltd.");
IDS.put(9841, "Innovative Logic");
IDS.put(9842, "GoPro");
IDS.put(9846, "Basler AG");
IDS.put(9851, "Palpilot International Corp.");
IDS.put(9896, "UNIREX CORPORATION");
IDS.put(9917, "Integral Memory Plc.");
IDS.put(9973, "Morning Star Digital Connector Co., Ltd.");
IDS.put(9984, "MITACHI CO., LTD.");
IDS.put(9999, "HGST, a Western Digital Company");
}
}
|
0
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/libuvccamera/2018.10.2/com/serenegiant/usb/UVCCamera.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usb;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.serenegiant.usb.USBMonitor.UsbControlBlock;
public class UVCCamera {
private static final boolean DEBUG = false; // TODO set false when releasing
private static final String TAG = UVCCamera.class.getSimpleName();
private static final String DEFAULT_USBFS = "/dev/bus/usb";
public static final int DEFAULT_PREVIEW_WIDTH = 640;
public static final int DEFAULT_PREVIEW_HEIGHT = 480;
public static final int DEFAULT_PREVIEW_MODE = 0;
public static final int DEFAULT_PREVIEW_MIN_FPS = 1;
public static final int DEFAULT_PREVIEW_MAX_FPS = 30;
public static final float DEFAULT_BANDWIDTH = 1.0f;
public static final int FRAME_FORMAT_YUYV = 0;
public static final int FRAME_FORMAT_MJPEG = 1;
public static final int PIXEL_FORMAT_RAW = 0;
public static final int PIXEL_FORMAT_YUV = 1;
public static final int PIXEL_FORMAT_RGB565 = 2;
public static final int PIXEL_FORMAT_RGBX = 3;
public static final int PIXEL_FORMAT_YUV420SP = 4;
public static final int PIXEL_FORMAT_NV21 = 5; // = YVU420SemiPlanar
//--------------------------------------------------------------------------------
public static final int CTRL_SCANNING = 0x00000001; // D0: Scanning Mode
public static final int CTRL_AE = 0x00000002; // D1: Auto-Exposure Mode
public static final int CTRL_AE_PRIORITY = 0x00000004; // D2: Auto-Exposure Priority
public static final int CTRL_AE_ABS = 0x00000008; // D3: Exposure Time (Absolute)
public static final int CTRL_AR_REL = 0x00000010; // D4: Exposure Time (Relative)
public static final int CTRL_FOCUS_ABS = 0x00000020; // D5: Focus (Absolute)
public static final int CTRL_FOCUS_REL = 0x00000040; // D6: Focus (Relative)
public static final int CTRL_IRIS_ABS = 0x00000080; // D7: Iris (Absolute)
public static final int CTRL_IRIS_REL = 0x00000100; // D8: Iris (Relative)
public static final int CTRL_ZOOM_ABS = 0x00000200; // D9: Zoom (Absolute)
public static final int CTRL_ZOOM_REL = 0x00000400; // D10: Zoom (Relative)
public static final int CTRL_PANTILT_ABS = 0x00000800; // D11: PanTilt (Absolute)
public static final int CTRL_PANTILT_REL = 0x00001000; // D12: PanTilt (Relative)
public static final int CTRL_ROLL_ABS = 0x00002000; // D13: Roll (Absolute)
public static final int CTRL_ROLL_REL = 0x00004000; // D14: Roll (Relative)
public static final int CTRL_FOCUS_AUTO = 0x00020000; // D17: Focus, Auto
public static final int CTRL_PRIVACY = 0x00040000; // D18: Privacy
public static final int CTRL_FOCUS_SIMPLE = 0x00080000; // D19: Focus, Simple
public static final int CTRL_WINDOW = 0x00100000; // D20: Window
public static final int PU_BRIGHTNESS = 0x80000001; // D0: Brightness
public static final int PU_CONTRAST = 0x80000002; // D1: Contrast
public static final int PU_HUE = 0x80000004; // D2: Hue
public static final int PU_SATURATION = 0x80000008; // D3: Saturation
public static final int PU_SHARPNESS = 0x80000010; // D4: Sharpness
public static final int PU_GAMMA = 0x80000020; // D5: Gamma
public static final int PU_WB_TEMP = 0x80000040; // D6: White Balance Temperature
public static final int PU_WB_COMPO = 0x80000080; // D7: White Balance Component
public static final int PU_BACKLIGHT = 0x80000100; // D8: Backlight Compensation
public static final int PU_GAIN = 0x80000200; // D9: Gain
public static final int PU_POWER_LF = 0x80000400; // D10: Power Line Frequency
public static final int PU_HUE_AUTO = 0x80000800; // D11: Hue, Auto
public static final int PU_WB_TEMP_AUTO = 0x80001000; // D12: White Balance Temperature, Auto
public static final int PU_WB_COMPO_AUTO = 0x80002000; // D13: White Balance Component, Auto
public static final int PU_DIGITAL_MULT = 0x80004000; // D14: Digital Multiplier
public static final int PU_DIGITAL_LIMIT = 0x80008000; // D15: Digital Multiplier Limit
public static final int PU_AVIDEO_STD = 0x80010000; // D16: Analog Video Standard
public static final int PU_AVIDEO_LOCK = 0x80020000; // D17: Analog Video Lock Status
public static final int PU_CONTRAST_AUTO = 0x80040000; // D18: Contrast, Auto
// uvc_status_class from libuvc.h
public static final int STATUS_CLASS_CONTROL = 0x10;
public static final int STATUS_CLASS_CONTROL_CAMERA = 0x11;
public static final int STATUS_CLASS_CONTROL_PROCESSING = 0x12;
// uvc_status_attribute from libuvc.h
public static final int STATUS_ATTRIBUTE_VALUE_CHANGE = 0x00;
public static final int STATUS_ATTRIBUTE_INFO_CHANGE = 0x01;
public static final int STATUS_ATTRIBUTE_FAILURE_CHANGE = 0x02;
public static final int STATUS_ATTRIBUTE_UNKNOWN = 0xff;
private static boolean isLoaded;
static {
if (!isLoaded) {
System.loadLibrary("jpeg-turbo1500");
System.loadLibrary("usb100");
System.loadLibrary("uvc");
System.loadLibrary("UVCCamera");
isLoaded = true;
}
}
private UsbControlBlock mCtrlBlock;
protected long mControlSupports; // カメラコントロールでサポートしている機能フラグ
protected long mProcSupports; // プロセッシングユニットでサポートしている機能フラグ
protected int mCurrentFrameFormat = FRAME_FORMAT_MJPEG;
protected int mCurrentWidth = DEFAULT_PREVIEW_WIDTH, mCurrentHeight = DEFAULT_PREVIEW_HEIGHT;
protected float mCurrentBandwidthFactor = DEFAULT_BANDWIDTH;
protected String mSupportedSize;
protected List<Size> mCurrentSizeList;
// these fields from here are accessed from native code and do not change name and remove
protected long mNativePtr;
protected int mScanningModeMin, mScanningModeMax, mScanningModeDef;
protected int mExposureModeMin, mExposureModeMax, mExposureModeDef;
protected int mExposurePriorityMin, mExposurePriorityMax, mExposurePriorityDef;
protected int mExposureMin, mExposureMax, mExposureDef;
protected int mAutoFocusMin, mAutoFocusMax, mAutoFocusDef;
protected int mFocusMin, mFocusMax, mFocusDef;
protected int mFocusRelMin, mFocusRelMax, mFocusRelDef;
protected int mFocusSimpleMin, mFocusSimpleMax, mFocusSimpleDef;
protected int mIrisMin, mIrisMax, mIrisDef;
protected int mIrisRelMin, mIrisRelMax, mIrisRelDef;
protected int mPanMin, mPanMax, mPanDef;
protected int mTiltMin, mTiltMax, mTiltDef;
protected int mRollMin, mRollMax, mRollDef;
protected int mPanRelMin, mPanRelMax, mPanRelDef;
protected int mTiltRelMin, mTiltRelMax, mTiltRelDef;
protected int mRollRelMin, mRollRelMax, mRollRelDef;
protected int mPrivacyMin, mPrivacyMax, mPrivacyDef;
protected int mAutoWhiteBlanceMin, mAutoWhiteBlanceMax, mAutoWhiteBlanceDef;
protected int mAutoWhiteBlanceCompoMin, mAutoWhiteBlanceCompoMax, mAutoWhiteBlanceCompoDef;
protected int mWhiteBlanceMin, mWhiteBlanceMax, mWhiteBlanceDef;
protected int mWhiteBlanceCompoMin, mWhiteBlanceCompoMax, mWhiteBlanceCompoDef;
protected int mWhiteBlanceRelMin, mWhiteBlanceRelMax, mWhiteBlanceRelDef;
protected int mBacklightCompMin, mBacklightCompMax, mBacklightCompDef;
protected int mBrightnessMin, mBrightnessMax, mBrightnessDef;
protected int mContrastMin, mContrastMax, mContrastDef;
protected int mSharpnessMin, mSharpnessMax, mSharpnessDef;
protected int mGainMin, mGainMax, mGainDef;
protected int mGammaMin, mGammaMax, mGammaDef;
protected int mSaturationMin, mSaturationMax, mSaturationDef;
protected int mHueMin, mHueMax, mHueDef;
protected int mZoomMin, mZoomMax, mZoomDef;
protected int mZoomRelMin, mZoomRelMax, mZoomRelDef;
protected int mPowerlineFrequencyMin, mPowerlineFrequencyMax, mPowerlineFrequencyDef;
protected int mMultiplierMin, mMultiplierMax, mMultiplierDef;
protected int mMultiplierLimitMin, mMultiplierLimitMax, mMultiplierLimitDef;
protected int mAnalogVideoStandardMin, mAnalogVideoStandardMax, mAnalogVideoStandardDef;
protected int mAnalogVideoLockStateMin, mAnalogVideoLockStateMax, mAnalogVideoLockStateDef;
// until here
/**
* the sonctructor of this class should be call within the thread that has a looper
* (UI thread or a thread that called Looper.prepare)
*/
public UVCCamera() {
mNativePtr = nativeCreate();
mSupportedSize = null;
}
/**
* connect to a UVC camera
* USB permission is necessary before this method is called
* @param ctrlBlock
*/
public synchronized void open(final UsbControlBlock ctrlBlock) {
int result;
try {
mCtrlBlock = ctrlBlock.clone();
result = nativeConnect(mNativePtr,
mCtrlBlock.getVenderId(), mCtrlBlock.getProductId(),
mCtrlBlock.getFileDescriptor(),
mCtrlBlock.getBusNum(),
mCtrlBlock.getDevNum(),
getUSBFSName(mCtrlBlock));
} catch (final Exception e) {
Log.w(TAG, e);
result = -1;
}
if (result != 0) {
throw new UnsupportedOperationException("open failed:result=" + result);
}
if (mNativePtr != 0 && TextUtils.isEmpty(mSupportedSize)) {
mSupportedSize = nativeGetSupportedSize(mNativePtr);
}
nativeSetPreviewSize(mNativePtr, DEFAULT_PREVIEW_WIDTH, DEFAULT_PREVIEW_HEIGHT,
DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, DEFAULT_PREVIEW_MODE, DEFAULT_BANDWIDTH);
}
/**
* set status callback
* @param callback
*/
public void setStatusCallback(final IStatusCallback callback) {
if (mNativePtr != 0) {
nativeSetStatusCallback(mNativePtr, callback);
}
}
/**
* set button callback
* @param callback
*/
public void setButtonCallback(final IButtonCallback callback) {
if (mNativePtr != 0) {
nativeSetButtonCallback(mNativePtr, callback);
}
}
/**
* close and release UVC camera
*/
public synchronized void close() {
stopPreview();
if (mNativePtr != 0) {
nativeRelease(mNativePtr);
// mNativePtr = 0; // nativeDestroyを呼ぶのでここでクリアしちゃダメ
}
if (mCtrlBlock != null) {
mCtrlBlock.close();
mCtrlBlock = null;
}
mControlSupports = mProcSupports = 0;
mCurrentFrameFormat = -1;
mCurrentBandwidthFactor = 0;
mSupportedSize = null;
mCurrentSizeList = null;
if (DEBUG) Log.v(TAG, "close:finished");
}
public UsbDevice getDevice() {
return mCtrlBlock != null ? mCtrlBlock.getDevice() : null;
}
public String getDeviceName(){
return mCtrlBlock != null ? mCtrlBlock.getDeviceName() : null;
}
public UsbControlBlock getUsbControlBlock() {
return mCtrlBlock;
}
public synchronized String getSupportedSize() {
return !TextUtils.isEmpty(mSupportedSize) ? mSupportedSize : (mSupportedSize = nativeGetSupportedSize(mNativePtr));
}
public Size getPreviewSize() {
Size result = null;
final List<Size> list = getSupportedSizeList();
for (final Size sz: list) {
if ((sz.width == mCurrentWidth)
|| (sz.height == mCurrentHeight)) {
result =sz;
break;
}
}
return result;
}
/**
* Set preview size and preview mode
* @param width
@param height
*/
public void setPreviewSize(final int width, final int height) {
setPreviewSize(width, height, DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, mCurrentFrameFormat, mCurrentBandwidthFactor);
}
/**
* Set preview size and preview mode
* @param width
* @param height
* @param frameFormat either FRAME_FORMAT_YUYV(0) or FRAME_FORMAT_MJPEG(1)
*/
public void setPreviewSize(final int width, final int height, final int frameFormat) {
setPreviewSize(width, height, DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, frameFormat, mCurrentBandwidthFactor);
}
/**
* Set preview size and preview mode
* @param width
@param height
@param frameFormat either FRAME_FORMAT_YUYV(0) or FRAME_FORMAT_MJPEG(1)
@param bandwidth [0.0f,1.0f]
*/
public void setPreviewSize(final int width, final int height, final int frameFormat, final float bandwidth) {
setPreviewSize(width, height, DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, frameFormat, bandwidth);
}
/**
* Set preview size and preview mode
* @param width
* @param height
* @param min_fps
* @param max_fps
* @param frameFormat either FRAME_FORMAT_YUYV(0) or FRAME_FORMAT_MJPEG(1)
* @param bandwidthFactor
*/
public void setPreviewSize(final int width, final int height, final int min_fps, final int max_fps, final int frameFormat, final float bandwidthFactor) {
if ((width == 0) || (height == 0))
throw new IllegalArgumentException("invalid preview size");
if (mNativePtr != 0) {
final int result = nativeSetPreviewSize(mNativePtr, width, height, min_fps, max_fps, frameFormat, bandwidthFactor);
if (result != 0)
throw new IllegalArgumentException("Failed to set preview size");
mCurrentFrameFormat = frameFormat;
mCurrentWidth = width;
mCurrentHeight = height;
mCurrentBandwidthFactor = bandwidthFactor;
}
}
public List<Size> getSupportedSizeList() {
final int type = (mCurrentFrameFormat > 0) ? 6 : 4;
return getSupportedSize(type, mSupportedSize);
}
public static List<Size> getSupportedSize(final int type, final String supportedSize) {
final List<Size> result = new ArrayList<Size>();
if (!TextUtils.isEmpty(supportedSize))
try {
final JSONObject json = new JSONObject(supportedSize);
final JSONArray formats = json.getJSONArray("formats");
final int format_nums = formats.length();
for (int i = 0; i < format_nums; i++) {
final JSONObject format = formats.getJSONObject(i);
if(format.has("type") && format.has("size")) {
final int format_type = format.getInt("type");
if ((format_type == type) || (type == -1)) {
addSize(format, format_type, 0, result);
}
}
}
} catch (final JSONException e) {
e.printStackTrace();
}
return result;
}
private static final void addSize(final JSONObject format, final int formatType, final int frameType, final List<Size> size_list) throws JSONException {
final JSONArray size = format.getJSONArray("size");
final int size_nums = size.length();
for (int j = 0; j < size_nums; j++) {
final String[] sz = size.getString(j).split("x");
try {
size_list.add(new Size(formatType, frameType, j, Integer.parseInt(sz[0]), Integer.parseInt(sz[1])));
} catch (final Exception e) {
break;
}
}
}
/**
* set preview surface with SurfaceHolder</br>
* you can use SurfaceHolder came from SurfaceView/GLSurfaceView
* @param holder
*/
public synchronized void setPreviewDisplay(final SurfaceHolder holder) {
nativeSetPreviewDisplay(mNativePtr, holder.getSurface());
}
/**
* set preview surface with SurfaceTexture.
* this method require API >= 14
* @param texture
*/
public synchronized void setPreviewTexture(final SurfaceTexture texture) { // API >= 11
final Surface surface = new Surface(texture); // XXX API >= 14
nativeSetPreviewDisplay(mNativePtr, surface);
}
/**
* set preview surface with Surface
* @param surface
*/
public synchronized void setPreviewDisplay(final Surface surface) {
nativeSetPreviewDisplay(mNativePtr, surface);
}
/**
* set frame callback
* @param callback
* @param pixelFormat
*/
public void setFrameCallback(final IFrameCallback callback, final int pixelFormat) {
if (mNativePtr != 0) {
nativeSetFrameCallback(mNativePtr, callback, pixelFormat);
}
}
/**
* start preview
*/
public synchronized void startPreview() {
if (mCtrlBlock != null) {
nativeStartPreview(mNativePtr);
}
}
/**
* stop preview
*/
public synchronized void stopPreview() {
setFrameCallback(null, 0);
if (mCtrlBlock != null) {
nativeStopPreview(mNativePtr);
}
}
/**
* destroy UVCCamera object
*/
public synchronized void destroy() {
close();
if (mNativePtr != 0) {
nativeDestroy(mNativePtr);
mNativePtr = 0;
}
}
// wrong result may return when you call this just after camera open.
// it is better to wait several hundreads millseconds.
public boolean checkSupportFlag(final long flag) {
updateCameraParams();
if ((flag & 0x80000000) == 0x80000000)
return ((mProcSupports & flag) == (flag & 0x7ffffffF));
else
return (mControlSupports & flag) == flag;
}
//================================================================================
public synchronized void setAutoFocus(final boolean autoFocus) {
if (mNativePtr != 0) {
nativeSetAutoFocus(mNativePtr, autoFocus);
}
}
public synchronized boolean getAutoFocus() {
boolean result = true;
if (mNativePtr != 0) {
result = nativeGetAutoFocus(mNativePtr) > 0;
}
return result;
}
//================================================================================
/**
* @param focus [%]
*/
public synchronized void setFocus(final int focus) {
if (mNativePtr != 0) {
final float range = Math.abs(mFocusMax - mFocusMin);
if (range > 0)
nativeSetFocus(mNativePtr, (int)(focus / 100.f * range) + mFocusMin);
}
}
/**
* @param focus_abs
* @return focus[%]
*/
public synchronized int getFocus(final int focus_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateFocusLimit(mNativePtr);
final float range = Math.abs(mFocusMax - mFocusMin);
if (range > 0) {
result = (int)((focus_abs - mFocusMin) * 100.f / range);
}
}
return result;
}
/**
* @return focus[%]
*/
public synchronized int getFocus() {
return getFocus(nativeGetFocus(mNativePtr));
}
public synchronized void resetFocus() {
if (mNativePtr != 0) {
nativeSetFocus(mNativePtr, mFocusDef);
}
}
//================================================================================
public synchronized void setAutoWhiteBlance(final boolean autoWhiteBlance) {
if (mNativePtr != 0) {
nativeSetAutoWhiteBlance(mNativePtr, autoWhiteBlance);
}
}
public synchronized boolean getAutoWhiteBlance() {
boolean result = true;
if (mNativePtr != 0) {
result = nativeGetAutoWhiteBlance(mNativePtr) > 0;
}
return result;
}
//================================================================================
/**
* @param whiteBlance [%]
*/
public synchronized void setWhiteBlance(final int whiteBlance) {
if (mNativePtr != 0) {
final float range = Math.abs(mWhiteBlanceMax - mWhiteBlanceMin);
if (range > 0)
nativeSetWhiteBlance(mNativePtr, (int)(whiteBlance / 100.f * range) + mWhiteBlanceMin);
}
}
/**
* @param whiteBlance_abs
* @return whiteBlance[%]
*/
public synchronized int getWhiteBlance(final int whiteBlance_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateWhiteBlanceLimit(mNativePtr);
final float range = Math.abs(mWhiteBlanceMax - mWhiteBlanceMin);
if (range > 0) {
result = (int)((whiteBlance_abs - mWhiteBlanceMin) * 100.f / range);
}
}
return result;
}
/**
* @return white blance[%]
*/
public synchronized int getWhiteBlance() {
return getFocus(nativeGetWhiteBlance(mNativePtr));
}
public synchronized void resetWhiteBlance() {
if (mNativePtr != 0) {
nativeSetWhiteBlance(mNativePtr, mWhiteBlanceDef);
}
}
//================================================================================
/**
* @param brightness [%]
*/
public synchronized void setBrightness(final int brightness) {
if (mNativePtr != 0) {
final float range = Math.abs(mBrightnessMax - mBrightnessMin);
if (range > 0)
nativeSetBrightness(mNativePtr, (int)(brightness / 100.f * range) + mBrightnessMin);
}
}
/**
* @param brightness_abs
* @return brightness[%]
*/
public synchronized int getBrightness(final int brightness_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateBrightnessLimit(mNativePtr);
final float range = Math.abs(mBrightnessMax - mBrightnessMin);
if (range > 0) {
result = (int)((brightness_abs - mBrightnessMin) * 100.f / range);
}
}
return result;
}
/**
* @return brightness[%]
*/
public synchronized int getBrightness() {
return getBrightness(nativeGetBrightness(mNativePtr));
}
public synchronized void resetBrightness() {
if (mNativePtr != 0) {
nativeSetBrightness(mNativePtr, mBrightnessDef);
}
}
//================================================================================
/**
* @param contrast [%]
*/
public synchronized void setContrast(final int contrast) {
if (mNativePtr != 0) {
nativeUpdateContrastLimit(mNativePtr);
final float range = Math.abs(mContrastMax - mContrastMin);
if (range > 0)
nativeSetContrast(mNativePtr, (int)(contrast / 100.f * range) + mContrastMin);
}
}
/**
* @param contrast_abs
* @return contrast[%]
*/
public synchronized int getContrast(final int contrast_abs) {
int result = 0;
if (mNativePtr != 0) {
final float range = Math.abs(mContrastMax - mContrastMin);
if (range > 0) {
result = (int)((contrast_abs - mContrastMin) * 100.f / range);
}
}
return result;
}
/**
* @return contrast[%]
*/
public synchronized int getContrast() {
return getContrast(nativeGetContrast(mNativePtr));
}
public synchronized void resetContrast() {
if (mNativePtr != 0) {
nativeSetContrast(mNativePtr, mContrastDef);
}
}
//================================================================================
/**
* @param sharpness [%]
*/
public synchronized void setSharpness(final int sharpness) {
if (mNativePtr != 0) {
final float range = Math.abs(mSharpnessMax - mSharpnessMin);
if (range > 0)
nativeSetSharpness(mNativePtr, (int)(sharpness / 100.f * range) + mSharpnessMin);
}
}
/**
* @param sharpness_abs
* @return sharpness[%]
*/
public synchronized int getSharpness(final int sharpness_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateSharpnessLimit(mNativePtr);
final float range = Math.abs(mSharpnessMax - mSharpnessMin);
if (range > 0) {
result = (int)((sharpness_abs - mSharpnessMin) * 100.f / range);
}
}
return result;
}
/**
* @return sharpness[%]
*/
public synchronized int getSharpness() {
return getSharpness(nativeGetSharpness(mNativePtr));
}
public synchronized void resetSharpness() {
if (mNativePtr != 0) {
nativeSetSharpness(mNativePtr, mSharpnessDef);
}
}
//================================================================================
/**
* @param gain [%]
*/
public synchronized void setGain(final int gain) {
if (mNativePtr != 0) {
final float range = Math.abs(mGainMax - mGainMin);
if (range > 0)
nativeSetGain(mNativePtr, (int)(gain / 100.f * range) + mGainMin);
}
}
/**
* @param gain_abs
* @return gain[%]
*/
public synchronized int getGain(final int gain_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateGainLimit(mNativePtr);
final float range = Math.abs(mGainMax - mGainMin);
if (range > 0) {
result = (int)((gain_abs - mGainMin) * 100.f / range);
}
}
return result;
}
/**
* @return gain[%]
*/
public synchronized int getGain() {
return getGain(nativeGetGain(mNativePtr));
}
public synchronized void resetGain() {
if (mNativePtr != 0) {
nativeSetGain(mNativePtr, mGainDef);
}
}
//================================================================================
/**
* @param gamma [%]
*/
public synchronized void setGamma(final int gamma) {
if (mNativePtr != 0) {
final float range = Math.abs(mGammaMax - mGammaMin);
if (range > 0)
nativeSetGamma(mNativePtr, (int)(gamma / 100.f * range) + mGammaMin);
}
}
/**
* @param gamma_abs
* @return gamma[%]
*/
public synchronized int getGamma(final int gamma_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateGammaLimit(mNativePtr);
final float range = Math.abs(mGammaMax - mGammaMin);
if (range > 0) {
result = (int)((gamma_abs - mGammaMin) * 100.f / range);
}
}
return result;
}
/**
* @return gamma[%]
*/
public synchronized int getGamma() {
return getGamma(nativeGetGamma(mNativePtr));
}
public synchronized void resetGamma() {
if (mNativePtr != 0) {
nativeSetGamma(mNativePtr, mGammaDef);
}
}
//================================================================================
/**
* @param saturation [%]
*/
public synchronized void setSaturation(final int saturation) {
if (mNativePtr != 0) {
final float range = Math.abs(mSaturationMax - mSaturationMin);
if (range > 0)
nativeSetSaturation(mNativePtr, (int)(saturation / 100.f * range) + mSaturationMin);
}
}
/**
* @param saturation_abs
* @return saturation[%]
*/
public synchronized int getSaturation(final int saturation_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateSaturationLimit(mNativePtr);
final float range = Math.abs(mSaturationMax - mSaturationMin);
if (range > 0) {
result = (int)((saturation_abs - mSaturationMin) * 100.f / range);
}
}
return result;
}
/**
* @return saturation[%]
*/
public synchronized int getSaturation() {
return getSaturation(nativeGetSaturation(mNativePtr));
}
public synchronized void resetSaturation() {
if (mNativePtr != 0) {
nativeSetSaturation(mNativePtr, mSaturationDef);
}
}
//================================================================================
/**
* @param hue [%]
*/
public synchronized void setHue(final int hue) {
if (mNativePtr != 0) {
final float range = Math.abs(mHueMax - mHueMin);
if (range > 0)
nativeSetHue(mNativePtr, (int)(hue / 100.f * range) + mHueMin);
}
}
/**
* @param hue_abs
* @return hue[%]
*/
public synchronized int getHue(final int hue_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateHueLimit(mNativePtr);
final float range = Math.abs(mHueMax - mHueMin);
if (range > 0) {
result = (int)((hue_abs - mHueMin) * 100.f / range);
}
}
return result;
}
/**
* @return hue[%]
*/
public synchronized int getHue() {
return getHue(nativeGetHue(mNativePtr));
}
public synchronized void resetHue() {
if (mNativePtr != 0) {
nativeSetHue(mNativePtr, mSaturationDef);
}
}
//================================================================================
public void setPowerlineFrequency(final int frequency) {
if (mNativePtr != 0)
nativeSetPowerlineFrequency(mNativePtr, frequency);
}
public int getPowerlineFrequency() {
return nativeGetPowerlineFrequency(mNativePtr);
}
//================================================================================
/**
* this may not work well with some combination of camera and device
* @param zoom [%]
*/
public synchronized void setZoom(final int zoom) {
if (mNativePtr != 0) {
final float range = Math.abs(mZoomMax - mZoomMin);
if (range > 0) {
final int z = (int)(zoom / 100.f * range) + mZoomMin;
// Log.d(TAG, "setZoom:zoom=" + zoom + " ,value=" + z);
nativeSetZoom(mNativePtr, z);
}
}
}
/**
* @param zoom_abs
* @return zoom[%]
*/
public synchronized int getZoom(final int zoom_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateZoomLimit(mNativePtr);
final float range = Math.abs(mZoomMax - mZoomMin);
if (range > 0) {
result = (int)((zoom_abs - mZoomMin) * 100.f / range);
}
}
return result;
}
/**
* @return zoom[%]
*/
public synchronized int getZoom() {
return getZoom(nativeGetZoom(mNativePtr));
}
public synchronized void resetZoom() {
if (mNativePtr != 0) {
nativeSetZoom(mNativePtr, mZoomDef);
}
}
//================================================================================
public synchronized void updateCameraParams() {
if (mNativePtr != 0) {
if ((mControlSupports == 0) || (mProcSupports == 0)) {
// サポートしている機能フラグを取得
if (mControlSupports == 0)
mControlSupports = nativeGetCtrlSupports(mNativePtr);
if (mProcSupports == 0)
mProcSupports = nativeGetProcSupports(mNativePtr);
// 設定値を取得
if ((mControlSupports != 0) && (mProcSupports != 0)) {
nativeUpdateBrightnessLimit(mNativePtr);
nativeUpdateContrastLimit(mNativePtr);
nativeUpdateSharpnessLimit(mNativePtr);
nativeUpdateGainLimit(mNativePtr);
nativeUpdateGammaLimit(mNativePtr);
nativeUpdateSaturationLimit(mNativePtr);
nativeUpdateHueLimit(mNativePtr);
nativeUpdateZoomLimit(mNativePtr);
nativeUpdateWhiteBlanceLimit(mNativePtr);
nativeUpdateFocusLimit(mNativePtr);
}
if (DEBUG) {
dumpControls(mControlSupports);
dumpProc(mProcSupports);
Log.v(TAG, String.format("Brightness:min=%d,max=%d,def=%d", mBrightnessMin, mBrightnessMax, mBrightnessDef));
Log.v(TAG, String.format("Contrast:min=%d,max=%d,def=%d", mContrastMin, mContrastMax, mContrastDef));
Log.v(TAG, String.format("Sharpness:min=%d,max=%d,def=%d", mSharpnessMin, mSharpnessMax, mSharpnessDef));
Log.v(TAG, String.format("Gain:min=%d,max=%d,def=%d", mGainMin, mGainMax, mGainDef));
Log.v(TAG, String.format("Gamma:min=%d,max=%d,def=%d", mGammaMin, mGammaMax, mGammaDef));
Log.v(TAG, String.format("Saturation:min=%d,max=%d,def=%d", mSaturationMin, mSaturationMax, mSaturationDef));
Log.v(TAG, String.format("Hue:min=%d,max=%d,def=%d", mHueMin, mHueMax, mHueDef));
Log.v(TAG, String.format("Zoom:min=%d,max=%d,def=%d", mZoomMin, mZoomMax, mZoomDef));
Log.v(TAG, String.format("WhiteBlance:min=%d,max=%d,def=%d", mWhiteBlanceMin, mWhiteBlanceMax, mWhiteBlanceDef));
Log.v(TAG, String.format("Focus:min=%d,max=%d,def=%d", mFocusMin, mFocusMax, mFocusDef));
}
}
} else {
mControlSupports = mProcSupports = 0;
}
}
private static final String[] SUPPORTS_CTRL = {
"D0: Scanning Mode",
"D1: Auto-Exposure Mode",
"D2: Auto-Exposure Priority",
"D3: Exposure Time (Absolute)",
"D4: Exposure Time (Relative)",
"D5: Focus (Absolute)",
"D6: Focus (Relative)",
"D7: Iris (Absolute)",
"D8: Iris (Relative)",
"D9: Zoom (Absolute)",
"D10: Zoom (Relative)",
"D11: PanTilt (Absolute)",
"D12: PanTilt (Relative)",
"D13: Roll (Absolute)",
"D14: Roll (Relative)",
"D15: Reserved",
"D16: Reserved",
"D17: Focus, Auto",
"D18: Privacy",
"D19: Focus, Simple",
"D20: Window",
"D21: Region of Interest",
"D22: Reserved, set to zero",
"D23: Reserved, set to zero",
};
private static final String[] SUPPORTS_PROC = {
"D0: Brightness",
"D1: Contrast",
"D2: Hue",
"D3: Saturation",
"D4: Sharpness",
"D5: Gamma",
"D6: White Balance Temperature",
"D7: White Balance Component",
"D8: Backlight Compensation",
"D9: Gain",
"D10: Power Line Frequency",
"D11: Hue, Auto",
"D12: White Balance Temperature, Auto",
"D13: White Balance Component, Auto",
"D14: Digital Multiplier",
"D15: Digital Multiplier Limit",
"D16: Analog Video Standard",
"D17: Analog Video Lock Status",
"D18: Contrast, Auto",
"D19: Reserved. Set to zero",
"D20: Reserved. Set to zero",
"D21: Reserved. Set to zero",
"D22: Reserved. Set to zero",
"D23: Reserved. Set to zero",
};
private static final void dumpControls(final long controlSupports) {
Log.i(TAG, String.format("controlSupports=%x", controlSupports));
for (int i = 0; i < SUPPORTS_CTRL.length; i++) {
Log.i(TAG, SUPPORTS_CTRL[i] + ((controlSupports & (0x1 << i)) != 0 ? "=enabled" : "=disabled"));
}
}
private static final void dumpProc(final long procSupports) {
Log.i(TAG, String.format("procSupports=%x", procSupports));
for (int i = 0; i < SUPPORTS_PROC.length; i++) {
Log.i(TAG, SUPPORTS_PROC[i] + ((procSupports & (0x1 << i)) != 0 ? "=enabled" : "=disabled"));
}
}
private final String getUSBFSName(final UsbControlBlock ctrlBlock) {
String result = null;
final String name = ctrlBlock.getDeviceName();
final String[] v = !TextUtils.isEmpty(name) ? name.split("/") : null;
if ((v != null) && (v.length > 2)) {
final StringBuilder sb = new StringBuilder(v[0]);
for (int i = 1; i < v.length - 2; i++)
sb.append("/").append(v[i]);
result = sb.toString();
}
if (TextUtils.isEmpty(result)) {
Log.w(TAG, "failed to get USBFS path, try to use default path:" + name);
result = DEFAULT_USBFS;
}
return result;
}
// #nativeCreate and #nativeDestroy are not static methods.
private final native long nativeCreate();
private final native void nativeDestroy(final long id_camera);
private final native int nativeConnect(long id_camera, int venderId, int productId, int fileDescriptor, int busNum, int devAddr, String usbfs);
private static final native int nativeRelease(final long id_camera);
private static final native int nativeSetStatusCallback(final long mNativePtr, final IStatusCallback callback);
private static final native int nativeSetButtonCallback(final long mNativePtr, final IButtonCallback callback);
private static final native int nativeSetPreviewSize(final long id_camera, final int width, final int height, final int min_fps, final int max_fps, final int mode, final float bandwidth);
private static final native String nativeGetSupportedSize(final long id_camera);
private static final native int nativeStartPreview(final long id_camera);
private static final native int nativeStopPreview(final long id_camera);
private static final native int nativeSetPreviewDisplay(final long id_camera, final Surface surface);
private static final native int nativeSetFrameCallback(final long mNativePtr, final IFrameCallback callback, final int pixelFormat);
//**********************************************************************
/**
* start movie capturing(this should call while previewing)
* @param surface
*/
public void startCapture(final Surface surface) {
if (mCtrlBlock != null && surface != null) {
nativeSetCaptureDisplay(mNativePtr, surface);
} else
throw new NullPointerException("startCapture");
}
/**
* stop movie capturing
*/
public void stopCapture() {
if (mCtrlBlock != null) {
nativeSetCaptureDisplay(mNativePtr, null);
}
}
private static final native int nativeSetCaptureDisplay(final long id_camera, final Surface surface);
private static final native long nativeGetCtrlSupports(final long id_camera);
private static final native long nativeGetProcSupports(final long id_camera);
private final native int nativeUpdateScanningModeLimit(final long id_camera);
private static final native int nativeSetScanningMode(final long id_camera, final int scanning_mode);
private static final native int nativeGetScanningMode(final long id_camera);
private final native int nativeUpdateExposureModeLimit(final long id_camera);
private static final native int nativeSetExposureMode(final long id_camera, final int exposureMode);
private static final native int nativeGetExposureMode(final long id_camera);
private final native int nativeUpdateExposurePriorityLimit(final long id_camera);
private static final native int nativeSetExposurePriority(final long id_camera, final int priority);
private static final native int nativeGetExposurePriority(final long id_camera);
private final native int nativeUpdateExposureLimit(final long id_camera);
private static final native int nativeSetExposure(final long id_camera, final int exposure);
private static final native int nativeGetExposure(final long id_camera);
private final native int nativeUpdateExposureRelLimit(final long id_camera);
private static final native int nativeSetExposureRel(final long id_camera, final int exposure_rel);
private static final native int nativeGetExposureRel(final long id_camera);
private final native int nativeUpdateAutoFocusLimit(final long id_camera);
private static final native int nativeSetAutoFocus(final long id_camera, final boolean autofocus);
private static final native int nativeGetAutoFocus(final long id_camera);
private final native int nativeUpdateFocusLimit(final long id_camera);
private static final native int nativeSetFocus(final long id_camera, final int focus);
private static final native int nativeGetFocus(final long id_camera);
private final native int nativeUpdateFocusRelLimit(final long id_camera);
private static final native int nativeSetFocusRel(final long id_camera, final int focus_rel);
private static final native int nativeGetFocusRel(final long id_camera);
private final native int nativeUpdateIrisLimit(final long id_camera);
private static final native int nativeSetIris(final long id_camera, final int iris);
private static final native int nativeGetIris(final long id_camera);
private final native int nativeUpdateIrisRelLimit(final long id_camera);
private static final native int nativeSetIrisRel(final long id_camera, final int iris_rel);
private static final native int nativeGetIrisRel(final long id_camera);
private final native int nativeUpdatePanLimit(final long id_camera);
private static final native int nativeSetPan(final long id_camera, final int pan);
private static final native int nativeGetPan(final long id_camera);
private final native int nativeUpdatePanRelLimit(final long id_camera);
private static final native int nativeSetPanRel(final long id_camera, final int pan_rel);
private static final native int nativeGetPanRel(final long id_camera);
private final native int nativeUpdateTiltLimit(final long id_camera);
private static final native int nativeSetTilt(final long id_camera, final int tilt);
private static final native int nativeGetTilt(final long id_camera);
private final native int nativeUpdateTiltRelLimit(final long id_camera);
private static final native int nativeSetTiltRel(final long id_camera, final int tilt_rel);
private static final native int nativeGetTiltRel(final long id_camera);
private final native int nativeUpdateRollLimit(final long id_camera);
private static final native int nativeSetRoll(final long id_camera, final int roll);
private static final native int nativeGetRoll(final long id_camera);
private final native int nativeUpdateRollRelLimit(final long id_camera);
private static final native int nativeSetRollRel(final long id_camera, final int roll_rel);
private static final native int nativeGetRollRel(final long id_camera);
private final native int nativeUpdateAutoWhiteBlanceLimit(final long id_camera);
private static final native int nativeSetAutoWhiteBlance(final long id_camera, final boolean autoWhiteBlance);
private static final native int nativeGetAutoWhiteBlance(final long id_camera);
private final native int nativeUpdateAutoWhiteBlanceCompoLimit(final long id_camera);
private static final native int nativeSetAutoWhiteBlanceCompo(final long id_camera, final boolean autoWhiteBlanceCompo);
private static final native int nativeGetAutoWhiteBlanceCompo(final long id_camera);
private final native int nativeUpdateWhiteBlanceLimit(final long id_camera);
private static final native int nativeSetWhiteBlance(final long id_camera, final int whiteBlance);
private static final native int nativeGetWhiteBlance(final long id_camera);
private final native int nativeUpdateWhiteBlanceCompoLimit(final long id_camera);
private static final native int nativeSetWhiteBlanceCompo(final long id_camera, final int whiteBlance_compo);
private static final native int nativeGetWhiteBlanceCompo(final long id_camera);
private final native int nativeUpdateBacklightCompLimit(final long id_camera);
private static final native int nativeSetBacklightComp(final long id_camera, final int backlight_comp);
private static final native int nativeGetBacklightComp(final long id_camera);
private final native int nativeUpdateBrightnessLimit(final long id_camera);
private static final native int nativeSetBrightness(final long id_camera, final int brightness);
private static final native int nativeGetBrightness(final long id_camera);
private final native int nativeUpdateContrastLimit(final long id_camera);
private static final native int nativeSetContrast(final long id_camera, final int contrast);
private static final native int nativeGetContrast(final long id_camera);
private final native int nativeUpdateAutoContrastLimit(final long id_camera);
private static final native int nativeSetAutoContrast(final long id_camera, final boolean autocontrast);
private static final native int nativeGetAutoContrast(final long id_camera);
private final native int nativeUpdateSharpnessLimit(final long id_camera);
private static final native int nativeSetSharpness(final long id_camera, final int sharpness);
private static final native int nativeGetSharpness(final long id_camera);
private final native int nativeUpdateGainLimit(final long id_camera);
private static final native int nativeSetGain(final long id_camera, final int gain);
private static final native int nativeGetGain(final long id_camera);
private final native int nativeUpdateGammaLimit(final long id_camera);
private static final native int nativeSetGamma(final long id_camera, final int gamma);
private static final native int nativeGetGamma(final long id_camera);
private final native int nativeUpdateSaturationLimit(final long id_camera);
private static final native int nativeSetSaturation(final long id_camera, final int saturation);
private static final native int nativeGetSaturation(final long id_camera);
private final native int nativeUpdateHueLimit(final long id_camera);
private static final native int nativeSetHue(final long id_camera, final int hue);
private static final native int nativeGetHue(final long id_camera);
private final native int nativeUpdateAutoHueLimit(final long id_camera);
private static final native int nativeSetAutoHue(final long id_camera, final boolean autohue);
private static final native int nativeGetAutoHue(final long id_camera);
private final native int nativeUpdatePowerlineFrequencyLimit(final long id_camera);
private static final native int nativeSetPowerlineFrequency(final long id_camera, final int frequency);
private static final native int nativeGetPowerlineFrequency(final long id_camera);
private final native int nativeUpdateZoomLimit(final long id_camera);
private static final native int nativeSetZoom(final long id_camera, final int zoom);
private static final native int nativeGetZoom(final long id_camera);
private final native int nativeUpdateZoomRelLimit(final long id_camera);
private static final native int nativeSetZoomRel(final long id_camera, final int zoom_rel);
private static final native int nativeGetZoomRel(final long id_camera);
private final native int nativeUpdateDigitalMultiplierLimit(final long id_camera);
private static final native int nativeSetDigitalMultiplier(final long id_camera, final int multiplier);
private static final native int nativeGetDigitalMultiplier(final long id_camera);
private final native int nativeUpdateDigitalMultiplierLimitLimit(final long id_camera);
private static final native int nativeSetDigitalMultiplierLimit(final long id_camera, final int multiplier_limit);
private static final native int nativeGetDigitalMultiplierLimit(final long id_camera);
private final native int nativeUpdateAnalogVideoStandardLimit(final long id_camera);
private static final native int nativeSetAnalogVideoStandard(final long id_camera, final int standard);
private static final native int nativeGetAnalogVideoStandard(final long id_camera);
private final native int nativeUpdateAnalogVideoLockStateLimit(final long id_camera);
private static final native int nativeSetAnalogVideoLoackState(final long id_camera, final int state);
private static final native int nativeGetAnalogVideoLoackState(final long id_camera);
private final native int nativeUpdatePrivacyLimit(final long id_camera);
private static final native int nativeSetPrivacy(final long id_camera, final boolean privacy);
private static final native int nativeGetPrivacy(final long id_camera);
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/IAudioEncoder.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
public interface IAudioEncoder {
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/IVideoEncoder.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
public interface IVideoEncoder {
public boolean frameAvailableSoon();
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/MediaAudioEncoder.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.util.Log;
public class MediaAudioEncoder extends MediaEncoder implements IAudioEncoder {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "MediaAudioEncoder";
private static final String MIME_TYPE = "audio/mp4a-latm";
private static final int SAMPLE_RATE = 44100; // 44.1[KHz] is only setting guaranteed to be available on all devices.
private static final int BIT_RATE = 64000;
public static final int SAMPLES_PER_FRAME = 1024; // AAC, bytes/frame/channel
public static final int FRAMES_PER_BUFFER = 25; // AAC, frame/buffer/sec
private AudioThread mAudioThread = null;
public MediaAudioEncoder(final MediaMuxerWrapper muxer, final MediaEncoderListener listener) {
super(muxer, listener);
}
@Override
protected void prepare() throws IOException {
if (DEBUG) Log.v(TAG, "prepare:");
mTrackIndex = -1;
mMuxerStarted = mIsEOS = false;
// prepare MediaCodec for AAC encoding of audio data from inernal mic.
final MediaCodecInfo audioCodecInfo = selectAudioCodec(MIME_TYPE);
if (audioCodecInfo == null) {
Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE);
return;
}
if (DEBUG) Log.i(TAG, "selected codec: " + audioCodecInfo.getName());
final MediaFormat audioFormat = MediaFormat.createAudioFormat(MIME_TYPE, SAMPLE_RATE, 1);
audioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
audioFormat.setInteger(MediaFormat.KEY_CHANNEL_MASK, AudioFormat.CHANNEL_IN_MONO);
audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
// audioFormat.setLong(MediaFormat.KEY_MAX_INPUT_SIZE, inputFile.length());
// audioFormat.setLong(MediaFormat.KEY_DURATION, (long)durationInMs );
if (DEBUG) Log.i(TAG, "format: " + audioFormat);
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mMediaCodec.configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
if (DEBUG) Log.i(TAG, "prepare finishing");
if (mListener != null) {
try {
mListener.onPrepared(this);
} catch (final Exception e) {
Log.e(TAG, "prepare:", e);
}
}
}
@Override
protected void startRecording() {
super.startRecording();
// create and execute audio capturing thread using internal mic
if (mAudioThread == null) {
mAudioThread = new AudioThread();
mAudioThread.start();
}
}
@Override
protected void release() {
mAudioThread = null;
super.release();
}
private static final int[] AUDIO_SOURCES = new int[] {
MediaRecorder.AudioSource.DEFAULT,
MediaRecorder.AudioSource.MIC,
MediaRecorder.AudioSource.CAMCORDER,
};
/**
* Thread to capture audio data from internal mic as uncompressed 16bit PCM data
* and write them to the MediaCodec encoder
*/
private class AudioThread extends Thread {
@Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO); // THREAD_PRIORITY_URGENT_AUDIO
int cnt = 0;
final int min_buffer_size = AudioRecord.getMinBufferSize(
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
int buffer_size = SAMPLES_PER_FRAME * FRAMES_PER_BUFFER;
if (buffer_size < min_buffer_size)
buffer_size = ((min_buffer_size / SAMPLES_PER_FRAME) + 1) * SAMPLES_PER_FRAME * 2;
final ByteBuffer buf = ByteBuffer.allocateDirect(SAMPLES_PER_FRAME).order(ByteOrder.nativeOrder());
AudioRecord audioRecord = null;
for (final int src: AUDIO_SOURCES) {
try {
audioRecord = new AudioRecord(src,
SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buffer_size);
if (audioRecord != null) {
if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
audioRecord.release();
audioRecord = null;
}
}
} catch (final Exception e) {
audioRecord = null;
}
if (audioRecord != null) {
break;
}
}
if (audioRecord != null) {
try {
if (mIsCapturing) {
if (DEBUG) Log.v(TAG, "AudioThread:start audio recording");
int readBytes;
audioRecord.startRecording();
try {
for ( ; mIsCapturing && !mRequestStop && !mIsEOS ; ) {
// read audio data from internal mic
buf.clear();
try {
readBytes = audioRecord.read(buf, SAMPLES_PER_FRAME);
} catch (final Exception e) {
break;
}
if (readBytes > 0) {
// set audio data to encoder
buf.position(readBytes);
buf.flip();
encode(buf, readBytes, getPTSUs());
frameAvailableSoon();
cnt++;
}
}
if (cnt > 0) {
frameAvailableSoon();
}
} finally {
audioRecord.stop();
}
}
} catch (final Exception e) {
Log.e(TAG, "AudioThread#run", e);
} finally {
audioRecord.release();
}
}
if (cnt == 0) {
for (int i = 0; mIsCapturing && (i < 5); i++) {
buf.position(SAMPLES_PER_FRAME);
buf.flip();
try {
encode(buf, SAMPLES_PER_FRAME, getPTSUs());
frameAvailableSoon();
} catch (final Exception e) {
break;
}
synchronized(this) {
try {
wait(50);
} catch (final InterruptedException e) {
}
}
}
}
if (DEBUG) Log.v(TAG, "AudioThread:finished");
}
}
/**
* select the first codec that match a specific MIME type
* @param mimeType
* @return
*/
private static final MediaCodecInfo selectAudioCodec(final String mimeType) {
if (DEBUG) Log.v(TAG, "selectAudioCodec:");
MediaCodecInfo result = null;
// get the list of available codecs
final int numCodecs = MediaCodecList.getCodecCount();
LOOP: for (int i = 0; i < numCodecs; i++) {
final MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (!codecInfo.isEncoder()) { // skipp decoder
continue;
}
final String[] types = codecInfo.getSupportedTypes();
for (int j = 0; j < types.length; j++) {
if (DEBUG) Log.i(TAG, "supportedType:" + codecInfo.getName() + ",MIME=" + types[j]);
if (types[j].equalsIgnoreCase(mimeType)) {
if (result == null) {
result = codecInfo;
break LOOP;
}
}
}
}
return result;
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/MediaEncoder.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
public abstract class MediaEncoder implements Runnable {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "MediaEncoder";
protected static final int TIMEOUT_USEC = 10000; // 10[msec]
protected static final int MSG_FRAME_AVAILABLE = 1;
protected static final int MSG_STOP_RECORDING = 9;
public interface MediaEncoderListener {
public void onPrepared(MediaEncoder encoder);
public void onStopped(MediaEncoder encoder);
}
protected final Object mSync = new Object();
/**
* Flag that indicate this encoder is capturing now.
*/
protected volatile boolean mIsCapturing;
/**
* Flag that indicate the frame data will be available soon.
*/
private int mRequestDrain;
/**
* Flag to request stop capturing
*/
protected volatile boolean mRequestStop;
/**
* Flag that indicate encoder received EOS(End Of Stream)
*/
protected boolean mIsEOS;
/**
* Flag the indicate the muxer is running
*/
protected boolean mMuxerStarted;
/**
* Track Number
*/
protected int mTrackIndex;
/**
* MediaCodec instance for encoding
*/
protected MediaCodec mMediaCodec; // API >= 16(Android4.1.2)
/**
* Weak refarence of MediaMuxerWarapper instance
*/
protected final WeakReference<MediaMuxerWrapper> mWeakMuxer;
/**
* BufferInfo instance for dequeuing
*/
private MediaCodec.BufferInfo mBufferInfo; // API >= 16(Android4.1.2)
protected final MediaEncoderListener mListener;
public MediaEncoder(final MediaMuxerWrapper muxer, final MediaEncoderListener listener) {
if (listener == null) throw new NullPointerException("MediaEncoderListener is null");
if (muxer == null) throw new NullPointerException("MediaMuxerWrapper is null");
mWeakMuxer = new WeakReference<MediaMuxerWrapper>(muxer);
muxer.addEncoder(this);
mListener = listener;
synchronized (mSync) {
// create BufferInfo here for effectiveness(to reduce GC)
mBufferInfo = new MediaCodec.BufferInfo();
// wait for starting thread
new Thread(this, getClass().getSimpleName()).start();
try {
mSync.wait();
} catch (final InterruptedException e) {
}
}
}
public String getOutputPath() {
final MediaMuxerWrapper muxer = mWeakMuxer.get();
return muxer != null ? muxer.getOutputPath() : null;
}
/**
* the method to indicate frame data is soon available or already available
* @return return true if encoder is ready to encod.
*/
public boolean frameAvailableSoon() {
// if (DEBUG) Log.v(TAG, "frameAvailableSoon");
synchronized (mSync) {
if (!mIsCapturing || mRequestStop) {
return false;
}
mRequestDrain++;
mSync.notifyAll();
}
return true;
}
/**
* encoding loop on private thread
*/
@Override
public void run() {
// android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
synchronized (mSync) {
mRequestStop = false;
mRequestDrain = 0;
mSync.notify();
}
final boolean isRunning = true;
boolean localRequestStop;
boolean localRequestDrain;
while (isRunning) {
synchronized (mSync) {
localRequestStop = mRequestStop;
localRequestDrain = (mRequestDrain > 0);
if (localRequestDrain)
mRequestDrain--;
}
if (localRequestStop) {
drain();
// request stop recording
signalEndOfInputStream();
// process output data again for EOS signale
drain();
// release all related objects
release();
break;
}
if (localRequestDrain) {
drain();
} else {
synchronized (mSync) {
try {
mSync.wait();
} catch (final InterruptedException e) {
break;
}
}
}
} // end of while
if (DEBUG) Log.d(TAG, "Encoder thread exiting");
synchronized (mSync) {
mRequestStop = true;
mIsCapturing = false;
}
}
/*
* prepareing method for each sub class
* this method should be implemented in sub class, so set this as abstract method
* @throws IOException
*/
/*package*/ abstract void prepare() throws IOException;
/*package*/ void startRecording() {
if (DEBUG) Log.v(TAG, "startRecording");
synchronized (mSync) {
mIsCapturing = true;
mRequestStop = false;
mSync.notifyAll();
}
}
/**
* the method to request stop encoding
*/
/*package*/ void stopRecording() {
if (DEBUG) Log.v(TAG, "stopRecording");
synchronized (mSync) {
if (!mIsCapturing || mRequestStop) {
return;
}
mRequestStop = true; // for rejecting newer frame
mSync.notifyAll();
// We can not know when the encoding and writing finish.
// so we return immediately after request to avoid delay of caller thread
}
}
//********************************************************************************
//********************************************************************************
/**
* Release all releated objects
*/
protected void release() {
if (DEBUG) Log.d(TAG, "release:");
try {
mListener.onStopped(this);
} catch (final Exception e) {
Log.e(TAG, "failed onStopped", e);
}
mIsCapturing = false;
if (mMediaCodec != null) {
try {
mMediaCodec.stop();
mMediaCodec.release();
mMediaCodec = null;
} catch (final Exception e) {
Log.e(TAG, "failed releasing MediaCodec", e);
}
}
if (mMuxerStarted) {
final MediaMuxerWrapper muxer = mWeakMuxer.get();
if (muxer != null) {
try {
muxer.stop();
} catch (final Exception e) {
Log.e(TAG, "failed stopping muxer", e);
}
}
}
mBufferInfo = null;
}
protected void signalEndOfInputStream() {
if (DEBUG) Log.d(TAG, "sending EOS to encoder");
// signalEndOfInputStream is only avairable for video encoding with surface
// and equivalent sending a empty buffer with BUFFER_FLAG_END_OF_STREAM flag.
// mMediaCodec.signalEndOfInputStream(); // API >= 18
encode((byte[])null, 0, getPTSUs());
}
/**
* Method to set byte array to the MediaCodec encoder
* @param buffer
* @param length length of byte array, zero means EOS.
* @param presentationTimeUs
*/
@SuppressWarnings("deprecation")
protected void encode(final byte[] buffer, final int length, final long presentationTimeUs) {
// if (DEBUG) Log.v(TAG, "encode:buffer=" + buffer);
if (!mIsCapturing) return;
int ix = 0, sz;
final ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
while (mIsCapturing && ix < length) {
final int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
if (inputBufferIndex >= 0) {
final ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
inputBuffer.clear();
sz = inputBuffer.remaining();
sz = (ix + sz < length) ? sz : length - ix;
if (sz > 0 && (buffer != null)) {
inputBuffer.put(buffer, ix, sz);
}
ix += sz;
// if (DEBUG) Log.v(TAG, "encode:queueInputBuffer");
if (length <= 0) {
// send EOS
mIsEOS = true;
if (DEBUG) Log.i(TAG, "send BUFFER_FLAG_END_OF_STREAM");
mMediaCodec.queueInputBuffer(inputBufferIndex, 0, 0,
presentationTimeUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
break;
} else {
mMediaCodec.queueInputBuffer(inputBufferIndex, 0, sz,
presentationTimeUs, 0);
}
} else if (inputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
// wait for MediaCodec encoder is ready to encode
// nothing to do here because MediaCodec#dequeueInputBuffer(TIMEOUT_USEC)
// will wait for maximum TIMEOUT_USEC(10msec) on each call
}
}
}
/**
* Method to set ByteBuffer to the MediaCodec encoder
* @param buffer null means EOS
* @param presentationTimeUs
*/
@SuppressWarnings("deprecation")
protected void encode(final ByteBuffer buffer, final int length, final long presentationTimeUs) {
// if (DEBUG) Log.v(TAG, "encode:buffer=" + buffer);
if (!mIsCapturing) return;
int ix = 0, sz;
final ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
while (mIsCapturing && ix < length) {
final int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
if (inputBufferIndex >= 0) {
final ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
inputBuffer.clear();
sz = inputBuffer.remaining();
sz = (ix + sz < length) ? sz : length - ix;
if (sz > 0 && (buffer != null)) {
buffer.position(ix + sz);
buffer.flip();
inputBuffer.put(buffer);
}
ix += sz;
// if (DEBUG) Log.v(TAG, "encode:queueInputBuffer");
if (length <= 0) {
// send EOS
mIsEOS = true;
if (DEBUG) Log.i(TAG, "send BUFFER_FLAG_END_OF_STREAM");
mMediaCodec.queueInputBuffer(inputBufferIndex, 0, 0,
presentationTimeUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
break;
} else {
mMediaCodec.queueInputBuffer(inputBufferIndex, 0, sz,
presentationTimeUs, 0);
}
} else if (inputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
// wait for MediaCodec encoder is ready to encode
// nothing to do here because MediaCodec#dequeueInputBuffer(TIMEOUT_USEC)
// will wait for maximum TIMEOUT_USEC(10msec) on each call
}
}
}
/**
* drain encoded data and write them to muxer
*/
@SuppressWarnings("deprecation")
protected void drain() {
if (mMediaCodec == null) return;
ByteBuffer[] encoderOutputBuffers = mMediaCodec.getOutputBuffers();
int encoderStatus, count = 0;
final MediaMuxerWrapper muxer = mWeakMuxer.get();
if (muxer == null) {
// throw new NullPointerException("muxer is unexpectedly null");
Log.w(TAG, "muxer is unexpectedly null");
return;
}
LOOP: while (mIsCapturing) {
// get encoded data with maximum timeout duration of TIMEOUT_USEC(=10[msec])
encoderStatus = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
// wait 5 counts(=TIMEOUT_USEC x 5 = 50msec) until data/EOS come
if (!mIsEOS) {
if (++count > 5)
break LOOP; // out of while
}
} else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
if (DEBUG) Log.v(TAG, "INFO_OUTPUT_BUFFERS_CHANGED");
// this shoud not come when encoding
encoderOutputBuffers = mMediaCodec.getOutputBuffers();
} else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
if (DEBUG) Log.v(TAG, "INFO_OUTPUT_FORMAT_CHANGED");
// this status indicate the output format of codec is changed
// this should come only once before actual encoded data
// but this status never come on Android4.3 or less
// and in that case, you should treat when MediaCodec.BUFFER_FLAG_CODEC_CONFIG come.
if (mMuxerStarted) { // second time request is error
throw new RuntimeException("format changed twice");
}
// get output format from codec and pass them to muxer
// getOutputFormat should be called after INFO_OUTPUT_FORMAT_CHANGED otherwise crash.
final MediaFormat format = mMediaCodec.getOutputFormat(); // API >= 16
mTrackIndex = muxer.addTrack(format);
mMuxerStarted = true;
if (!muxer.start()) {
// we should wait until muxer is ready
synchronized (muxer) {
while (!muxer.isStarted())
try {
muxer.wait(100);
} catch (final InterruptedException e) {
break LOOP;
}
}
}
} else if (encoderStatus < 0) {
// unexpected status
if (DEBUG) Log.w(TAG, "drain:unexpected result from encoder#dequeueOutputBuffer: " + encoderStatus);
} else {
final ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
if (encodedData == null) {
// this never should come...may be a MediaCodec internal error
throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null");
}
if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
// You shoud set output format to muxer here when you target Android4.3 or less
// but MediaCodec#getOutputFormat can not call here(because INFO_OUTPUT_FORMAT_CHANGED don't come yet)
// therefor we should expand and prepare output format from buffer data.
// This sample is for API>=18(>=Android 4.3), just ignore this flag here
if (DEBUG) Log.d(TAG, "drain:BUFFER_FLAG_CODEC_CONFIG");
mBufferInfo.size = 0;
}
if (mBufferInfo.size != 0) {
// encoded data is ready, clear waiting counter
count = 0;
if (!mMuxerStarted) {
// muxer is not ready...this will prrograming failure.
throw new RuntimeException("drain:muxer hasn't started");
}
// write encoded data to muxer(need to adjust presentationTimeUs.
mBufferInfo.presentationTimeUs = getPTSUs();
muxer.writeSampleData(mTrackIndex, encodedData, mBufferInfo);
prevOutputPTSUs = mBufferInfo.presentationTimeUs;
}
// return buffer to encoder
mMediaCodec.releaseOutputBuffer(encoderStatus, false);
if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
// when EOS come.
mMuxerStarted = mIsCapturing = false;
break; // out of while
}
}
}
}
/**
* previous presentationTimeUs for writing
*/
private long prevOutputPTSUs = 0;
/**
* get next encoding presentationTimeUs
* @return
*/
protected long getPTSUs() {
long result = System.nanoTime() / 1000L;
// presentationTimeUs should be monotonic
// otherwise muxer fail to write
if (result < prevOutputPTSUs)
result = (prevOutputPTSUs - result) + result;
return result;
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/MediaMuxerWrapper.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Locale;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
public class MediaMuxerWrapper {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "MediaMuxerWrapper";
private static final String DIR_NAME = "USBCameraTest";
private static final SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
private String mOutputPath;
private final MediaMuxer mMediaMuxer; // API >= 18
private int mEncoderCount, mStatredCount;
private boolean mIsStarted;
private MediaEncoder mVideoEncoder, mAudioEncoder;
/**
* Constructor
* @param ext extension of output file
* @throws IOException
*/
public MediaMuxerWrapper(String ext) throws IOException {
if (TextUtils.isEmpty(ext)) ext = ".mp4";
try {
mOutputPath = getCaptureFile(Environment.DIRECTORY_MOVIES, ext).toString();
} catch (final NullPointerException e) {
throw new RuntimeException("This app has no permission of writing external storage");
}
mMediaMuxer = new MediaMuxer(mOutputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
mEncoderCount = mStatredCount = 0;
mIsStarted = false;
}
public String getOutputPath() {
return mOutputPath;
}
public void prepare() throws IOException {
if (mVideoEncoder != null)
mVideoEncoder.prepare();
if (mAudioEncoder != null)
mAudioEncoder.prepare();
}
public void startRecording() {
if (mVideoEncoder != null)
mVideoEncoder.startRecording();
if (mAudioEncoder != null)
mAudioEncoder.startRecording();
}
public void stopRecording() {
if (mVideoEncoder != null)
mVideoEncoder.stopRecording();
mVideoEncoder = null;
if (mAudioEncoder != null)
mAudioEncoder.stopRecording();
mAudioEncoder = null;
}
public synchronized boolean isStarted() {
return mIsStarted;
}
//**********************************************************************
//**********************************************************************
/**
* assign encoder to this calss. this is called from encoder.
* @param encoder instance of MediaVideoEncoder or MediaAudioEncoder
*/
/*package*/ void addEncoder(final MediaEncoder encoder) {
if (encoder instanceof MediaVideoEncoder) {
if (mVideoEncoder != null)
throw new IllegalArgumentException("Video encoder already added.");
mVideoEncoder = encoder;
} else if (encoder instanceof MediaSurfaceEncoder) {
if (mVideoEncoder != null)
throw new IllegalArgumentException("Video encoder already added.");
mVideoEncoder = encoder;
} else if (encoder instanceof MediaVideoBufferEncoder) {
if (mVideoEncoder != null)
throw new IllegalArgumentException("Video encoder already added.");
mVideoEncoder = encoder;
} else if (encoder instanceof MediaAudioEncoder) {
if (mAudioEncoder != null)
throw new IllegalArgumentException("Video encoder already added.");
mAudioEncoder = encoder;
} else
throw new IllegalArgumentException("unsupported encoder");
mEncoderCount = (mVideoEncoder != null ? 1 : 0) + (mAudioEncoder != null ? 1 : 0);
}
/**
* request start recording from encoder
* @return true when muxer is ready to write
*/
/*package*/ synchronized boolean start() {
if (DEBUG) Log.v(TAG, "start:");
mStatredCount++;
if ((mEncoderCount > 0) && (mStatredCount == mEncoderCount)) {
mMediaMuxer.start();
mIsStarted = true;
notifyAll();
if (DEBUG) Log.v(TAG, "MediaMuxer started:");
}
return mIsStarted;
}
/**
* request stop recording from encoder when encoder received EOS
*/
/*package*/ synchronized void stop() {
if (DEBUG) Log.v(TAG, "stop:mStatredCount=" + mStatredCount);
mStatredCount--;
if ((mEncoderCount > 0) && (mStatredCount <= 0)) {
try {
mMediaMuxer.stop();
} catch (final Exception e) {
Log.w(TAG, e);
}
mIsStarted = false;
if (DEBUG) Log.v(TAG, "MediaMuxer stopped:");
}
}
/**
* assign encoder to muxer
* @param format
* @return minus value indicate error
*/
/*package*/ synchronized int addTrack(final MediaFormat format) {
if (mIsStarted)
throw new IllegalStateException("muxer already started");
final int trackIx = mMediaMuxer.addTrack(format);
if (DEBUG) Log.i(TAG, "addTrack:trackNum=" + mEncoderCount + ",trackIx=" + trackIx + ",format=" + format);
return trackIx;
}
/**
* write encoded data to muxer
* @param trackIndex
* @param byteBuf
* @param bufferInfo
*/
/*package*/ synchronized void writeSampleData(final int trackIndex, final ByteBuffer byteBuf, final MediaCodec.BufferInfo bufferInfo) {
if (mStatredCount > 0)
mMediaMuxer.writeSampleData(trackIndex, byteBuf, bufferInfo);
}
//**********************************************************************
//**********************************************************************
/**
* generate output file
* @param type Environment.DIRECTORY_MOVIES / Environment.DIRECTORY_DCIM etc.
* @param ext .mp4(.m4a for audio) or .png
* @return return null when this app has no writing permission to external storage.
*/
public static final File getCaptureFile(final String type, final String ext) {
final File dir = new File(Environment.getExternalStoragePublicDirectory(type), DIR_NAME);
Log.d(TAG, "path=" + dir.toString());
dir.mkdirs();
if (dir.canWrite()) {
return new File(dir, getDateTimeString() + ext);
}
return null;
}
/**
* get current date and time as String
* @return
*/
private static final String getDateTimeString() {
final GregorianCalendar now = new GregorianCalendar();
return mDateTimeFormat.format(now.getTime());
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/MediaSurfaceEncoder.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
import java.io.IOException;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.util.Log;
import android.view.Surface;
public class MediaSurfaceEncoder extends MediaEncoder implements IVideoEncoder {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "MediaSurfaceEncoder";
private static final String MIME_TYPE = "video/avc";
// parameters for recording
private final int mWidth, mHeight;
private static final int FRAME_RATE = 15;
private static final float BPP = 0.50f;
private Surface mSurface;
public MediaSurfaceEncoder(final MediaMuxerWrapper muxer, final int width, final int height, final MediaEncoderListener listener) {
super(muxer, listener);
if (DEBUG) Log.i(TAG, "MediaVideoEncoder: ");
mWidth = width;
mHeight = height;
}
/**
* Returns the encoder's input surface.
*/
public Surface getInputSurface() {
return mSurface;
}
@Override
protected void prepare() throws IOException {
if (DEBUG) Log.i(TAG, "prepare: ");
mTrackIndex = -1;
mMuxerStarted = mIsEOS = false;
final MediaCodecInfo videoCodecInfo = selectVideoCodec(MIME_TYPE);
if (videoCodecInfo == null) {
Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE);
return;
}
if (DEBUG) Log.i(TAG, "selected codec: " + videoCodecInfo.getName());
final MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); // API >= 18
format.setInteger(MediaFormat.KEY_BIT_RATE, calcBitRate());
format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10);
if (DEBUG) Log.i(TAG, "format: " + format);
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
// get Surface for encoder input
// this method only can call between #configure and #start
mSurface = mMediaCodec.createInputSurface(); // API >= 18
mMediaCodec.start();
if (DEBUG) Log.i(TAG, "prepare finishing");
if (mListener != null) {
try {
mListener.onPrepared(this);
} catch (final Exception e) {
Log.e(TAG, "prepare:", e);
}
}
}
@Override
protected void release() {
if (DEBUG) Log.i(TAG, "release:");
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
super.release();
}
private int calcBitRate() {
final int bitrate = (int)(BPP * FRAME_RATE * mWidth * mHeight);
Log.i(TAG, String.format("bitrate=%5.2f[Mbps]", bitrate / 1024f / 1024f));
return bitrate;
}
/**
* select the first codec that match a specific MIME type
* @param mimeType
* @return null if no codec matched
*/
protected static final MediaCodecInfo selectVideoCodec(final String mimeType) {
if (DEBUG) Log.v(TAG, "selectVideoCodec:");
// get the list of available codecs
final int numCodecs = MediaCodecList.getCodecCount();
for (int i = 0; i < numCodecs; i++) {
final MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (!codecInfo.isEncoder()) { // skipp decoder
continue;
}
// select first codec that match a specific MIME type and color format
final String[] types = codecInfo.getSupportedTypes();
for (int j = 0; j < types.length; j++) {
if (types[j].equalsIgnoreCase(mimeType)) {
if (DEBUG) Log.i(TAG, "codec:" + codecInfo.getName() + ",MIME=" + types[j]);
final int format = selectColorFormat(codecInfo, mimeType);
if (format > 0) {
return codecInfo;
}
}
}
}
return null;
}
/**
* select color format available on specific codec and we can use.
* @return 0 if no colorFormat is matched
*/
protected static final int selectColorFormat(final MediaCodecInfo codecInfo, final String mimeType) {
if (DEBUG) Log.i(TAG, "selectColorFormat: ");
int result = 0;
final MediaCodecInfo.CodecCapabilities caps;
try {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
caps = codecInfo.getCapabilitiesForType(mimeType);
} finally {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
int colorFormat;
for (int i = 0; i < caps.colorFormats.length; i++) {
colorFormat = caps.colorFormats[i];
if (isRecognizedVideoFormat(colorFormat)) {
if (result == 0)
result = colorFormat;
break;
}
}
if (result == 0)
Log.e(TAG, "couldn't find a good color format for " + codecInfo.getName() + " / " + mimeType);
return result;
}
/**
* color formats that we can use in this class
*/
protected static int[] recognizedFormats;
static {
recognizedFormats = new int[] {
// MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar,
// MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
// MediaCodecInfo.CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,
};
}
private static final boolean isRecognizedVideoFormat(final int colorFormat) {
if (DEBUG) Log.i(TAG, "isRecognizedVideoFormat:colorFormat=" + colorFormat);
final int n = recognizedFormats != null ? recognizedFormats.length : 0;
for (int i = 0; i < n; i++) {
if (recognizedFormats[i] == colorFormat) {
return true;
}
}
return false;
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/MediaVideoBufferEncoder.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
import java.io.IOException;
import java.nio.ByteBuffer;
import android.annotation.TargetApi;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.util.Log;
/**
* This class receives video images as ByteBuffer(strongly recommend direct ByteBuffer) as NV21(YUV420SP)
* and encode them to h.264.
* If you use this directly with IFrameCallback, you should know UVCCamera and it backend native libraries
* never execute color space conversion. This means that color tone of resulted movie will be different
* from that you expected/can see on screen.
*/
public class MediaVideoBufferEncoder extends MediaEncoder implements IVideoEncoder {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "MediaVideoBufferEncoder";
private static final String MIME_TYPE = "video/avc";
// parameters for recording
private static final int FRAME_RATE = 15;
private static final float BPP = 0.50f;
private final int mWidth, mHeight;
protected int mColorFormat;
public MediaVideoBufferEncoder(final MediaMuxerWrapper muxer, final int width, final int height, final MediaEncoderListener listener) {
super(muxer, listener);
if (DEBUG) Log.i(TAG, "MediaVideoEncoder: ");
mWidth = width;
mHeight = height;
}
public void encode(final ByteBuffer buffer) {
// if (DEBUG) Log.v(TAG, "encode:buffer=" + buffer);
synchronized (mSync) {
if (!mIsCapturing || mRequestStop) return;
}
encode(buffer, buffer.capacity(), getPTSUs());
}
@Override
protected void prepare() throws IOException {
if (DEBUG) Log.i(TAG, "prepare: ");
mTrackIndex = -1;
mMuxerStarted = mIsEOS = false;
final MediaCodecInfo videoCodecInfo = selectVideoCodec(MIME_TYPE);
if (videoCodecInfo == null) {
Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE);
return;
}
if (DEBUG) Log.i(TAG, "selected codec: " + videoCodecInfo.getName());
final MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, mColorFormat);
format.setInteger(MediaFormat.KEY_BIT_RATE, calcBitRate());
format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10);
if (DEBUG) Log.i(TAG, "format: " + format);
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
if (DEBUG) Log.i(TAG, "prepare finishing");
if (mListener != null) {
try {
mListener.onPrepared(this);
} catch (final Exception e) {
Log.e(TAG, "prepare:", e);
}
}
}
private int calcBitRate() {
final int bitrate = (int)(BPP * FRAME_RATE * mWidth * mHeight);
Log.i(TAG, String.format("bitrate=%5.2f[Mbps]", bitrate / 1024f / 1024f));
return bitrate;
}
/**
* select the first codec that match a specific MIME type
* @param mimeType
* @return null if no codec matched
*/
@SuppressWarnings("deprecation")
protected final MediaCodecInfo selectVideoCodec(final String mimeType) {
if (DEBUG) Log.v(TAG, "selectVideoCodec:");
// get the list of available codecs
final int numCodecs = MediaCodecList.getCodecCount();
for (int i = 0; i < numCodecs; i++) {
final MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (!codecInfo.isEncoder()) { // skipp decoder
continue;
}
// select first codec that match a specific MIME type and color format
final String[] types = codecInfo.getSupportedTypes();
for (int j = 0; j < types.length; j++) {
if (types[j].equalsIgnoreCase(mimeType)) {
if (DEBUG) Log.i(TAG, "codec:" + codecInfo.getName() + ",MIME=" + types[j]);
final int format = selectColorFormat(codecInfo, mimeType);
if (format > 0) {
mColorFormat = format;
return codecInfo;
}
}
}
}
return null;
}
/**
* select color format available on specific codec and we can use.
* @return 0 if no colorFormat is matched
*/
protected static final int selectColorFormat(final MediaCodecInfo codecInfo, final String mimeType) {
if (DEBUG) Log.i(TAG, "selectColorFormat: ");
int result = 0;
final MediaCodecInfo.CodecCapabilities caps;
try {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
caps = codecInfo.getCapabilitiesForType(mimeType);
} finally {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
int colorFormat;
for (int i = 0; i < caps.colorFormats.length; i++) {
colorFormat = caps.colorFormats[i];
if (isRecognizedViewoFormat(colorFormat)) {
if (result == 0)
result = colorFormat;
break;
}
}
if (result == 0)
Log.e(TAG, "couldn't find a good color format for " + codecInfo.getName() + " / " + mimeType);
return result;
}
/**
* color formats that we can use in this class
*/
protected static int[] recognizedFormats;
static {
recognizedFormats = new int[] {
// MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar,
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
MediaCodecInfo.CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
// MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,
};
}
private static final boolean isRecognizedViewoFormat(final int colorFormat) {
if (DEBUG) Log.i(TAG, "isRecognizedViewoFormat:colorFormat=" + colorFormat);
final int n = recognizedFormats != null ? recognizedFormats.length : 0;
for (int i = 0; i < n; i++) {
if (recognizedFormats[i] == colorFormat) {
return true;
}
}
return false;
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/encoder/MediaVideoEncoder.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.encoder;
import java.io.IOException;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.util.Log;
import android.view.Surface;
import com.serenegiant.glutils.EGLBase;
import com.serenegiant.glutils.RenderHandler;
/**
* Encode texture images as H.264 video
* using MediaCodec.
* This class render texture images into recording surface
* camera from MediaCodec encoder using Open GL|ES
*/
public class MediaVideoEncoder extends MediaEncoder implements IVideoEncoder {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "MediaVideoEncoder";
private static final String MIME_TYPE = "video/avc";
// parameters for recording
private final int mWidth, mHeight;
private static final int FRAME_RATE = 15;
private static final float BPP = 0.50f;
private RenderHandler mRenderHandler;
private Surface mSurface;
public MediaVideoEncoder(final MediaMuxerWrapper muxer, final int width, final int height, final MediaEncoderListener listener) {
super(muxer, listener);
if (DEBUG) Log.i(TAG, "MediaVideoEncoder: ");
mRenderHandler = RenderHandler.createHandler(TAG);
mWidth = width;
mHeight = height;
}
public boolean frameAvailableSoon(final float[] tex_matrix) {
boolean result;
if (result = super.frameAvailableSoon())
mRenderHandler.draw(tex_matrix);
return result;
}
/**
* This method does not work correctly on this class,
* use #frameAvailableSoon(final float[]) instead
* @return
*/
@Override
public boolean frameAvailableSoon() {
boolean result;
if (result = super.frameAvailableSoon())
mRenderHandler.draw(null);
return result;
}
@Override
protected void prepare() throws IOException {
if (DEBUG) Log.i(TAG, "prepare: ");
mTrackIndex = -1;
mMuxerStarted = mIsEOS = false;
final MediaCodecInfo videoCodecInfo = selectVideoCodec(MIME_TYPE);
if (videoCodecInfo == null) {
Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE);
return;
}
if (DEBUG) Log.i(TAG, "selected codec: " + videoCodecInfo.getName());
final MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); // API >= 18
format.setInteger(MediaFormat.KEY_BIT_RATE, calcBitRate());
format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10);
if (DEBUG) Log.i(TAG, "format: " + format);
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
// get Surface for encoder input
// this method only can call between #configure and #start
mSurface = mMediaCodec.createInputSurface(); // API >= 18
mMediaCodec.start();
if (DEBUG) Log.i(TAG, "prepare finishing");
if (mListener != null) {
try {
mListener.onPrepared(this);
} catch (final Exception e) {
Log.e(TAG, "prepare:", e);
}
}
}
public void setEglContext(final EGLBase.IContext sharedContext, final int tex_id) {
mRenderHandler.setEglContext(sharedContext, tex_id, mSurface, true);
}
@Override
protected void release() {
if (DEBUG) Log.i(TAG, "release:");
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
if (mRenderHandler != null) {
mRenderHandler.release();
mRenderHandler = null;
}
super.release();
}
private int calcBitRate() {
final int bitrate = (int)(BPP * FRAME_RATE * mWidth * mHeight);
Log.i(TAG, String.format("bitrate=%5.2f[Mbps]", bitrate / 1024f / 1024f));
return bitrate;
}
/**
* select the first codec that match a specific MIME type
* @param mimeType
* @return null if no codec matched
*/
protected static final MediaCodecInfo selectVideoCodec(final String mimeType) {
if (DEBUG) Log.v(TAG, "selectVideoCodec:");
// get the list of available codecs
final int numCodecs = MediaCodecList.getCodecCount();
for (int i = 0; i < numCodecs; i++) {
final MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (!codecInfo.isEncoder()) { // skipp decoder
continue;
}
// select first codec that match a specific MIME type and color format
final String[] types = codecInfo.getSupportedTypes();
for (int j = 0; j < types.length; j++) {
if (types[j].equalsIgnoreCase(mimeType)) {
if (DEBUG) Log.i(TAG, "codec:" + codecInfo.getName() + ",MIME=" + types[j]);
final int format = selectColorFormat(codecInfo, mimeType);
if (format > 0) {
return codecInfo;
}
}
}
}
return null;
}
/**
* select color format available on specific codec and we can use.
* @return 0 if no colorFormat is matched
*/
protected static final int selectColorFormat(final MediaCodecInfo codecInfo, final String mimeType) {
if (DEBUG) Log.i(TAG, "selectColorFormat: ");
int result = 0;
final MediaCodecInfo.CodecCapabilities caps;
try {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
caps = codecInfo.getCapabilitiesForType(mimeType);
} finally {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
int colorFormat;
for (int i = 0; i < caps.colorFormats.length; i++) {
colorFormat = caps.colorFormats[i];
if (isRecognizedVideoFormat(colorFormat)) {
if (result == 0)
result = colorFormat;
break;
}
}
if (result == 0)
Log.e(TAG, "couldn't find a good color format for " + codecInfo.getName() + " / " + mimeType);
return result;
}
/**
* color formats that we can use in this class
*/
protected static int[] recognizedFormats;
static {
recognizedFormats = new int[] {
// MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar,
// MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
// MediaCodecInfo.CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,
};
}
private static final boolean isRecognizedVideoFormat(final int colorFormat) {
if (DEBUG) Log.i(TAG, "isRecognizedVideoFormat:colorFormat=" + colorFormat);
final int n = recognizedFormats != null ? recognizedFormats.length : 0;
for (int i = 0; i < n; i++) {
if (recognizedFormats[i] == colorFormat) {
return true;
}
}
return false;
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/usbcameracommon/AbstractUVCCameraHandler.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usbcameracommon;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.media.AudioManager;
import android.media.MediaScannerConnection;
import android.media.SoundPool;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.serenegiant.encoder.MediaAudioEncoder;
import com.serenegiant.encoder.MediaEncoder;
import com.serenegiant.encoder.MediaMuxerWrapper;
import com.serenegiant.encoder.MediaSurfaceEncoder;
import com.serenegiant.encoder.MediaVideoBufferEncoder;
import com.serenegiant.encoder.MediaVideoEncoder;
import com.serenegiant.usb.IFrameCallback;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;
import com.serenegiant.widget.CameraViewInterface;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
abstract class AbstractUVCCameraHandler extends Handler {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "AbsUVCCameraHandler";
public interface CameraCallback {
public void onOpen();
public void onClose();
public void onStartPreview();
public void onStopPreview();
public void onStartRecording();
public void onStopRecording();
public void onError(final Exception e);
}
private static final int MSG_OPEN = 0;
private static final int MSG_CLOSE = 1;
private static final int MSG_PREVIEW_START = 2;
private static final int MSG_PREVIEW_STOP = 3;
private static final int MSG_CAPTURE_STILL = 4;
private static final int MSG_CAPTURE_START = 5;
private static final int MSG_CAPTURE_STOP = 6;
private static final int MSG_MEDIA_UPDATE = 7;
private static final int MSG_RELEASE = 9;
private final WeakReference<AbstractUVCCameraHandler.CameraThread> mWeakThread;
private volatile boolean mReleased;
protected AbstractUVCCameraHandler(final CameraThread thread) {
mWeakThread = new WeakReference<CameraThread>(thread);
}
public int getWidth() {
final CameraThread thread = mWeakThread.get();
return thread != null ? thread.getWidth() : 0;
}
public int getHeight() {
final CameraThread thread = mWeakThread.get();
return thread != null ? thread.getHeight() : 0;
}
public boolean isOpened() {
final CameraThread thread = mWeakThread.get();
return thread != null && thread.isCameraOpened();
}
public boolean isPreviewing() {
final CameraThread thread = mWeakThread.get();
return thread != null && thread.isPreviewing();
}
public boolean isRecording() {
final CameraThread thread = mWeakThread.get();
return thread != null && thread.isRecording();
}
public boolean isEqual(final UsbDevice device) {
final CameraThread thread = mWeakThread.get();
return (thread != null) && thread.isEqual(device);
}
protected boolean isCameraThread() {
final CameraThread thread = mWeakThread.get();
return thread != null && (thread.getId() == Thread.currentThread().getId());
}
protected boolean isReleased() {
final CameraThread thread = mWeakThread.get();
return mReleased || (thread == null);
}
protected void checkReleased() {
if (isReleased()) {
throw new IllegalStateException("already released");
}
}
public void open(final USBMonitor.UsbControlBlock ctrlBlock) {
checkReleased();
sendMessage(obtainMessage(MSG_OPEN, ctrlBlock));
}
public void close() {
if (DEBUG) Log.v(TAG, "close:");
if (isOpened()) {
stopPreview();
sendEmptyMessage(MSG_CLOSE);
}
if (DEBUG) Log.v(TAG, "close:finished");
}
public void resize(final int width, final int height) {
checkReleased();
throw new UnsupportedOperationException("does not support now");
}
protected void startPreview(final Object surface) {
checkReleased();
if (!((surface instanceof SurfaceHolder) || (surface instanceof Surface) || (surface instanceof SurfaceTexture))) {
throw new IllegalArgumentException("surface should be one of SurfaceHolder, Surface or SurfaceTexture");
}
sendMessage(obtainMessage(MSG_PREVIEW_START, surface));
}
public void stopPreview() {
if (DEBUG) Log.v(TAG, "stopPreview:");
removeMessages(MSG_PREVIEW_START);
stopRecording();
if (isPreviewing()) {
final CameraThread thread = mWeakThread.get();
if (thread == null) return;
synchronized (thread.mSync) {
sendEmptyMessage(MSG_PREVIEW_STOP);
if (!isCameraThread()) {
// wait for actually preview stopped to avoid releasing Surface/SurfaceTexture
// while preview is still running.
// therefore this method will take a time to execute
try {
thread.mSync.wait();
} catch (final InterruptedException e) {
}
}
}
}
if (DEBUG) Log.v(TAG, "stopPreview:finished");
}
protected void captureStill() {
checkReleased();
sendEmptyMessage(MSG_CAPTURE_STILL);
}
protected void captureStill(final String path) {
checkReleased();
sendMessage(obtainMessage(MSG_CAPTURE_STILL, path));
}
public void startRecording() {
checkReleased();
sendEmptyMessage(MSG_CAPTURE_START);
}
public void stopRecording() {
sendEmptyMessage(MSG_CAPTURE_STOP);
}
public void release() {
mReleased = true;
close();
sendEmptyMessage(MSG_RELEASE);
}
public void addCallback(final CameraCallback callback) {
checkReleased();
if (!mReleased && (callback != null)) {
final CameraThread thread = mWeakThread.get();
if (thread != null) {
thread.mCallbacks.add(callback);
}
}
}
public void removeCallback(final CameraCallback callback) {
if (callback != null) {
final CameraThread thread = mWeakThread.get();
if (thread != null) {
thread.mCallbacks.remove(callback);
}
}
}
protected void updateMedia(final String path) {
sendMessage(obtainMessage(MSG_MEDIA_UPDATE, path));
}
public boolean checkSupportFlag(final long flag) {
checkReleased();
final CameraThread thread = mWeakThread.get();
return thread != null && thread.mUVCCamera != null && thread.mUVCCamera.checkSupportFlag(flag);
}
public int getValue(final int flag) {
checkReleased();
final CameraThread thread = mWeakThread.get();
final UVCCamera camera = thread != null ? thread.mUVCCamera : null;
if (camera != null) {
if (flag == UVCCamera.PU_BRIGHTNESS) {
return camera.getBrightness();
} else if (flag == UVCCamera.PU_CONTRAST) {
return camera.getContrast();
}
}
throw new IllegalStateException();
}
public int setValue(final int flag, final int value) {
checkReleased();
final CameraThread thread = mWeakThread.get();
final UVCCamera camera = thread != null ? thread.mUVCCamera : null;
if (camera != null) {
if (flag == UVCCamera.PU_BRIGHTNESS) {
camera.setBrightness(value);
return camera.getBrightness();
} else if (flag == UVCCamera.PU_CONTRAST) {
camera.setContrast(value);
return camera.getContrast();
}
}
throw new IllegalStateException();
}
public int resetValue(final int flag) {
checkReleased();
final CameraThread thread = mWeakThread.get();
final UVCCamera camera = thread != null ? thread.mUVCCamera : null;
if (camera != null) {
if (flag == UVCCamera.PU_BRIGHTNESS) {
camera.resetBrightness();
return camera.getBrightness();
} else if (flag == UVCCamera.PU_CONTRAST) {
camera.resetContrast();
return camera.getContrast();
}
}
throw new IllegalStateException();
}
@Override
public void handleMessage(final Message msg) {
final CameraThread thread = mWeakThread.get();
if (thread == null) return;
switch (msg.what) {
case MSG_OPEN:
thread.handleOpen((USBMonitor.UsbControlBlock)msg.obj);
break;
case MSG_CLOSE:
thread.handleClose();
break;
case MSG_PREVIEW_START:
thread.handleStartPreview(msg.obj);
break;
case MSG_PREVIEW_STOP:
thread.handleStopPreview();
break;
case MSG_CAPTURE_STILL:
thread.handleCaptureStill((String)msg.obj);
break;
case MSG_CAPTURE_START:
thread.handleStartRecording();
break;
case MSG_CAPTURE_STOP:
thread.handleStopRecording();
break;
case MSG_MEDIA_UPDATE:
thread.handleUpdateMedia((String)msg.obj);
break;
case MSG_RELEASE:
thread.handleRelease();
break;
default:
throw new RuntimeException("unsupported message:what=" + msg.what);
}
}
static final class CameraThread extends Thread {
private static final String TAG_THREAD = "CameraThread";
private final Object mSync = new Object();
private final Class<? extends AbstractUVCCameraHandler> mHandlerClass;
private final WeakReference<Activity> mWeakParent;
private final WeakReference<CameraViewInterface> mWeakCameraView;
private final int mEncoderType;
private final Set<CameraCallback> mCallbacks = new CopyOnWriteArraySet<CameraCallback>();
private int mWidth, mHeight, mPreviewMode;
private float mBandwidthFactor;
private boolean mIsPreviewing;
private boolean mIsRecording;
/**
* shutter sound
*/
private SoundPool mSoundPool;
private int mSoundId;
private AbstractUVCCameraHandler mHandler;
/**
* for accessing UVC camera
*/
private UVCCamera mUVCCamera;
/**
* muxer for audio/video recording
*/
private MediaMuxerWrapper mMuxer;
private MediaVideoBufferEncoder mVideoEncoder;
/**
*
* @param clazz Class extends AbstractUVCCameraHandler
* @param parent parent Activity
* @param cameraView for still capturing
* @param encoderType 0: use MediaSurfaceEncoder, 1: use MediaVideoEncoder, 2: use MediaVideoBufferEncoder
* @param width
* @param height
* @param format either FRAME_FORMAT_YUYV(0) or FRAME_FORMAT_MJPEG(1)
* @param bandwidthFactor
*/
CameraThread(final Class<? extends AbstractUVCCameraHandler> clazz,
final Activity parent, final CameraViewInterface cameraView,
final int encoderType, final int width, final int height, final int format,
final float bandwidthFactor) {
super("CameraThread");
mHandlerClass = clazz;
mEncoderType = encoderType;
mWidth = width;
mHeight = height;
mPreviewMode = format;
mBandwidthFactor = bandwidthFactor;
mWeakParent = new WeakReference<Activity>(parent);
mWeakCameraView = new WeakReference<CameraViewInterface>(cameraView);
loadShutterSound(parent);
}
@Override
protected void finalize() throws Throwable {
Log.i(TAG, "CameraThread#finalize");
super.finalize();
}
public AbstractUVCCameraHandler getHandler() {
if (DEBUG) Log.v(TAG_THREAD, "getHandler:");
synchronized (mSync) {
if (mHandler == null)
try {
mSync.wait();
} catch (final InterruptedException e) {
}
}
return mHandler;
}
public int getWidth() {
synchronized (mSync) {
return mWidth;
}
}
public int getHeight() {
synchronized (mSync) {
return mHeight;
}
}
public boolean isCameraOpened() {
synchronized (mSync) {
return mUVCCamera != null;
}
}
public boolean isPreviewing() {
synchronized (mSync) {
return mUVCCamera != null && mIsPreviewing;
}
}
public boolean isRecording() {
synchronized (mSync) {
return (mUVCCamera != null) && (mMuxer != null);
}
}
public boolean isEqual(final UsbDevice device) {
return (mUVCCamera != null) && (mUVCCamera.getDevice() != null) && mUVCCamera.getDevice().equals(device);
}
public void handleOpen(final USBMonitor.UsbControlBlock ctrlBlock) {
if (DEBUG) Log.v(TAG_THREAD, "handleOpen:");
handleClose();
try {
final UVCCamera camera = new UVCCamera();
camera.open(ctrlBlock);
synchronized (mSync) {
mUVCCamera = camera;
}
callOnOpen();
} catch (final Exception e) {
callOnError(e);
}
if (DEBUG) Log.i(TAG, "supportedSize:" + (mUVCCamera != null ? mUVCCamera.getSupportedSize() : null));
}
public void handleClose() {
if (DEBUG) Log.v(TAG_THREAD, "handleClose:");
handleStopRecording();
final UVCCamera camera;
synchronized (mSync) {
camera = mUVCCamera;
mUVCCamera = null;
}
if (camera != null) {
camera.stopPreview();
camera.destroy();
callOnClose();
}
}
public void handleStartPreview(final Object surface) {
if (DEBUG) Log.v(TAG_THREAD, "handleStartPreview:");
if ((mUVCCamera == null) || mIsPreviewing) return;
try {
mUVCCamera.setPreviewSize(mWidth, mHeight, 1, 31, mPreviewMode, mBandwidthFactor);
} catch (final IllegalArgumentException e) {
try {
// fallback to YUV mode
mUVCCamera.setPreviewSize(mWidth, mHeight, 1, 31, UVCCamera.DEFAULT_PREVIEW_MODE, mBandwidthFactor);
} catch (final IllegalArgumentException e1) {
callOnError(e1);
return;
}
}
if (surface instanceof SurfaceHolder) {
mUVCCamera.setPreviewDisplay((SurfaceHolder)surface);
} if (surface instanceof Surface) {
mUVCCamera.setPreviewDisplay((Surface)surface);
} else {
mUVCCamera.setPreviewTexture((SurfaceTexture)surface);
}
mUVCCamera.startPreview();
mUVCCamera.updateCameraParams();
synchronized (mSync) {
mIsPreviewing = true;
}
callOnStartPreview();
}
public void handleStopPreview() {
if (DEBUG) Log.v(TAG_THREAD, "handleStopPreview:");
if (mIsPreviewing) {
if (mUVCCamera != null) {
mUVCCamera.stopPreview();
}
synchronized (mSync) {
mIsPreviewing = false;
mSync.notifyAll();
}
callOnStopPreview();
}
if (DEBUG) Log.v(TAG_THREAD, "handleStopPreview:finished");
}
public void handleCaptureStill(final String path) {
if (DEBUG) Log.v(TAG_THREAD, "handleCaptureStill:");
final Activity parent = mWeakParent.get();
if (parent == null) return;
mSoundPool.play(mSoundId, 0.2f, 0.2f, 0, 0, 1.0f); // play shutter sound
try {
final Bitmap bitmap = mWeakCameraView.get().captureStillImage();
// get buffered output stream for saving a captured still image as a file on external storage.
// the file name is came from current time.
// You should use extension name as same as CompressFormat when calling Bitmap#compress.
final File outputFile = TextUtils.isEmpty(path)
? MediaMuxerWrapper.getCaptureFile(Environment.DIRECTORY_DCIM, ".png")
: new File(path);
final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
mHandler.sendMessage(mHandler.obtainMessage(MSG_MEDIA_UPDATE, outputFile.getPath()));
} catch (final IOException e) {
}
} finally {
os.close();
}
} catch (final Exception e) {
callOnError(e);
}
}
public void handleStartRecording() {
if (DEBUG) Log.v(TAG_THREAD, "handleStartRecording:");
try {
if ((mUVCCamera == null) || (mMuxer != null)) return;
final MediaMuxerWrapper muxer = new MediaMuxerWrapper(".mp4"); // if you record audio only, ".m4a" is also OK.
MediaVideoBufferEncoder videoEncoder = null;
switch (mEncoderType) {
case 1: // for video capturing using MediaVideoEncoder
new MediaVideoEncoder(muxer, getWidth(), getHeight(), mMediaEncoderListener);
break;
case 2: // for video capturing using MediaVideoBufferEncoder
videoEncoder = new MediaVideoBufferEncoder(muxer, getWidth(), getHeight(), mMediaEncoderListener);
break;
// case 0: // for video capturing using MediaSurfaceEncoder
default:
new MediaSurfaceEncoder(muxer, getWidth(), getHeight(), mMediaEncoderListener);
break;
}
if (true) {
// for audio capturing
new MediaAudioEncoder(muxer, mMediaEncoderListener);
}
muxer.prepare();
muxer.startRecording();
if (videoEncoder != null) {
mUVCCamera.setFrameCallback(mIFrameCallback, UVCCamera.PIXEL_FORMAT_NV21);
}
synchronized (mSync) {
mMuxer = muxer;
mVideoEncoder = videoEncoder;
}
callOnStartRecording();
} catch (final IOException e) {
callOnError(e);
Log.e(TAG, "startCapture:", e);
}
}
public void handleStopRecording() {
if (DEBUG) Log.v(TAG_THREAD, "handleStopRecording:mMuxer=" + mMuxer);
final MediaMuxerWrapper muxer;
synchronized (mSync) {
muxer = mMuxer;
mMuxer = null;
mVideoEncoder = null;
if (mUVCCamera != null) {
mUVCCamera.stopCapture();
}
}
try {
mWeakCameraView.get().setVideoEncoder(null);
} catch (final Exception e) {
// ignore
}
if (muxer != null) {
muxer.stopRecording();
mUVCCamera.setFrameCallback(null, 0);
// you should not wait here
callOnStopRecording();
}
}
private final IFrameCallback mIFrameCallback = new IFrameCallback() {
@Override
public void onFrame(final ByteBuffer frame) {
final MediaVideoBufferEncoder videoEncoder;
synchronized (mSync) {
videoEncoder = mVideoEncoder;
}
if (videoEncoder != null) {
videoEncoder.frameAvailableSoon();
videoEncoder.encode(frame);
}
}
};
public void handleUpdateMedia(final String path) {
if (DEBUG) Log.v(TAG_THREAD, "handleUpdateMedia:path=" + path);
final Activity parent = mWeakParent.get();
final boolean released = (mHandler == null) || mHandler.mReleased;
if (parent != null && parent.getApplicationContext() != null) {
try {
if (DEBUG) Log.i(TAG, "MediaScannerConnection#scanFile");
MediaScannerConnection.scanFile(parent.getApplicationContext(), new String[]{ path }, null, null);
} catch (final Exception e) {
Log.e(TAG, "handleUpdateMedia:", e);
}
if (released || parent.isDestroyed())
handleRelease();
} else {
Log.w(TAG, "MainActivity already destroyed");
// give up to add this movie to MediaStore now.
// Seeing this movie on Gallery app etc. will take a lot of time.
handleRelease();
}
}
public void handleRelease() {
if (DEBUG) Log.v(TAG_THREAD, "handleRelease:mIsRecording=" + mIsRecording);
handleClose();
mCallbacks.clear();
if (!mIsRecording) {
mHandler.mReleased = true;
Looper.myLooper().quit();
}
if (DEBUG) Log.v(TAG_THREAD, "handleRelease:finished");
}
private final MediaEncoder.MediaEncoderListener mMediaEncoderListener = new MediaEncoder.MediaEncoderListener() {
@Override
public void onPrepared(final MediaEncoder encoder) {
if (DEBUG) Log.v(TAG, "onPrepared:encoder=" + encoder);
mIsRecording = true;
if (encoder instanceof MediaVideoEncoder)
try {
mWeakCameraView.get().setVideoEncoder((MediaVideoEncoder)encoder);
} catch (final Exception e) {
Log.e(TAG, "onPrepared:", e);
}
if (encoder instanceof MediaSurfaceEncoder)
try {
mWeakCameraView.get().setVideoEncoder((MediaSurfaceEncoder)encoder);
mUVCCamera.startCapture(((MediaSurfaceEncoder)encoder).getInputSurface());
} catch (final Exception e) {
Log.e(TAG, "onPrepared:", e);
}
}
@Override
public void onStopped(final MediaEncoder encoder) {
if (DEBUG) Log.v(TAG_THREAD, "onStopped:encoder=" + encoder);
if ((encoder instanceof MediaVideoEncoder)
|| (encoder instanceof MediaSurfaceEncoder))
try {
mIsRecording = false;
final Activity parent = mWeakParent.get();
mWeakCameraView.get().setVideoEncoder(null);
synchronized (mSync) {
if (mUVCCamera != null) {
mUVCCamera.stopCapture();
}
}
final String path = encoder.getOutputPath();
if (!TextUtils.isEmpty(path)) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_MEDIA_UPDATE, path), 1000);
} else {
final boolean released = (mHandler == null) || mHandler.mReleased;
if (released || parent == null || parent.isDestroyed()) {
handleRelease();
}
}
} catch (final Exception e) {
Log.e(TAG, "onPrepared:", e);
}
}
};
/**
* prepare and load shutter sound for still image capturing
*/
@SuppressWarnings("deprecation")
private void loadShutterSound(final Context context) {
// get system stream type using reflection
int streamType;
try {
final Class<?> audioSystemClass = Class.forName("android.media.AudioSystem");
final Field sseField = audioSystemClass.getDeclaredField("STREAM_SYSTEM_ENFORCED");
streamType = sseField.getInt(null);
} catch (final Exception e) {
streamType = AudioManager.STREAM_SYSTEM; // set appropriate according to your app policy
}
if (mSoundPool != null) {
try {
mSoundPool.release();
} catch (final Exception e) {
}
mSoundPool = null;
}
// load shutter sound from resource
mSoundPool = new SoundPool(2, streamType, 0);
mSoundId = mSoundPool.load(context, R.raw.camera_click, 1);
}
@Override
public void run() {
Looper.prepare();
AbstractUVCCameraHandler handler = null;
try {
final Constructor<? extends AbstractUVCCameraHandler> constructor = mHandlerClass.getDeclaredConstructor(CameraThread.class);
handler = constructor.newInstance(this);
} catch (final NoSuchMethodException e) {
Log.w(TAG, e);
} catch (final IllegalAccessException e) {
Log.w(TAG, e);
} catch (final InstantiationException e) {
Log.w(TAG, e);
} catch (final InvocationTargetException e) {
Log.w(TAG, e);
}
if (handler != null) {
synchronized (mSync) {
mHandler = handler;
mSync.notifyAll();
}
Looper.loop();
if (mSoundPool != null) {
mSoundPool.release();
mSoundPool = null;
}
if (mHandler != null) {
mHandler.mReleased = true;
}
}
mCallbacks.clear();
synchronized (mSync) {
mHandler = null;
mSync.notifyAll();
}
}
private void callOnOpen() {
for (final CameraCallback callback: mCallbacks) {
try {
callback.onOpen();
} catch (final Exception e) {
mCallbacks.remove(callback);
Log.w(TAG, e);
}
}
}
private void callOnClose() {
for (final CameraCallback callback: mCallbacks) {
try {
callback.onClose();
} catch (final Exception e) {
mCallbacks.remove(callback);
Log.w(TAG, e);
}
}
}
private void callOnStartPreview() {
for (final CameraCallback callback: mCallbacks) {
try {
callback.onStartPreview();
} catch (final Exception e) {
mCallbacks.remove(callback);
Log.w(TAG, e);
}
}
}
private void callOnStopPreview() {
for (final CameraCallback callback: mCallbacks) {
try {
callback.onStopPreview();
} catch (final Exception e) {
mCallbacks.remove(callback);
Log.w(TAG, e);
}
}
}
private void callOnStartRecording() {
for (final CameraCallback callback: mCallbacks) {
try {
callback.onStartRecording();
} catch (final Exception e) {
mCallbacks.remove(callback);
Log.w(TAG, e);
}
}
}
private void callOnStopRecording() {
for (final CameraCallback callback: mCallbacks) {
try {
callback.onStopRecording();
} catch (final Exception e) {
mCallbacks.remove(callback);
Log.w(TAG, e);
}
}
}
private void callOnError(final Exception e) {
for (final CameraCallback callback: mCallbacks) {
try {
callback.onError(e);
} catch (final Exception e1) {
mCallbacks.remove(callback);
Log.w(TAG, e);
}
}
}
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/usbcameracommon/UVCCameraHandler.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usbcameracommon;
import android.app.Activity;
import com.serenegiant.usb.UVCCamera;
import com.serenegiant.widget.CameraViewInterface;
public class UVCCameraHandler extends AbstractUVCCameraHandler {
/**
* create UVCCameraHandler, use MediaVideoEncoder, try MJPEG, default bandwidth
* @param parent
* @param cameraView
* @param width
* @param height
* @return
*/
public static final UVCCameraHandler createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int width, final int height) {
return createHandler(parent, cameraView, 1, width, height, UVCCamera.FRAME_FORMAT_MJPEG, UVCCamera.DEFAULT_BANDWIDTH);
}
/**
* create UVCCameraHandler, use MediaVideoEncoder, try MJPEG
* @param parent
* @param cameraView
* @param width
* @param height
* @param bandwidthFactor
* @return
*/
public static final UVCCameraHandler createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int width, final int height, final float bandwidthFactor) {
return createHandler(parent, cameraView, 1, width, height, UVCCamera.FRAME_FORMAT_MJPEG, bandwidthFactor);
}
/**
* create UVCCameraHandler, try MJPEG, default bandwidth
* @param parent
* @param cameraView
* @param encoderType 0: use MediaSurfaceEncoder, 1: use MediaVideoEncoder, 2: use MediaVideoBufferEncoder
* @param width
* @param height
* @return
*/
public static final UVCCameraHandler createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int encoderType, final int width, final int height) {
return createHandler(parent, cameraView, encoderType, width, height, UVCCamera.FRAME_FORMAT_MJPEG, UVCCamera.DEFAULT_BANDWIDTH);
}
/**
* create UVCCameraHandler, default bandwidth
* @param parent
* @param cameraView
* @param encoderType 0: use MediaSurfaceEncoder, 1: use MediaVideoEncoder, 2: use MediaVideoBufferEncoder
* @param width
* @param height
* @param format either UVCCamera.FRAME_FORMAT_YUYV(0) or UVCCamera.FRAME_FORMAT_MJPEG(1)
* @return
*/
public static final UVCCameraHandler createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int encoderType, final int width, final int height, final int format) {
return createHandler(parent, cameraView, encoderType, width, height, format, UVCCamera.DEFAULT_BANDWIDTH);
}
/**
* create UVCCameraHandler
* @param parent
* @param cameraView
* @param encoderType 0: use MediaSurfaceEncoder, 1: use MediaVideoEncoder, 2: use MediaVideoBufferEncoder
* @param width
* @param height
* @param format either UVCCamera.FRAME_FORMAT_YUYV(0) or UVCCamera.FRAME_FORMAT_MJPEG(1)
* @param bandwidthFactor
* @return
*/
public static final UVCCameraHandler createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int encoderType, final int width, final int height, final int format, final float bandwidthFactor) {
final CameraThread thread = new CameraThread(UVCCameraHandler.class, parent, cameraView, encoderType, width, height, format, bandwidthFactor);
thread.start();
return (UVCCameraHandler)thread.getHandler();
}
protected UVCCameraHandler(final CameraThread thread) {
super(thread);
}
@Override
public void startPreview(final Object surface) {
super.startPreview(surface);
}
@Override
public void captureStill() {
super.captureStill();
}
@Override
public void captureStill(final String path) {
super.captureStill(path);
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/usbcameracommon/UVCCameraHandlerMultiSurface.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usbcameracommon;
import android.app.Activity;
import android.view.Surface;
import com.serenegiant.glutils.RendererHolder;
import com.serenegiant.usb.UVCCamera;
import com.serenegiant.widget.CameraViewInterface;
public class UVCCameraHandlerMultiSurface extends AbstractUVCCameraHandler {
/**
* create UVCCameraHandlerMultiSurface, use MediaVideoEncoder, try MJPEG, default bandwidth
* @param parent
* @param cameraView
* @param width
* @param height
* @return
*/
public static final UVCCameraHandlerMultiSurface createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int width, final int height) {
return createHandler(parent, cameraView, 1, width, height, UVCCamera.FRAME_FORMAT_MJPEG, UVCCamera.DEFAULT_BANDWIDTH);
}
/**
* create UVCCameraHandlerMultiSurface, use MediaVideoEncoder, try MJPEG
* @param parent
* @param cameraView
* @param width
* @param height
* @param bandwidthFactor
* @return
*/
public static final UVCCameraHandlerMultiSurface createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int width, final int height, final float bandwidthFactor) {
return createHandler(parent, cameraView, 1, width, height, UVCCamera.FRAME_FORMAT_MJPEG, bandwidthFactor);
}
/**
* create UVCCameraHandlerMultiSurface, try MJPEG, default bandwidth
* @param parent
* @param cameraView
* @param encoderType
* @param width
* @param height
* @return
*/
public static final UVCCameraHandlerMultiSurface createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int encoderType, final int width, final int height) {
return createHandler(parent, cameraView, encoderType, width, height, UVCCamera.FRAME_FORMAT_MJPEG, UVCCamera.DEFAULT_BANDWIDTH);
}
/**
* create UVCCameraHandlerMultiSurface, default bandwidth
* @param parent
* @param cameraView
* @param encoderType
* @param width
* @param height
* @param format
* @return
*/
public static final UVCCameraHandlerMultiSurface createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int encoderType, final int width, final int height, final int format) {
return createHandler(parent, cameraView, encoderType, width, height, format, UVCCamera.DEFAULT_BANDWIDTH);
}
/**
* create UVCCameraHandlerMultiSurface
* @param parent
* @param cameraView
* @param encoderType 0: use MediaSurfaceEncoder, 1: use MediaVideoEncoder, 2: use MediaVideoBufferEncoder
* @param width
* @param height
* @param format either UVCCamera.FRAME_FORMAT_YUYV(0) or UVCCamera.FRAME_FORMAT_MJPEG(1)
* @param bandwidthFactor
* @return
*/
public static final UVCCameraHandlerMultiSurface createHandler(
final Activity parent, final CameraViewInterface cameraView,
final int encoderType, final int width, final int height, final int format, final float bandwidthFactor) {
final CameraThread thread = new CameraThread(UVCCameraHandlerMultiSurface.class, parent, cameraView, encoderType, width, height, format, bandwidthFactor);
thread.start();
return (UVCCameraHandlerMultiSurface)thread.getHandler();
}
private RendererHolder mRendererHolder;
protected UVCCameraHandlerMultiSurface(final CameraThread thread) {
super(thread);
mRendererHolder = new RendererHolder(thread.getWidth(), thread.getHeight(), null);
}
public synchronized void release() {
if (mRendererHolder != null) {
mRendererHolder.release();
mRendererHolder = null;
}
super.release();
}
public synchronized void resize(final int width, final int height) {
super.resize(width, height);
if (mRendererHolder != null) {
mRendererHolder.resize(width, height);
}
}
public synchronized void startPreview() {
checkReleased();
if (mRendererHolder != null) {
super.startPreview(mRendererHolder.getSurface());
} else {
throw new IllegalStateException();
}
}
public synchronized void addSurface(final int surfaceId, final Surface surface, final boolean isRecordable) {
checkReleased();
mRendererHolder.addSurface(surfaceId, surface, isRecordable);
}
public synchronized void removeSurface(final int surfaceId) {
if (mRendererHolder != null) {
mRendererHolder.removeSurface(surfaceId);
}
}
@Override
public void captureStill() {
checkReleased();
super.captureStill();
}
@Override
public void captureStill(final String path) {
checkReleased();
post(new Runnable() {
@Override
public void run() {
synchronized (UVCCameraHandlerMultiSurface.this) {
if (mRendererHolder != null) {
mRendererHolder.captureStill(path);
updateMedia(path);
}
}
}
});
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/widget/AspectRatioTextureView.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;
/**
* change the view size with keeping the specified aspect ratio.
* if you set this view with in a FrameLayout and set property "android:layout_gravity="center",
* you can show this view in the center of screen and keep the aspect ratio of content
* XXX it is better that can set the aspect ratio as xml property
*/
public class AspectRatioTextureView extends TextureView // API >= 14
implements IAspectRatioView {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "AbstractCameraView";
private double mRequestedAspect = -1.0;
private CameraViewInterface.Callback mCallback;
public AspectRatioTextureView(final Context context) {
this(context, null, 0);
}
public AspectRatioTextureView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public AspectRatioTextureView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAspectRatio(final double aspectRatio) {
if (aspectRatio < 0) {
throw new IllegalArgumentException();
}
if (mRequestedAspect != aspectRatio) {
mRequestedAspect = aspectRatio;
requestLayout();
}
}
@Override
public void setAspectRatio(final int width, final int height) {
setAspectRatio(width / (double)height);
}
@Override
public double getAspectRatio() {
return mRequestedAspect;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mRequestedAspect > 0) {
int initialWidth = MeasureSpec.getSize(widthMeasureSpec);
int initialHeight = MeasureSpec.getSize(heightMeasureSpec);
final int horizPadding = getPaddingLeft() + getPaddingRight();
final int vertPadding = getPaddingTop() + getPaddingBottom();
initialWidth -= horizPadding;
initialHeight -= vertPadding;
final double viewAspectRatio = (double)initialWidth / initialHeight;
final double aspectDiff = mRequestedAspect / viewAspectRatio - 1;
if (Math.abs(aspectDiff) > 0.01) {
if (aspectDiff > 0) {
// width priority decision
initialHeight = (int) (initialWidth / mRequestedAspect);
} else {
// height priority decision
initialWidth = (int) (initialHeight * mRequestedAspect);
}
initialWidth += horizPadding;
initialHeight += vertPadding;
widthMeasureSpec = MeasureSpec.makeMeasureSpec(initialWidth, MeasureSpec.EXACTLY);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(initialHeight, MeasureSpec.EXACTLY);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/widget/CameraViewInterface.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.widget;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import com.serenegiant.encoder.IVideoEncoder;
public interface CameraViewInterface extends IAspectRatioView {
public interface Callback {
public void onSurfaceCreated(CameraViewInterface view, Surface surface);
public void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height);
public void onSurfaceDestroy(CameraViewInterface view, Surface surface);
}
public void onPause();
public void onResume();
public void setCallback(Callback callback);
public SurfaceTexture getSurfaceTexture();
public Surface getSurface();
public boolean hasSurface();
public void setVideoEncoder(final IVideoEncoder encoder);
public Bitmap captureStillImage();
}
|
0
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant
|
java-sources/ai/eye2you/usbCameraCommon/2018.10.2/com/serenegiant/widget/UVCCameraTextureView.java
|
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import com.serenegiant.encoder.IVideoEncoder;
import com.serenegiant.encoder.MediaEncoder;
import com.serenegiant.encoder.MediaVideoEncoder;
import com.serenegiant.glutils.EGLBase;
import com.serenegiant.glutils.GLDrawer2D;
import com.serenegiant.glutils.es1.GLHelper;
import com.serenegiant.utils.FpsCounter;
/**
* change the view size with keeping the specified aspect ratio.
* if you set this view with in a FrameLayout and set property "android:layout_gravity="center",
* you can show this view in the center of screen and keep the aspect ratio of content
* XXX it is better that can set the aspect ratio as xml property
*/
public class UVCCameraTextureView extends AspectRatioTextureView // API >= 14
implements TextureView.SurfaceTextureListener, CameraViewInterface {
private static final boolean DEBUG = true; // TODO set false on release
private static final String TAG = "UVCCameraTextureView";
private boolean mHasSurface;
private RenderHandler mRenderHandler;
private final Object mCaptureSync = new Object();
private Bitmap mTempBitmap;
private boolean mReqesutCaptureStillImage;
private Callback mCallback;
/** for calculation of frame rate */
private final FpsCounter mFpsCounter = new FpsCounter();
public UVCCameraTextureView(final Context context) {
this(context, null, 0);
}
public UVCCameraTextureView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public UVCCameraTextureView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
setSurfaceTextureListener(this);
}
@Override
public void onResume() {
if (DEBUG) Log.v(TAG, "onResume:");
if (mHasSurface) {
mRenderHandler = RenderHandler.createHandler(mFpsCounter, super.getSurfaceTexture(), getWidth(), getHeight());
}
}
@Override
public void onPause() {
if (DEBUG) Log.v(TAG, "onPause:");
if (mRenderHandler != null) {
mRenderHandler.release();
mRenderHandler = null;
}
if (mTempBitmap != null) {
mTempBitmap.recycle();
mTempBitmap = null;
}
}
@Override
public void onSurfaceTextureAvailable(final SurfaceTexture surface, final int width, final int height) {
if (DEBUG) Log.v(TAG, "onSurfaceTextureAvailable:" + surface);
if (mRenderHandler == null) {
mRenderHandler = RenderHandler.createHandler(mFpsCounter, surface, width, height);
} else {
mRenderHandler.resize(width, height);
}
mHasSurface = true;
if (mCallback != null) {
mCallback.onSurfaceCreated(this, getSurface());
}
}
@Override
public void onSurfaceTextureSizeChanged(final SurfaceTexture surface, final int width, final int height) {
if (DEBUG) Log.v(TAG, "onSurfaceTextureSizeChanged:" + surface);
if (mRenderHandler != null) {
mRenderHandler.resize(width, height);
}
if (mCallback != null) {
mCallback.onSurfaceChanged(this, getSurface(), width, height);
}
}
@Override
public boolean onSurfaceTextureDestroyed(final SurfaceTexture surface) {
if (DEBUG) Log.v(TAG, "onSurfaceTextureDestroyed:" + surface);
if (mRenderHandler != null) {
mRenderHandler.release();
mRenderHandler = null;
}
mHasSurface = false;
if (mCallback != null) {
mCallback.onSurfaceDestroy(this, getSurface());
}
if (mPreviewSurface != null) {
mPreviewSurface.release();
mPreviewSurface = null;
}
return true;
}
@Override
public void onSurfaceTextureUpdated(final SurfaceTexture surface) {
synchronized (mCaptureSync) {
if (mReqesutCaptureStillImage) {
mReqesutCaptureStillImage = false;
if (mTempBitmap == null)
mTempBitmap = getBitmap();
else
getBitmap(mTempBitmap);
mCaptureSync.notifyAll();
}
}
}
@Override
public boolean hasSurface() {
return mHasSurface;
}
/**
* capture preview image as a bitmap
* this method blocks current thread until bitmap is ready
* if you call this method at almost same time from different thread,
* the returned bitmap will be changed while you are processing the bitmap
* (because we return same instance of bitmap on each call for memory saving)
* if you need to call this method from multiple thread,
* you should change this method(copy and return)
*/
@Override
public Bitmap captureStillImage() {
synchronized (mCaptureSync) {
mReqesutCaptureStillImage = true;
try {
mCaptureSync.wait();
} catch (final InterruptedException e) {
}
return mTempBitmap;
}
}
@Override
public SurfaceTexture getSurfaceTexture() {
return mRenderHandler != null ? mRenderHandler.getPreviewTexture() : null;
}
private Surface mPreviewSurface;
@Override
public Surface getSurface() {
if (DEBUG) Log.v(TAG, "getSurface:hasSurface=" + mHasSurface);
if (mPreviewSurface == null) {
final SurfaceTexture st = getSurfaceTexture();
if (st != null) {
mPreviewSurface = new Surface(st);
}
}
return mPreviewSurface;
}
@Override
public void setVideoEncoder(final IVideoEncoder encoder) {
if (mRenderHandler != null)
mRenderHandler.setVideoEncoder(encoder);
}
@Override
public void setCallback(final Callback callback) {
mCallback = callback;
}
public void resetFps() {
mFpsCounter.reset();
}
/** update frame rate of image processing */
public void updateFps() {
mFpsCounter.update();
}
/**
* get current frame rate of image processing
* @return
*/
public float getFps() {
return mFpsCounter.getFps();
}
/**
* get total frame rate from start
* @return
*/
public float getTotalFps() {
return mFpsCounter.getTotalFps();
}
/**
* render camera frames on this view on a private thread
* @author saki
*
*/
private static final class RenderHandler extends Handler
implements SurfaceTexture.OnFrameAvailableListener {
private static final int MSG_REQUEST_RENDER = 1;
private static final int MSG_SET_ENCODER = 2;
private static final int MSG_CREATE_SURFACE = 3;
private static final int MSG_RESIZE = 4;
private static final int MSG_TERMINATE = 9;
private RenderThread mThread;
private boolean mIsActive = true;
private final FpsCounter mFpsCounter;
public static final RenderHandler createHandler(final FpsCounter counter,
final SurfaceTexture surface, final int width, final int height) {
final RenderThread thread = new RenderThread(counter, surface, width, height);
thread.start();
return thread.getHandler();
}
private RenderHandler(final FpsCounter counter, final RenderThread thread) {
mThread = thread;
mFpsCounter = counter;
}
public final void setVideoEncoder(final IVideoEncoder encoder) {
if (DEBUG) Log.v(TAG, "setVideoEncoder:");
if (mIsActive)
sendMessage(obtainMessage(MSG_SET_ENCODER, encoder));
}
public final SurfaceTexture getPreviewTexture() {
if (DEBUG) Log.v(TAG, "getPreviewTexture:");
if (mIsActive) {
synchronized (mThread.mSync) {
sendEmptyMessage(MSG_CREATE_SURFACE);
try {
mThread.mSync.wait();
} catch (final InterruptedException e) {
}
return mThread.mPreviewSurface;
}
} else {
return null;
}
}
public void resize(final int width, final int height) {
if (DEBUG) Log.v(TAG, "resize:");
if (mIsActive) {
synchronized (mThread.mSync) {
sendMessage(obtainMessage(MSG_RESIZE, width, height));
try {
mThread.mSync.wait();
} catch (final InterruptedException e) {
}
}
}
}
public final void release() {
if (DEBUG) Log.v(TAG, "release:");
if (mIsActive) {
mIsActive = false;
removeMessages(MSG_REQUEST_RENDER);
removeMessages(MSG_SET_ENCODER);
sendEmptyMessage(MSG_TERMINATE);
}
}
@Override
public final void onFrameAvailable(final SurfaceTexture surfaceTexture) {
if (mIsActive) {
mFpsCounter.count();
sendEmptyMessage(MSG_REQUEST_RENDER);
}
}
@Override
public final void handleMessage(final Message msg) {
if (mThread == null) return;
switch (msg.what) {
case MSG_REQUEST_RENDER:
mThread.onDrawFrame();
break;
case MSG_SET_ENCODER:
mThread.setEncoder((MediaEncoder)msg.obj);
break;
case MSG_CREATE_SURFACE:
mThread.updatePreviewSurface();
break;
case MSG_RESIZE:
mThread.resize(msg.arg1, msg.arg2);
break;
case MSG_TERMINATE:
Looper.myLooper().quit();
mThread = null;
break;
default:
super.handleMessage(msg);
}
}
private static final class RenderThread extends Thread {
private final Object mSync = new Object();
private final SurfaceTexture mSurface;
private RenderHandler mHandler;
private EGLBase mEgl;
/** IEglSurface instance related to this TextureView */
private EGLBase.IEglSurface mEglSurface;
private GLDrawer2D mDrawer;
private int mTexId = -1;
/** SurfaceTexture instance to receive video images */
private SurfaceTexture mPreviewSurface;
private final float[] mStMatrix = new float[16];
private MediaEncoder mEncoder;
private int mViewWidth, mViewHeight;
private final FpsCounter mFpsCounter;
/**
* constructor
* @param surface: drawing surface came from TexureView
*/
public RenderThread(final FpsCounter fpsCounter, final SurfaceTexture surface, final int width, final int height) {
mFpsCounter = fpsCounter;
mSurface = surface;
mViewWidth = width;
mViewHeight = height;
setName("RenderThread");
}
public final RenderHandler getHandler() {
if (DEBUG) Log.v(TAG, "RenderThread#getHandler:");
synchronized (mSync) {
// create rendering thread
if (mHandler == null)
try {
mSync.wait();
} catch (final InterruptedException e) {
}
}
return mHandler;
}
public void resize(final int width, final int height) {
if (((width > 0) && (width != mViewWidth)) || ((height > 0) && (height != mViewHeight))) {
mViewWidth = width;
mViewHeight = height;
updatePreviewSurface();
} else {
synchronized (mSync) {
mSync.notifyAll();
}
}
}
public final void updatePreviewSurface() {
if (DEBUG) Log.i(TAG, "RenderThread#updatePreviewSurface:");
synchronized (mSync) {
if (mPreviewSurface != null) {
if (DEBUG) Log.d(TAG, "updatePreviewSurface:release mPreviewSurface");
mPreviewSurface.setOnFrameAvailableListener(null);
mPreviewSurface.release();
mPreviewSurface = null;
}
mEglSurface.makeCurrent();
if (mTexId >= 0) {
mDrawer.deleteTex(mTexId);
}
// create texture and SurfaceTexture for input from camera
mTexId = mDrawer.initTex();
if (DEBUG) Log.v(TAG, "updatePreviewSurface:tex_id=" + mTexId);
mPreviewSurface = new SurfaceTexture(mTexId);
mPreviewSurface.setDefaultBufferSize(mViewWidth, mViewHeight);
mPreviewSurface.setOnFrameAvailableListener(mHandler);
// notify to caller thread that previewSurface is ready
mSync.notifyAll();
}
}
public final void setEncoder(final MediaEncoder encoder) {
if (DEBUG) Log.v(TAG, "RenderThread#setEncoder:encoder=" + encoder);
if (encoder != null && (encoder instanceof MediaVideoEncoder)) {
((MediaVideoEncoder)encoder).setEglContext(mEglSurface.getContext(), mTexId);
}
mEncoder = encoder;
}
/*
* Now you can get frame data as ByteBuffer(as YUV/RGB565/RGBX/NV21 pixel format) using IFrameCallback interface
* with UVCCamera#setFrameCallback instead of using following code samples.
*/
/* // for part1
private static final int BUF_NUM = 1;
private static final int BUF_STRIDE = 640 * 480;
private static final int BUF_SIZE = BUF_STRIDE * BUF_NUM;
int cnt = 0;
int offset = 0;
final int pixels[] = new int[BUF_SIZE];
final IntBuffer buffer = IntBuffer.wrap(pixels); */
/* // for part2
private ByteBuffer buf = ByteBuffer.allocateDirect(640 * 480 * 4);
*/
/**
* draw a frame (and request to draw for video capturing if it is necessary)
*/
public final void onDrawFrame() {
mEglSurface.makeCurrent();
// update texture(came from camera)
mPreviewSurface.updateTexImage();
// get texture matrix
mPreviewSurface.getTransformMatrix(mStMatrix);
// notify video encoder if it exist
if (mEncoder != null) {
// notify to capturing thread that the camera frame is available.
if (mEncoder instanceof MediaVideoEncoder)
((MediaVideoEncoder)mEncoder).frameAvailableSoon(mStMatrix);
else
mEncoder.frameAvailableSoon();
}
// draw to preview screen
mDrawer.draw(mTexId, mStMatrix, 0);
mEglSurface.swap();
/* // sample code to read pixels into Buffer and save as a Bitmap (part1)
buffer.position(offset);
GLES20.glReadPixels(0, 0, 640, 480, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);
if (++cnt == 100) { // save as a Bitmap, only once on this sample code
// if you save every frame as a Bitmap, app will crash by Out of Memory exception...
Log.i(TAG, "Capture image using glReadPixels:offset=" + offset);
final Bitmap bitmap = createBitmap(pixels,offset, 640, 480);
final File outputFile = MediaMuxerWrapper.getCaptureFile(Environment.DIRECTORY_DCIM, ".png");
try {
final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
try {
bitmap.compress(CompressFormat.PNG, 100, os);
os.flush();
bitmap.recycle();
} catch (IOException e) {
}
} finally {
os.close();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
offset = (offset + BUF_STRIDE) % BUF_SIZE;
*/
/* // sample code to read pixels into Buffer and save as a Bitmap (part2)
buf.order(ByteOrder.LITTLE_ENDIAN); // it is enough to call this only once.
GLES20.glReadPixels(0, 0, 640, 480, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf);
buf.rewind();
if (++cnt == 100) { // save as a Bitmap, only once on this sample code
// if you save every frame as a Bitmap, app will crash by Out of Memory exception...
final File outputFile = MediaMuxerWrapper.getCaptureFile(Environment.DIRECTORY_DCIM, ".png");
BufferedOutputStream os = null;
try {
try {
os = new BufferedOutputStream(new FileOutputStream(outputFile));
Bitmap bmp = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buf);
bmp.compress(Bitmap.CompressFormat.PNG, 90, os);
bmp.recycle();
} finally {
if (os != null) os.close();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
*/
}
/* // sample code to read pixels into IntBuffer and save as a Bitmap (part1)
private static Bitmap createBitmap(final int[] pixels, final int offset, final int width, final int height) {
final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
paint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(new float[] {
0, 0, 1, 0, 0,
0, 1, 0, 0, 0,
1, 0, 0, 0, 0,
0, 0, 0, 1, 0
})));
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
final Matrix matrix = new Matrix();
matrix.postScale(1.0f, -1.0f);
matrix.postTranslate(0, height);
canvas.concat(matrix);
canvas.drawBitmap(pixels, offset, width, 0, 0, width, height, false, paint);
return bitmap;
} */
@Override
public final void run() {
Log.d(TAG, getName() + " started");
init();
Looper.prepare();
synchronized (mSync) {
mHandler = new RenderHandler(mFpsCounter, this);
mSync.notify();
}
Looper.loop();
Log.d(TAG, getName() + " finishing");
release();
synchronized (mSync) {
mHandler = null;
mSync.notify();
}
}
private final void init() {
if (DEBUG) Log.v(TAG, "RenderThread#init:");
// create EGLContext for this thread
mEgl = EGLBase.createFrom(null, false, false);
mEglSurface = mEgl.createFromSurface(mSurface);
mEglSurface.makeCurrent();
// create drawing object
mDrawer = new GLDrawer2D(true);
}
private final void release() {
if (DEBUG) Log.v(TAG, "RenderThread#release:");
if (mDrawer != null) {
mDrawer.release();
mDrawer = null;
}
if (mPreviewSurface != null) {
mPreviewSurface.release();
mPreviewSurface = null;
}
if (mTexId >= 0) {
GLHelper.deleteTex(mTexId);
mTexId = -1;
}
if (mEglSurface != null) {
mEglSurface.release();
mEglSurface = null;
}
if (mEgl != null) {
mEgl.release();
mEgl = null;
}
}
}
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/ApiOptions.java
|
package ai.fal.client;
public interface ApiOptions<O> {
Object getInput();
String getHttpMethod();
Class<O> getResultType();
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/ClientConfig.java
|
package ai.fal.client;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
public class ClientConfig {
private CredentialsResolver credentials;
private String proxyUrl;
@Nonnull
public CredentialsResolver getCredentials() {
return credentials;
}
@Nullable
public String getProxyUrl() {
return proxyUrl;
}
public static Builder builder() {
return new Builder().withCredentials(CredentialsResolver.fromEnv());
}
public static ClientConfig withCredentials(CredentialsResolver credentials) {
return builder().withCredentials(credentials).build();
}
public static ClientConfig withProxyUrl(String proxyUrl) {
return builder().withProxyUrl(proxyUrl).build();
}
public static class Builder {
private final ClientConfig config = new ClientConfig();
public Builder withCredentials(CredentialsResolver credentials) {
config.credentials = credentials;
return this;
}
public Builder withProxyUrl(String proxyUrl) {
config.proxyUrl = proxyUrl;
return this;
}
public ClientConfig build() {
return config;
}
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/CredentialsResolver.java
|
package ai.fal.client;
import java.util.function.Supplier;
public interface CredentialsResolver extends Supplier<String> {
static CredentialsResolver fromApiKey(String apiKey) {
return () -> apiKey;
}
static CredentialsResolver fromEnv() {
return () -> System.getenv("FAL_KEY");
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/FalClient.java
|
package ai.fal.client;
import ai.fal.client.queue.QueueClient;
import jakarta.annotation.Nonnull;
/**
* The main client interface for interacting with the FAL APIs.
*
* @see #withConfig(ClientConfig) method to create a new client instance
* with the provided configuration.
* @see #withEnvCredentials() method to create a new client instance
* with the credentials resolved from the environment.
*/
public interface FalClient {
/**
* Run the specified endpoint with the provided options. This method is only recommended for
* short-running operations. For long-running operations, consider using the {@link
* #subscribe(String, SubscribeOptions)} method to subscribe to the endpoint's results via
* the queue or {@link #queue()} client for specific queue operations. .
*
* @param <O> Output type.
* @param endpointId The endpoint ID to run, e.g. `fal-ai/fast-sdxl`.
* @param options The run options.
* @return The result of the operation.
*/
<O> Output<O> run(String endpointId, RunOptions<O> options);
/**
* Subscribe to the specified endpoint with the provided options. This method is recommended for
* long-running operations. The subscription will return the result once the operation is
* completed.
*
* @param <O> Output type.
* @param endpointId The endpoint ID to subscribe to, e.g. `fal-ai/fast-sdxl`.
* @param options The subscribe options.
* @return The result of the operation.
* @see #queue()
*/
<O> Output<O> subscribe(String endpointId, SubscribeOptions<O> options);
/**
* Get the queue client for interacting with the FAL queue.
*
* @return The queue client.
*/
QueueClient queue();
/**
* Create a new client instance with the provided configuration.
*
* @param config The client configuration.
* @return The new client instance.
*/
static FalClient withConfig(@Nonnull ClientConfig config) {
return new FalClientImpl(config);
}
/**
* Create a new client instance with the credentials resolved from the `FAL_KEY` environment
* variable.
*
* @return The new client instance.
*/
static FalClient withEnvCredentials() {
return new FalClientImpl(ClientConfig.withCredentials(CredentialsResolver.fromEnv()));
}
/**
* Create a new client instance with the provided proxy URL. With this configuration all
* requests will be proxied through the provided URL and the fal target url will be in a request
* header called `X-Fal-Target-Url`.
*
* @param proxyUrl The proxy URL.
* @return The new client instance.
*/
static FalClient withProxyUrl(@Nonnull String proxyUrl) {
return new FalClientImpl(ClientConfig.builder().withProxyUrl(proxyUrl).build());
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/FalClientImpl.java
|
package ai.fal.client;
import ai.fal.client.http.ClientProxyInterceptor;
import ai.fal.client.http.CredentialsInterceptor;
import ai.fal.client.http.HttpClient;
import ai.fal.client.queue.*;
import jakarta.annotation.Nonnull;
import okhttp3.OkHttpClient;
public class FalClientImpl implements FalClient {
private final HttpClient httpClient;
private final QueueClient queueClient;
FalClientImpl(@Nonnull ClientConfig config) {
final var builder = new OkHttpClient.Builder().addInterceptor(new CredentialsInterceptor(config));
if (config.getProxyUrl() != null) {
builder.addInterceptor(new ClientProxyInterceptor(config));
}
this.httpClient = new HttpClient(config, builder.build());
this.queueClient = new QueueClientImpl(this.httpClient);
}
@Override
@Nonnull
public <O> Output<O> run(String endpointId, RunOptions<O> options) {
final var url = "https://fal.run/" + endpointId;
final var request = httpClient.prepareRequest(url, options);
final var response = httpClient.executeRequest(request);
return httpClient.wrapInResult(response, options.getResultType());
}
@Override
@Nonnull
public <O> Output<O> subscribe(String endpointId, SubscribeOptions<O> options) {
final var enqueued = queueClient.submit(
endpointId,
QueueSubmitOptions.builder()
.input(options.getInput())
.webhookUrl(options.getWebhookUrl())
.build());
final var completed = queueClient.subscribeToStatus(
endpointId,
QueueSubscribeOptions.builder()
.requestId(enqueued.getRequestId())
.logs(options.getLogs())
.onQueueUpdate(options.getOnQueueUpdate())
.build());
return queueClient.result(
endpointId,
QueueResultOptions.<O>builder()
.requestId(completed.getRequestId())
.resultType(options.getResultType())
.build());
}
@Override
public QueueClient queue() {
return this.queueClient;
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/JsonInput.java
|
package ai.fal.client;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class JsonInput {
private final JsonObject input;
JsonInput(JsonObject input) {
this.input = input;
}
public static JsonInput input() {
return new JsonInput(new JsonObject());
}
public JsonInput set(String key, String value) {
input.addProperty(key, value);
return this;
}
public JsonInput set(String key, Number value) {
input.addProperty(key, value);
return this;
}
public JsonInput set(String key, Boolean value) {
input.addProperty(key, value);
return this;
}
public JsonInput set(String key, Character value) {
input.addProperty(key, value);
return this;
}
public JsonInput set(String key, JsonObject value) {
input.add(key, value);
return this;
}
public JsonInput set(String key, JsonArray value) {
input.add(key, value);
return this;
}
public JsonObject build() {
return input;
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/Output.java
|
package ai.fal.client;
import jakarta.annotation.Nonnull;
import java.util.Objects;
/**
* Represents the output of a request. It contains the data and the {@code requestId}.
* @param <T> the type of the data in the output
*/
public class Output<T> {
private final T data;
private final String requestId;
public Output(@Nonnull T data, @Nonnull String requestId) {
this.data = Objects.requireNonNull(data);
this.requestId = Objects.requireNonNull(requestId);
}
@Nonnull
public T getData() {
return data;
}
@Nonnull
public String getRequestId() {
return requestId;
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/RunOptions.java
|
package ai.fal.client;
import com.google.gson.JsonObject;
import jakarta.annotation.Nonnull;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class RunOptions<O> implements ApiOptions<O> {
private final Object input;
private final String httpMethod;
private final Class<O> resultType;
public static <O> RunOptions<O> withInput(@Nonnull Object input, @Nonnull Class<O> resultType) {
return RunOptions.<O>builder().input(input).resultType(resultType).build();
}
public static RunOptions<JsonObject> withInput(@Nonnull Object input) {
return withInput(input, JsonObject.class);
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/SubscribeOptions.java
|
package ai.fal.client;
import ai.fal.client.queue.QueueStatus;
import com.google.gson.JsonObject;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import java.util.function.Consumer;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class SubscribeOptions<O> implements ApiOptions<O> {
@Nonnull
private final Object input;
@Nullable
private final String webhookUrl;
@Nonnull
private final Class<O> resultType;
@Nullable
private final Boolean logs;
@Nullable
private final Consumer<QueueStatus.StatusUpdate> onQueueUpdate;
@Override
public String getHttpMethod() {
return "POST";
}
@Nonnull
public static SubscribeOptions<JsonObject> withInput(@Nonnull Object input) {
return withInput(input, JsonObject.class);
}
@Nonnull
public static <O> SubscribeOptions<O> withInput(@Nonnull Object input, @Nullable Class<O> resultType) {
return SubscribeOptions.<O>builder().input(input).resultType(resultType).build();
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/exception/FalException.java
|
package ai.fal.client.exception;
import static java.util.Objects.requireNonNull;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
public class FalException extends RuntimeException {
@Nullable
private final String requestId;
public FalException(@Nonnull String message, @Nullable String requestId) {
super(requireNonNull(message));
this.requestId = requestId;
}
public FalException(@Nonnull String message, @Nonnull Throwable cause, @Nullable String requestId) {
super(requireNonNull(message), cause);
this.requestId = requestId;
}
public FalException(Throwable cause) {
super(cause);
this.requestId = null;
}
@Nullable
public String getRequestId() {
return this.requestId;
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/exception/FalValidationException.java
|
package ai.fal.client.exception;
import com.google.gson.annotations.SerializedName;
import jakarta.annotation.Nonnull;
import java.util.List;
import lombok.Data;
public class FalValidationException {
private final List<ValidationError> errors;
public FalValidationException(List<ValidationError> errors) {
this.errors = errors;
}
@Data
public static class ValidationError {
@SerializedName("msg")
private final String message;
@SerializedName("loc")
private List<Object> location;
@Nonnull
private final String type;
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/http/ClientProxyInterceptor.java
|
package ai.fal.client.http;
import ai.fal.client.ClientConfig;
import jakarta.annotation.Nonnull;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
public class ClientProxyInterceptor implements Interceptor {
public static final String HEADER_TARGET_URL = "X-Fal-Target-Url";
private final ClientConfig config;
public ClientProxyInterceptor(@Nonnull ClientConfig config) {
this.config = config;
}
@Override
@Nonnull
public Response intercept(@NotNull Chain chain) throws IOException {
final String proxyUrl = config.getProxyUrl();
if (proxyUrl == null) {
return chain.proceed(chain.request());
}
Request originalRequest = chain.request();
HttpUrl originalUrl = originalRequest.url();
Request.Builder requestBuilder = originalRequest.newBuilder().header(HEADER_TARGET_URL, originalUrl.toString());
HttpUrl newUrl = HttpUrl.parse(proxyUrl);
if (newUrl != null) {
requestBuilder.url(newUrl);
}
Request newRequest = requestBuilder.build();
return chain.proceed(newRequest);
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/http/CredentialsInterceptor.java
|
package ai.fal.client.http;
import ai.fal.client.ClientConfig;
import jakarta.annotation.Nonnull;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
public class CredentialsInterceptor implements Interceptor {
private final ClientConfig config;
public CredentialsInterceptor(@Nonnull ClientConfig config) {
this.config = config;
}
@Override
@Nonnull
public Response intercept(@NotNull Chain chain) throws IOException {
var resolver = config.getCredentials();
var credentials = resolver.get();
if (credentials != null) {
var request = chain.request()
.newBuilder()
.header("Authorization", "Key " + credentials)
.build();
return chain.proceed(request);
}
return chain.proceed(chain.request());
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/http/HttpClient.java
|
package ai.fal.client.http;
import ai.fal.client.ApiOptions;
import ai.fal.client.ClientConfig;
import ai.fal.client.Output;
import ai.fal.client.exception.FalException;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import jakarta.annotation.Nonnull;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpClient {
private static final String APPLICATION_JSON = "application/json";
private static final String HEADER_REQUEST_ID = "X-Fal-Request-Id";
private final ClientConfig config;
private final OkHttpClient client;
private final Gson gson;
public HttpClient(@Nonnull ClientConfig config, @Nonnull OkHttpClient client) {
this.config = config;
this.client = client;
this.gson = new Gson();
}
@Nonnull
public Request prepareRequest(@Nonnull String url, @Nonnull ApiOptions options) {
return prepareRequest(url, options, Collections.EMPTY_MAP);
}
@Nonnull
public Request prepareRequest(
@Nonnull String url, @Nonnull ApiOptions options, @Nonnull Map<String, Object> queryParams) {
var body = options.getInput() != null ? gson.toJson(options.getInput()) : null;
var urlBuilder = HttpUrl.parse(url).newBuilder();
if (!queryParams.isEmpty()) {
queryParams.forEach((key, value) -> urlBuilder.addQueryParameter(key, value.toString()));
}
final var httpMethod = Optional.ofNullable(options.getHttpMethod()).orElse("POST");
return new Request.Builder()
.addHeader("content-type", "application/json")
.addHeader("accept", "application/json")
.method(
httpMethod,
!httpMethod.equalsIgnoreCase("GET") && body != null
? RequestBody.create(body, MediaType.parse(APPLICATION_JSON))
: null)
.url(urlBuilder.build().url())
.build();
}
public Response executeRequest(Request request) {
try {
return client.newCall(request).execute();
} catch (IOException ex) {
throw new FalException(ex);
}
}
public CompletableFuture<Response> executeRequestAsync(Request request) {
var future = new CompletableFuture<Response>();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
future.complete(response);
}
@Override
public void onFailure(Call call, IOException e) {
future.completeExceptionally(e);
}
});
return future;
}
public <T> T handleResponse(Response response, Class<T> resultType) {
final var requestId = response.header(HEADER_REQUEST_ID);
if (!response.isSuccessful()) {
throw responseToException(response);
}
final var body = response.body();
if (body == null) {
throw new FalException("Response has empty body", requestId);
}
return gson.fromJson(body.charStream(), resultType);
}
public FalException responseToException(Response response) {
final var requestId = response.header(HEADER_REQUEST_ID);
final var contentType = response.header("content-type");
if (contentType != null && contentType.contains("application/json")) {
final var body = response.body();
if (body != null) {
final var json = gson.fromJson(body.charStream(), JsonElement.class);
}
}
return new FalException("Request failed with code: " + response.code(), requestId);
}
public <T> Output<T> wrapInResult(Response response, Class<T> resultType) {
final String requestId = response.header(HEADER_REQUEST_ID);
return new Output<>(handleResponse(response, resultType), requestId);
}
public <T> T fromJson(JsonElement json, Class<T> type) {
return gson.fromJson(json, type);
}
public <T> T fromJson(String json, Class<T> type) {
return gson.fromJson(json, type);
}
public OkHttpClient getUnderlyingClient() {
return client;
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/queue/QueueClient.java
|
package ai.fal.client.queue;
import ai.fal.client.Output;
import jakarta.annotation.Nonnull;
/** A client for interacting with the queue endpoints. */
public interface QueueClient {
/**
* Submit a payload to an endpoint's queue.
*
* @param endpointId the endpoint to submit to (e.g. `fal-ai/fast-sdxl`)
* @param options the submit options
* @return the status of the submission with the `requestId` for tracking the submission.
*/
@Nonnull
QueueStatus.InQueue submit(String endpointId, QueueSubmitOptions options);
/**
* Check the status of a submission.
*
* @param endpointId the endpoint to cancel the submission for
* @param options the status check options
* @return the status of the submission
*/
@Nonnull
QueueStatus.StatusUpdate status(@Nonnull String endpointId, @Nonnull QueueStatusOptions options);
/**
* Subscribe to the status of a submission.
*
* @param endpointId the endpoint to subscribe to the status for
* @param options the subscribe options
* @return the status of the submission
*/
@Nonnull
QueueStatus.Completed subscribeToStatus(@Nonnull String endpointId, @Nonnull QueueSubscribeOptions options);
/**
* Get the result of a submission.
*
* @param <O> the type of the output payload
* @param endpointId the endpoint to get the result for
* @param options the response options
* @return the result of the submission
*/
@Nonnull
<O> Output<O> result(@Nonnull String endpointId, @Nonnull QueueResultOptions<O> options);
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/queue/QueueClientImpl.java
|
package ai.fal.client.queue;
import ai.fal.client.Output;
import ai.fal.client.exception.FalException;
import ai.fal.client.http.HttpClient;
import ai.fal.client.queue.QueueStatus.Completed;
import ai.fal.client.util.EndpointId;
import com.google.gson.JsonObject;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
public class QueueClientImpl implements QueueClient {
private final HttpClient httpClient;
public QueueClientImpl(@Nonnull HttpClient httpClient) {
this.httpClient = httpClient;
}
@Nonnull
@Override
public QueueStatus.InQueue submit(@Nonnull String endpointId, @Nonnull QueueSubmitOptions options) {
final var url = "https://queue.fal.run/" + endpointId;
final var queryParams = new HashMap<String, Object>();
if (options.getWebhookUrl() != null) {
queryParams.put("fal_webhook", options.getWebhookUrl());
}
final var request = httpClient.prepareRequest(url, options, queryParams);
final var response = httpClient.executeRequest(request);
return httpClient.handleResponse(response, QueueStatus.InQueue.class);
}
@Nonnull
@Override
public QueueStatus.StatusUpdate status(@Nonnull String endpointId, @Nonnull QueueStatusOptions options) {
final var endpoint = EndpointId.fromString(endpointId);
final var url = String.format(
"https://queue.fal.run/%s/%s/requests/%s/status",
endpoint.getAppOwner(), endpoint.getAppName(), options.getRequestId());
final var queryParams = new HashMap<String, Object>();
if (options.getLogs() != null && options.getLogs()) {
queryParams.put("logs", "1");
}
final var request = httpClient.prepareRequest(url, options, queryParams);
final var response = httpClient.executeRequest(request);
final var result = httpClient.handleResponse(response, JsonObject.class);
return httpClient.fromJson(result, QueueStatus.resolveType(result));
}
@Override
@Nonnull
public Completed subscribeToStatus(@Nonnull String endpointId, @Nonnull QueueSubscribeOptions options) {
final var endpoint = EndpointId.fromString(endpointId);
final var url = String.format(
"https://queue.fal.run/%s/%s/requests/%s/status/stream",
endpoint.getAppOwner(), endpoint.getAppName(), options.getRequestId());
final var queryParams = new HashMap<String, Object>();
if (options.getLogs() != null && options.getLogs()) {
queryParams.put("logs", "1");
}
final var request = httpClient
.prepareRequest(url, options, queryParams)
.newBuilder()
.addHeader("Accept", "text/event-stream")
.build();
final var future = new CompletableFuture<Completed>();
final var factory = EventSources.createFactory(httpClient.getUnderlyingClient());
final var listener = new EventSourceListener() {
private QueueStatus.StatusUpdate currentStatus;
@Override
public void onEvent(
@Nonnull EventSource eventSource,
@Nullable String id,
@Nullable String type,
@Nonnull String data) {
final var json = httpClient.fromJson(data, JsonObject.class);
final var status = httpClient.fromJson(json, QueueStatus.resolveType(json));
final var onUpdate = options.getOnQueueUpdate();
if (onUpdate != null) {
onUpdate.accept(status);
}
this.currentStatus = status;
}
@Override
public void onClosed(@Nonnull EventSource eventSource) {
if (currentStatus != null && currentStatus instanceof Completed) {
future.complete((Completed) currentStatus);
return;
}
future.completeExceptionally(new FalException(
"Streaming closed with invalid state: " + currentStatus, options.getRequestId()));
}
@Override
public void onFailure(
@Nonnull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
future.completeExceptionally(t);
}
};
factory.newEventSource(request, listener);
try {
return future.get();
} catch (Exception ex) {
throw new FalException(ex.getMessage(), ex, options.getRequestId());
}
}
@Nonnull
@Override
public <O> Output<O> result(@Nonnull String endpointId, @Nonnull QueueResultOptions<O> options) {
final var endpoint = EndpointId.fromString(endpointId);
final var url = String.format(
"https://queue.fal.run/%s/%s/requests/%s",
endpoint.getAppOwner(), endpoint.getAppName(), options.getRequestId());
final var request = httpClient.prepareRequest(url, options);
final var response = httpClient.executeRequest(request);
return httpClient.wrapInResult(response, options.getResultType());
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/queue/QueueResultOptions.java
|
package ai.fal.client.queue;
import ai.fal.client.ApiOptions;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import jakarta.annotation.Nonnull;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class QueueResultOptions<O> implements ApiOptions<O> {
@Nonnull
private final String requestId;
private final Class<O> resultType;
@Nonnull
private final JsonNull input = JsonNull.INSTANCE;
@Override
public String getHttpMethod() {
return "GET";
}
@Nonnull
public static QueueResultOptions<JsonObject> withRequestId(@Nonnull String requestId) {
return QueueResultOptions.<JsonObject>builder()
.requestId(requestId)
.resultType(JsonObject.class)
.build();
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/queue/QueueStatus.java
|
package ai.fal.client.queue;
import ai.fal.client.type.RequestLog;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
public interface QueueStatus {
enum Status {
IN_QUEUE,
IN_PROGRESS,
COMPLETED,
}
interface StatusUpdate {
@Nonnull
Status getStatus();
@Nonnull
String getRequestId();
@Nonnull
String getStatusUrl();
@Nonnull
String getResponseUrl();
@Nonnull
String getCancelUrl();
}
@Data
@NoArgsConstructor
class BaseStatusUpdate implements StatusUpdate {
@Nonnull
protected Status status;
@Nonnull
@SerializedName("request_id")
protected String requestId;
@Nonnull
@SerializedName("status_url")
protected String statusUrl;
@Nonnull
@SerializedName("response_url")
protected String responseUrl;
@Nonnull
@SerializedName("cancel_url")
protected String cancelUrl;
}
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
class InQueue extends BaseStatusUpdate {
@Nonnull
@SerializedName("queue_position")
private Integer queuePosition;
}
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
class InProgress extends BaseStatusUpdate {
@Nullable
@SerializedName("logs")
private List<RequestLog> logs;
}
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
class Completed extends BaseStatusUpdate {
@Nullable
@SerializedName("logs")
private List<RequestLog> logs;
}
static Class<? extends StatusUpdate> resolveType(JsonObject payload) {
final var status = payload.get("status").getAsString();
if (status.equals(QueueStatus.Status.IN_QUEUE.name())) {
return InQueue.class;
}
if (status.equals(QueueStatus.Status.IN_PROGRESS.name())) {
return QueueStatus.InProgress.class;
}
if (status.equals(QueueStatus.Status.COMPLETED.name())) {
return QueueStatus.Completed.class;
}
throw new IllegalArgumentException("Unknown status: " + status);
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/queue/QueueStatusOptions.java
|
package ai.fal.client.queue;
import ai.fal.client.ApiOptions;
import com.google.gson.JsonNull;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class QueueStatusOptions implements ApiOptions<QueueStatus> {
@Nonnull
private final JsonNull input = JsonNull.INSTANCE;
@Nonnull
private final String requestId;
@Nullable
private final Boolean logs;
@Nonnull
private final Class<QueueStatus> resultType = QueueStatus.class;
@Override
public String getHttpMethod() {
return "GET";
}
public static QueueStatusOptions withRequestId(@Nonnull String requestId) {
return QueueStatusOptions.builder().requestId(requestId).build();
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/queue/QueueSubmitOptions.java
|
package ai.fal.client.queue;
import ai.fal.client.ApiOptions;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class QueueSubmitOptions implements ApiOptions<QueueStatus.InQueue> {
@Nonnull
private final Object input;
@Nullable
private final String webhookUrl;
@Nonnull
private final Class<QueueStatus.InQueue> resultType = QueueStatus.InQueue.class;
@Override
public String getHttpMethod() {
return "POST";
}
public static QueueSubmitOptions withInput(@Nonnull Object input) {
return QueueSubmitOptions.builder().input(input).build();
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/queue/QueueSubscribeOptions.java
|
package ai.fal.client.queue;
import ai.fal.client.ApiOptions;
import com.google.gson.JsonNull;
import java.util.function.Consumer;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class QueueSubscribeOptions implements ApiOptions<QueueStatus.Completed> {
private final JsonNull input = JsonNull.INSTANCE;
private final Class<QueueStatus.Completed> resultType = QueueStatus.Completed.class;
private final String requestId;
private final Boolean logs;
private final Consumer<QueueStatus.StatusUpdate> onQueueUpdate;
@Override
public String getHttpMethod() {
return "GET";
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/type/RequestLog.java
|
package ai.fal.client.type;
import jakarta.annotation.Nonnull;
import lombok.Data;
@Data
public class RequestLog {
public enum Level {
STDERR,
STDOUT,
ERROR,
INFO,
WARN,
DEBUG
}
@Nonnull
private final String message;
@Nonnull
private final String timestamp;
@Nonnull
private final LogLabels labels;
public Level getLevel() {
return labels.getLevel();
}
@Data
public static class LogLabels {
@Nonnull
private final Level level;
@Nonnull
private final String source;
}
}
|
0
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client/0.7.1/ai/fal/client/util/EndpointId.java
|
package ai.fal.client.util;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
public class EndpointId {
private static final List<String> RESERVED_NAMESPACES = Arrays.asList("workflows", "comfy");
private final String appOwner;
private final String appName;
private final String path;
private final String namespace;
public EndpointId(
@Nonnull String appOwner, @Nonnull String appName, @Nullable String path, @Nullable String namespace) {
this.appOwner = appOwner;
this.appName = appName;
this.path = path;
this.namespace = namespace;
}
@Nonnull
public String getAppOwner() {
return appOwner;
}
@Nonnull
public String getAppName() {
return appName;
}
@Nullable
public String getPath() {
return path;
}
@Nullable
public String getNamespace() {
return namespace;
}
public static EndpointId fromString(String endpointId) {
final String[] parts = endpointId.split("/");
if (RESERVED_NAMESPACES.contains(parts[0])) {
return new EndpointId(
parts[1],
parts[2],
parts.length > 3 ? String.join("/", Arrays.copyOfRange(parts, 3, parts.length)) : null,
parts[0]);
}
return new EndpointId(
parts[0],
parts[1],
parts.length > 2 ? String.join("/", Arrays.copyOfRange(parts, 2, parts.length)) : null,
null);
}
}
|
0
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal/client/AsyncFalClient.java
|
package ai.fal.client;
import ai.fal.client.queue.AsyncQueueClient;
import jakarta.annotation.Nonnull;
import java.util.concurrent.CompletableFuture;
public interface AsyncFalClient {
<O> CompletableFuture<Output<O>> run(String endpointId, RunOptions<O> options);
<O> CompletableFuture<Output<O>> subscribe(String endpointId, SubscribeOptions<O> options);
AsyncQueueClient queue();
/**
* Create a new client instance with the provided configuration.
*
* @param config The client configuration.
* @return The new client instance.
*/
static AsyncFalClient withConfig(@Nonnull ClientConfig config) {
return new AsyncFalClientImpl(config);
}
/**
* Create a new client instance with the credentials resolved from the `FAL_KEY` environment
* variable.
*
* @return The new client instance.
*/
static AsyncFalClient withEnvCredentials() {
return new AsyncFalClientImpl(ClientConfig.withCredentials(CredentialsResolver.fromEnv()));
}
/**
* Create a new client instance with the provided proxy URL. With this configuration all
* requests will be proxied through the provided URL and the fal target url will be in a request
* header called `X-Fal-Target-Url`.
*
* @param proxyUrl The proxy URL.
* @return The new client instance.
*/
static AsyncFalClient withProxyUrl(@Nonnull String proxyUrl) {
return new AsyncFalClientImpl(
ClientConfig.builder().withProxyUrl(proxyUrl).build());
}
}
|
0
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal/client/AsyncFalClientImpl.java
|
package ai.fal.client;
import ai.fal.client.http.ClientProxyInterceptor;
import ai.fal.client.http.CredentialsInterceptor;
import ai.fal.client.http.HttpClient;
import ai.fal.client.queue.*;
import java.util.concurrent.CompletableFuture;
import okhttp3.OkHttpClient;
public class AsyncFalClientImpl implements AsyncFalClient {
private final HttpClient httpClient;
private final AsyncQueueClient queueClient;
AsyncFalClientImpl(ClientConfig config) {
final var builder = new OkHttpClient.Builder().addInterceptor(new CredentialsInterceptor(config));
if (config.getProxyUrl() != null) {
builder.addInterceptor(new ClientProxyInterceptor(config));
}
this.httpClient = new HttpClient(config, builder.build());
this.queueClient = new AsyncQueueClientImpl(this.httpClient);
}
@Override
public <O> CompletableFuture<Output<O>> run(String endpointId, RunOptions<O> options) {
final var url = "https://fal.run/" + endpointId;
final var request = httpClient.prepareRequest(url, options);
return httpClient
.executeRequestAsync(request)
.thenApply(response -> httpClient.wrapInResult(response, options.getResultType()));
}
@Override
public <O> CompletableFuture<Output<O>> subscribe(String endpointId, SubscribeOptions<O> options) {
return queueClient
.submit(
endpointId,
QueueSubmitOptions.builder()
.input(options.getInput())
.webhookUrl(options.getWebhookUrl())
.build())
.thenCompose((submitted) -> queueClient.subscribeToStatus(
endpointId,
QueueSubscribeOptions.builder()
.requestId(submitted.getRequestId())
.logs(options.getLogs())
.onQueueUpdate(options.getOnQueueUpdate())
.build()))
.thenCompose((completed) -> queueClient.result(
endpointId,
QueueResultOptions.<O>builder()
.requestId(completed.getRequestId())
.resultType(options.getResultType())
.build()));
}
@Override
public AsyncQueueClient queue() {
return this.queueClient;
}
}
|
0
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal/client/queue/AsyncQueueClient.java
|
package ai.fal.client.queue;
import ai.fal.client.Output;
import jakarta.annotation.Nonnull;
import java.util.concurrent.CompletableFuture;
public interface AsyncQueueClient {
@Nonnull
CompletableFuture<QueueStatus.InQueue> submit(String endpointId, QueueSubmitOptions options);
@Nonnull
CompletableFuture<QueueStatus.StatusUpdate> status(@Nonnull String endpointId, @Nonnull QueueStatusOptions options);
@Nonnull
CompletableFuture<QueueStatus.Completed> subscribeToStatus(
@Nonnull String endpointId, @Nonnull QueueSubscribeOptions options);
@Nonnull
<O> CompletableFuture<Output<O>> result(@Nonnull String endpointId, @Nonnull QueueResultOptions<O> options);
}
|
0
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal/client
|
java-sources/ai/fal/client/fal-client-async/0.7.1/ai/fal/client/queue/AsyncQueueClientImpl.java
|
package ai.fal.client.queue;
import ai.fal.client.Output;
import ai.fal.client.exception.FalException;
import ai.fal.client.http.HttpClient;
import ai.fal.client.util.EndpointId;
import com.google.gson.JsonObject;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
public class AsyncQueueClientImpl implements AsyncQueueClient {
private final HttpClient httpClient;
public AsyncQueueClientImpl(@Nonnull HttpClient httpClient) {
this.httpClient = httpClient;
}
@Nonnull
@Override
public CompletableFuture<QueueStatus.InQueue> submit(String endpointId, QueueSubmitOptions options) {
final var url = "https://queue.fal.run/" + endpointId;
final var queryParams = new HashMap<String, Object>();
if (options.getWebhookUrl() != null) {
queryParams.put("fal_webhook", options.getWebhookUrl());
}
final var request = httpClient.prepareRequest(url, options, queryParams);
return httpClient
.executeRequestAsync(request)
.thenApply(response -> httpClient.handleResponse(response, QueueStatus.InQueue.class));
}
@Nonnull
@Override
public CompletableFuture<QueueStatus.StatusUpdate> status(
@Nonnull String endpointId, @Nonnull QueueStatusOptions options) {
final var endpoint = EndpointId.fromString(endpointId);
final var url = String.format(
"https://queue.fal.run/%s/%s/requests/%s/status",
endpoint.getAppOwner(), endpoint.getAppName(), options.getRequestId());
final var queryParams = new HashMap<String, Object>();
if (options.getLogs() != null && options.getLogs()) {
queryParams.put("logs", "1");
}
final var request = httpClient.prepareRequest(url, options, queryParams);
return httpClient.executeRequestAsync(request).thenApply((response) -> {
final var result = httpClient.handleResponse(response, JsonObject.class);
return httpClient.fromJson(result, QueueStatus.resolveType(result));
});
}
@Nonnull
@Override
public CompletableFuture<QueueStatus.Completed> subscribeToStatus(
@Nonnull String endpointId, @Nonnull QueueSubscribeOptions options) {
final var endpoint = EndpointId.fromString(endpointId);
final var url = String.format(
"https://queue.fal.run/%s/%s/requests/%s/status/stream",
endpoint.getAppOwner(), endpoint.getAppName(), options.getRequestId());
final var queryParams = new HashMap<String, Object>();
if (options.getLogs() != null && options.getLogs()) {
queryParams.put("logs", "1");
}
final var request = httpClient
.prepareRequest(url, options, queryParams)
.newBuilder()
.addHeader("Accept", "text/event-stream")
.build();
final var future = new CompletableFuture<QueueStatus.Completed>();
final var factory = EventSources.createFactory(httpClient.getUnderlyingClient());
final var listener = new EventSourceListener() {
private QueueStatus.StatusUpdate currentStatus;
@Override
public void onEvent(
@Nonnull EventSource eventSource,
@Nullable String id,
@Nullable String type,
@Nonnull String data) {
final var json = httpClient.fromJson(data, JsonObject.class);
final var status = httpClient.fromJson(json, QueueStatus.resolveType(json));
final var onUpdate = options.getOnQueueUpdate();
if (onUpdate != null) {
onUpdate.accept(status);
}
this.currentStatus = status;
}
@Override
public void onClosed(@Nonnull EventSource eventSource) {
if (currentStatus != null && currentStatus instanceof QueueStatus.Completed) {
future.complete((QueueStatus.Completed) currentStatus);
return;
}
future.completeExceptionally(new FalException(
"Streaming closed with invalid state: " + currentStatus, options.getRequestId()));
}
@Override
public void onFailure(
@Nonnull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
future.completeExceptionally(t);
}
};
factory.newEventSource(request, listener);
return future;
}
@Nonnull
@Override
public <O> CompletableFuture<Output<O>> result(@Nonnull String endpointId, @Nonnull QueueResultOptions<O> options) {
final var endpoint = EndpointId.fromString(endpointId);
final var url = String.format(
"https://queue.fal.run/%s/%s/requests/%s",
endpoint.getAppOwner(), endpoint.getAppName(), options.getRequestId());
final var request = httpClient.prepareRequest(url, options);
return httpClient
.executeRequestAsync(request)
.thenApply((response) -> httpClient.wrapInResult(response, options.getResultType()));
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/api/SignalsApi.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.api;
import ai.fideo.client.ApiCallback;
import ai.fideo.client.ApiClient;
import ai.fideo.client.ApiException;
import ai.fideo.client.ApiResponse;
import ai.fideo.client.Configuration;
import ai.fideo.client.Pair;
import ai.fideo.client.ProgressRequestBody;
import ai.fideo.client.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import ai.fideo.model.MultiFieldReqWithOptions;
import ai.fideo.model.SignalsPost200Response;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SignalsApi {
private ApiClient localVarApiClient;
private int localHostIndex;
private String localCustomBaseUrl;
public SignalsApi() {
this(Configuration.getDefaultApiClient());
}
public SignalsApi(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public int getHostIndex() {
return localHostIndex;
}
public void setHostIndex(int hostIndex) {
this.localHostIndex = hostIndex;
}
public String getCustomBaseUrl() {
return localCustomBaseUrl;
}
public void setCustomBaseUrl(String customBaseUrl) {
this.localCustomBaseUrl = customBaseUrl;
}
/**
* Build call for signalsPost
* @param v (optional)
* @param multiFieldReqWithOptions (optional)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
</table>
*/
public okhttp3.Call signalsPostCall(String v, MultiFieldReqWithOptions multiFieldReqWithOptions, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = multiFieldReqWithOptions;
// create path and map variables
String localVarPath = "/signals";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (v != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("v", v));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { "bearerAuth" };
return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call signalsPostValidateBeforeCall(String v, MultiFieldReqWithOptions multiFieldReqWithOptions, final ApiCallback _callback) throws ApiException {
return signalsPostCall(v, multiFieldReqWithOptions, _callback);
}
/**
*
*
* @param v (optional)
* @param multiFieldReqWithOptions (optional)
* @return SignalsPost200Response
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
</table>
*/
public SignalsPost200Response signalsPost(String v, MultiFieldReqWithOptions multiFieldReqWithOptions) throws ApiException {
ApiResponse<SignalsPost200Response> localVarResp = signalsPostWithHttpInfo(v, multiFieldReqWithOptions);
return localVarResp.getData();
}
/**
*
*
* @param v (optional)
* @param multiFieldReqWithOptions (optional)
* @return ApiResponse<SignalsPost200Response>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
</table>
*/
public ApiResponse<SignalsPost200Response> signalsPostWithHttpInfo(String v, MultiFieldReqWithOptions multiFieldReqWithOptions) throws ApiException {
okhttp3.Call localVarCall = signalsPostValidateBeforeCall(v, multiFieldReqWithOptions, null);
Type localVarReturnType = new TypeToken<SignalsPost200Response>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* (asynchronously)
*
* @param v (optional)
* @param multiFieldReqWithOptions (optional)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> Successful response </td><td> - </td></tr>
</table>
*/
public okhttp3.Call signalsPostAsync(String v, MultiFieldReqWithOptions multiFieldReqWithOptions, final ApiCallback<SignalsPost200Response> _callback) throws ApiException {
okhttp3.Call localVarCall = signalsPostValidateBeforeCall(v, multiFieldReqWithOptions, _callback);
Type localVarReturnType = new TypeToken<SignalsPost200Response>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/api/VerifyApi.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.api;
import ai.fideo.client.ApiCallback;
import ai.fideo.client.ApiClient;
import ai.fideo.client.ApiException;
import ai.fideo.client.ApiResponse;
import ai.fideo.client.Configuration;
import ai.fideo.client.Pair;
import ai.fideo.client.ProgressRequestBody;
import ai.fideo.client.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import ai.fideo.model.MultiFieldReq;
import ai.fideo.model.VerifyResponse;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class VerifyApi {
private ApiClient localVarApiClient;
private int localHostIndex;
private String localCustomBaseUrl;
public VerifyApi() {
this(Configuration.getDefaultApiClient());
}
public VerifyApi(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public int getHostIndex() {
return localHostIndex;
}
public void setHostIndex(int hostIndex) {
this.localHostIndex = hostIndex;
}
public String getCustomBaseUrl() {
return localCustomBaseUrl;
}
public void setCustomBaseUrl(String customBaseUrl) {
this.localCustomBaseUrl = customBaseUrl;
}
/**
* Build call for verifyPost
* @param multiFieldReq (optional)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> OK </td><td> - </td></tr>
</table>
*/
public okhttp3.Call verifyPostCall(MultiFieldReq multiFieldReq, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = multiFieldReq;
// create path and map variables
String localVarPath = "/verify";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { "bearerAuth" };
return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call verifyPostValidateBeforeCall(MultiFieldReq multiFieldReq, final ApiCallback _callback) throws ApiException {
return verifyPostCall(multiFieldReq, _callback);
}
/**
*
*
* @param multiFieldReq (optional)
* @return VerifyResponse
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> OK </td><td> - </td></tr>
</table>
*/
public VerifyResponse verifyPost(MultiFieldReq multiFieldReq) throws ApiException {
ApiResponse<VerifyResponse> localVarResp = verifyPostWithHttpInfo(multiFieldReq);
return localVarResp.getData();
}
/**
*
*
* @param multiFieldReq (optional)
* @return ApiResponse<VerifyResponse>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> OK </td><td> - </td></tr>
</table>
*/
public ApiResponse<VerifyResponse> verifyPostWithHttpInfo(MultiFieldReq multiFieldReq) throws ApiException {
okhttp3.Call localVarCall = verifyPostValidateBeforeCall(multiFieldReq, null);
Type localVarReturnType = new TypeToken<VerifyResponse>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* (asynchronously)
*
* @param multiFieldReq (optional)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> OK </td><td> - </td></tr>
</table>
*/
public okhttp3.Call verifyPostAsync(MultiFieldReq multiFieldReq, final ApiCallback<VerifyResponse> _callback) throws ApiException {
okhttp3.Call localVarCall = verifyPostValidateBeforeCall(multiFieldReq, _callback);
Type localVarReturnType = new TypeToken<VerifyResponse>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ApiCallback.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API download processing.
*
* @param bytesRead bytes Read
* @param contentLength content length of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ApiClient.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import okhttp3.*;
import okhttp3.internal.http.HttpMethod;
import okhttp3.internal.tls.OkHostnameVerifier;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import javax.net.ssl.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ai.fideo.client.auth.Authentication;
import ai.fideo.client.auth.HttpBasicAuth;
import ai.fideo.client.auth.HttpBearerAuth;
import ai.fideo.client.auth.ApiKeyAuth;
/**
* <p>ApiClient class.</p>
*/
public class ApiClient {
private String basePath = "https://api.fideo.ai";
protected List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>(Arrays.asList(
new ServerConfiguration(
"https://api.fideo.ai",
"No description provided",
new HashMap<String, ServerVariable>()
)
));
protected Integer serverIndex = 0;
protected Map<String, String> serverVariables = null;
private boolean debugging = false;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
private String tempFolderPath = null;
private Map<String, Authentication> authentications;
private DateFormat dateFormat;
private DateFormat datetimeFormat;
private boolean lenientDatetimeFormat;
private int dateLength;
private InputStream sslCaCert;
private boolean verifyingSsl;
private KeyManager[] keyManagers;
private OkHttpClient httpClient;
private JSON json;
private HttpLoggingInterceptor loggingInterceptor;
/**
* Basic constructor for ApiClient
*/
public ApiClient() {
init();
initHttpClient();
// Setup authentications (key: authentication name, value: authentication).
authentications.put("bearerAuth", new HttpBearerAuth("bearer"));
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Basic constructor with custom OkHttpClient
*
* @param client a {@link okhttp3.OkHttpClient} object
*/
public ApiClient(OkHttpClient client) {
init();
httpClient = client;
// Setup authentications (key: authentication name, value: authentication).
authentications.put("bearerAuth", new HttpBearerAuth("bearer"));
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
private void initHttpClient() {
initHttpClient(Collections.<Interceptor>emptyList());
}
private void initHttpClient(List<Interceptor> interceptors) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(getProgressInterceptor());
for (Interceptor interceptor: interceptors) {
builder.addInterceptor(interceptor);
}
httpClient = builder.build();
}
private void init() {
verifyingSsl = true;
json = new JSON();
// Set default User-Agent.
setUserAgent("OpenAPI-Generator/1.0.4/java");
authentications = new HashMap<String, Authentication>();
}
/**
* Get base path
*
* @return Base path
*/
public String getBasePath() {
return basePath;
}
/**
* Set base path
*
* @param basePath Base path of the URL (e.g https://api.fideo.ai
* @return An instance of OkHttpClient
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
this.serverIndex = null;
return this;
}
public List<ServerConfiguration> getServers() {
return servers;
}
public ApiClient setServers(List<ServerConfiguration> servers) {
this.servers = servers;
return this;
}
public Integer getServerIndex() {
return serverIndex;
}
public ApiClient setServerIndex(Integer serverIndex) {
this.serverIndex = serverIndex;
return this;
}
public Map<String, String> getServerVariables() {
return serverVariables;
}
public ApiClient setServerVariables(Map<String, String> serverVariables) {
this.serverVariables = serverVariables;
return this;
}
/**
* Get HTTP client
*
* @return An instance of OkHttpClient
*/
public OkHttpClient getHttpClient() {
return httpClient;
}
/**
* Set HTTP client, which must never be null.
*
* @param newHttpClient An instance of OkHttpClient
* @return Api Client
* @throws java.lang.NullPointerException when newHttpClient is null
*/
public ApiClient setHttpClient(OkHttpClient newHttpClient) {
this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!");
return this;
}
/**
* Get JSON
*
* @return JSON object
*/
public JSON getJSON() {
return json;
}
/**
* Set JSON
*
* @param json JSON object
* @return Api client
*/
public ApiClient setJSON(JSON json) {
this.json = json;
return this;
}
/**
* True if isVerifyingSsl flag is on
*
* @return True if isVerifySsl flag is on
*/
public boolean isVerifyingSsl() {
return verifyingSsl;
}
/**
* Configure whether to verify certificate and hostname when making https requests.
* Default to true.
* NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.
*
* @param verifyingSsl True to verify TLS/SSL connection
* @return ApiClient
*/
public ApiClient setVerifyingSsl(boolean verifyingSsl) {
this.verifyingSsl = verifyingSsl;
applySslSettings();
return this;
}
/**
* Get SSL CA cert.
*
* @return Input stream to the SSL CA cert
*/
public InputStream getSslCaCert() {
return sslCaCert;
}
/**
* Configure the CA certificate to be trusted when making https requests.
* Use null to reset to default.
*
* @param sslCaCert input stream for SSL CA cert
* @return ApiClient
*/
public ApiClient setSslCaCert(InputStream sslCaCert) {
this.sslCaCert = sslCaCert;
applySslSettings();
return this;
}
/**
* <p>Getter for the field <code>keyManagers</code>.</p>
*
* @return an array of {@link javax.net.ssl.KeyManager} objects
*/
public KeyManager[] getKeyManagers() {
return keyManagers;
}
/**
* Configure client keys to use for authorization in an SSL session.
* Use null to reset to default.
*
* @param managers The KeyManagers to use
* @return ApiClient
*/
public ApiClient setKeyManagers(KeyManager[] managers) {
this.keyManagers = managers;
applySslSettings();
return this;
}
/**
* <p>Getter for the field <code>dateFormat</code>.</p>
*
* @return a {@link java.text.DateFormat} object
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* <p>Setter for the field <code>dateFormat</code>.</p>
*
* @param dateFormat a {@link java.text.DateFormat} object
* @return a {@link ai.fideo.client.ApiClient} object
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
JSON.setDateFormat(dateFormat);
return this;
}
/**
* <p>Set SqlDateFormat.</p>
*
* @param dateFormat a {@link java.text.DateFormat} object
* @return a {@link ai.fideo.client.ApiClient} object
*/
public ApiClient setSqlDateFormat(DateFormat dateFormat) {
JSON.setSqlDateFormat(dateFormat);
return this;
}
/**
* <p>Set OffsetDateTimeFormat.</p>
*
* @param dateFormat a {@link java.time.format.DateTimeFormatter} object
* @return a {@link ai.fideo.client.ApiClient} object
*/
public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
JSON.setOffsetDateTimeFormat(dateFormat);
return this;
}
/**
* <p>Set LocalDateFormat.</p>
*
* @param dateFormat a {@link java.time.format.DateTimeFormatter} object
* @return a {@link ai.fideo.client.ApiClient} object
*/
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
JSON.setLocalDateFormat(dateFormat);
return this;
}
/**
* <p>Set LenientOnJson.</p>
*
* @param lenientOnJson a boolean
* @return a {@link ai.fideo.client.ApiClient} object
*/
public ApiClient setLenientOnJson(boolean lenientOnJson) {
JSON.setLenientOnJson(lenientOnJson);
return this;
}
/**
* Get authentications (key: authentication name, value: authentication).
*
* @return Map of authentication objects
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set access token for the first Bearer authentication.
* @param bearerToken Bearer token
*/
public void setBearerToken(String bearerToken) {
setBearerToken(() -> bearerToken);
}
/**
* Helper method to set the supplier of access tokens for Bearer authentication.
*
* @param tokenSupplier The supplier of bearer tokens
*/
public void setBearerToken(Supplier<String> tokenSupplier) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBearerAuth) {
((HttpBearerAuth) auth).setBearerToken(tokenSupplier);
return;
}
}
throw new RuntimeException("No Bearer authentication configured!");
}
/**
* Helper method to set username for the first HTTP basic authentication.
*
* @param username Username
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
*
* @param password Password
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*
* @param apiKey API key
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*
* @param apiKeyPrefix API key prefix
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set access token for the first OAuth2 authentication.
*
* @param accessToken Access token
*/
public void setAccessToken(String accessToken) {
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Helper method to set credentials for AWSV4 Signature
*
* @param accessKey Access Key
* @param secretKey Secret Key
* @param region Region
* @param service Service to access to
*/
public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) {
throw new RuntimeException("No AWS4 authentication configured!");
}
/**
* Helper method to set credentials for AWSV4 Signature
*
* @param accessKey Access Key
* @param secretKey Secret Key
* @param sessionToken Session Token
* @param region Region
* @param service Service to access to
*/
public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) {
throw new RuntimeException("No AWS4 authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*
* @param userAgent HTTP request's user agent
* @return ApiClient
*/
public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent);
return this;
}
/**
* Add a default header.
*
* @param key The header's key
* @param value The header's value
* @return ApiClient
*/
public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
return this;
}
/**
* Add a default cookie.
*
* @param key The cookie's key
* @param value The cookie's value
* @return ApiClient
*/
public ApiClient addDefaultCookie(String key, String value) {
defaultCookieMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
*
* @return True if debugging is enabled, false otherwise.
*/
public boolean isDebugging() {
return debugging;
}
/**
* Enable/disable debugging for this API client.
*
* @param debugging To enable (true) or disable (false) debugging
* @return ApiClient
*/
public ApiClient setDebugging(boolean debugging) {
if (debugging != this.debugging) {
if (debugging) {
loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(Level.BODY);
httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build();
} else {
final OkHttpClient.Builder builder = httpClient.newBuilder();
builder.interceptors().remove(loggingInterceptor);
httpClient = builder.build();
loggingInterceptor = null;
}
}
this.debugging = debugging;
return this;
}
/**
* The path of temporary folder used to store downloaded files from endpoints
* with file response. The default value is <code>null</code>, i.e. using
* the system's default temporary folder.
*
* @see <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempFile(java.lang.String,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...)">createTempFile</a>
* @return Temporary folder path
*/
public String getTempFolderPath() {
return tempFolderPath;
}
/**
* Set the temporary folder path (for downloading files)
*
* @param tempFolderPath Temporary folder path
* @return ApiClient
*/
public ApiClient setTempFolderPath(String tempFolderPath) {
this.tempFolderPath = tempFolderPath;
return this;
}
/**
* Get connection timeout (in milliseconds).
*
* @return Timeout in milliseconds
*/
public int getConnectTimeout() {
return httpClient.connectTimeoutMillis();
}
/**
* Sets the connect timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
* {@link java.lang.Integer#MAX_VALUE}.
*
* @param connectionTimeout connection timeout in milliseconds
* @return Api client
*/
public ApiClient setConnectTimeout(int connectionTimeout) {
httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build();
return this;
}
/**
* Get read timeout (in milliseconds).
*
* @return Timeout in milliseconds
*/
public int getReadTimeout() {
return httpClient.readTimeoutMillis();
}
/**
* Sets the read timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
* {@link java.lang.Integer#MAX_VALUE}.
*
* @param readTimeout read timeout in milliseconds
* @return Api client
*/
public ApiClient setReadTimeout(int readTimeout) {
httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build();
return this;
}
/**
* Get write timeout (in milliseconds).
*
* @return Timeout in milliseconds
*/
public int getWriteTimeout() {
return httpClient.writeTimeoutMillis();
}
/**
* Sets the write timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
* {@link java.lang.Integer#MAX_VALUE}.
*
* @param writeTimeout connection timeout in milliseconds
* @return Api client
*/
public ApiClient setWriteTimeout(int writeTimeout) {
httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build();
return this;
}
/**
* Format the given parameter object into string.
*
* @param param Parameter
* @return String representation of the parameter
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) {
//Serialize to json string and remove the " enclosing characters
String jsonStr = JSON.serialize(param);
return jsonStr.substring(1, jsonStr.length() - 1);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for (Object o : (Collection) param) {
if (b.length() > 0) {
b.append(",");
}
b.append(o);
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/**
* Formats the specified query parameter to a list containing a single {@code Pair} object.
*
* Note that {@code value} must not be a collection.
*
* @param name The name of the parameter.
* @param value The value of the parameter.
* @return A list containing a single {@code Pair} object.
*/
public List<Pair> parameterToPair(String name, Object value) {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null || value instanceof Collection) {
return params;
}
params.add(new Pair(name, parameterToString(value)));
return params;
}
/**
* Formats the specified collection query parameters to a list of {@code Pair} objects.
*
* Note that the values of each of the returned Pair objects are percent-encoded.
*
* @param collectionFormat The collection format of the parameter.
* @param name The name of the parameter.
* @param value The value of the parameter.
* @return A list of {@code Pair} objects.
*/
public List<Pair> parameterToPairs(String collectionFormat, String name, Collection value) {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null || value.isEmpty()) {
return params;
}
// create the params based on the collection format
if ("multi".equals(collectionFormat)) {
for (Object item : value) {
params.add(new Pair(name, escapeString(parameterToString(item))));
}
return params;
}
// collectionFormat is assumed to be "csv" by default
String delimiter = ",";
// escape all delimiters except commas, which are URI reserved
// characters
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}
StringBuilder sb = new StringBuilder();
for (Object item : value) {
sb.append(delimiter);
sb.append(escapeString(parameterToString(item)));
}
params.add(new Pair(name, sb.substring(delimiter.length())));
return params;
}
/**
* Formats the specified free-form query parameters to a list of {@code Pair} objects.
*
* @param value The free-form query parameters.
* @return A list of {@code Pair} objects.
*/
public List<Pair> freeFormParameterToPairs(Object value) {
List<Pair> params = new ArrayList<>();
// preconditions
if (value == null || !(value instanceof Map )) {
return params;
}
final Map<String, Object> valuesMap = (Map<String, Object>) value;
for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
params.add(new Pair(entry.getKey(), parameterToString(entry.getValue())));
}
return params;
}
/**
* Formats the specified collection path parameter to a string value.
*
* @param collectionFormat The collection format of the parameter.
* @param value The value of the parameter.
* @return String representation of the parameter
*/
public String collectionPathParameterToString(String collectionFormat, Collection value) {
// create the value based on the collection format
if ("multi".equals(collectionFormat)) {
// not valid for path params
return parameterToString(value);
}
// collectionFormat is assumed to be "csv" by default
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = " ";
} else if ("tsv".equals(collectionFormat)) {
delimiter = "\t";
} else if ("pipes".equals(collectionFormat)) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder() ;
for (Object item : value) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
return sb.substring(delimiter.length());
}
/**
* Sanitize filename by removing path.
* e.g. ../../sun.gif becomes sun.gif
*
* @param filename The filename to be sanitized
* @return The sanitized filename
*/
public String sanitizeFilename(String filename) {
return filename.replaceAll(".*[/\\\\]", "");
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* "* / *" is also default to JSON
* @param mime MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public boolean isJsonMime(String mime) {
String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$";
return mime != null && (mime.matches(jsonMime) || mime.equals("*/*"));
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly).
*/
public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
if (isJsonMime(accept)) {
return accept;
}
}
return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty,
* returns null. If it matches "any", JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return null;
}
if (contentTypes[0].equals("*/*")) {
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
return contentType;
}
}
return contentTypes[0];
}
/**
* Escape the given string to be used as URL query value.
*
* @param str String to be escaped
* @return Escaped string
*/
public String escapeString(String str) {
try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
return str;
}
}
/**
* Deserialize response body to Java object, according to the return type and
* the Content-Type response header.
*
* @param <T> Type
* @param response HTTP response
* @param returnType The type of the Java object
* @return The deserialized Java object
* @throws ai.fideo.client.ApiException If fail to deserialize response body, i.e. cannot read response body
* or the Content-Type of the response is not supported.
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null) {
return null;
}
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading.
return (T) downloadFileFromResponse(response);
}
String respBody;
try {
if (response.body() != null)
respBody = response.body().string();
else
respBody = null;
} catch (IOException e) {
throw new ApiException(e);
}
if (respBody == null || "".equals(respBody)) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
// ensuring a default content type
contentType = "application/json";
}
if (isJsonMime(contentType)) {
return JSON.deserialize(respBody, returnType);
} else if (returnType.equals(String.class)) {
// Expecting string, return the raw response body.
return (T) respBody;
} else {
throw new ApiException(
"Content type \"" + contentType + "\" is not supported for type: " + returnType,
response.code(),
response.headers().toMultimap(),
respBody);
}
}
/**
* Serialize the given Java object into request body according to the object's
* class and the request Content-Type.
*
* @param obj The Java object
* @param contentType The request Content-Type
* @return The serialized request body
* @throws ai.fideo.client.ApiException If fail to serialize the given object
*/
public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (obj instanceof byte[]) {
// Binary (byte array) body parameter support.
return RequestBody.create((byte[]) obj, MediaType.parse(contentType));
} else if (obj instanceof File) {
// File body parameter support.
return RequestBody.create((File) obj, MediaType.parse(contentType));
} else if ("text/plain".equals(contentType) && obj instanceof String) {
return RequestBody.create((String) obj, MediaType.parse(contentType));
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = JSON.serialize(obj);
} else {
content = null;
}
return RequestBody.create(content, MediaType.parse(contentType));
} else if (obj instanceof String) {
return RequestBody.create((String) obj, MediaType.parse(contentType));
} else {
throw new ApiException("Content type \"" + contentType + "\" is not supported");
}
}
/**
* Download file from the given response.
*
* @param response An instance of the Response object
* @throws ai.fideo.client.ApiException If fail to read file content from response and write to disk
* @return Downloaded file
*/
public File downloadFileFromResponse(Response response) throws ApiException {
try {
File file = prepareDownloadFile(response);
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
return file;
} catch (IOException e) {
throw new ApiException(e);
}
}
/**
* Prepare file for download
*
* @param response An instance of the Response object
* @return Prepared file for the download
* @throws java.io.IOException If fail to prepare file for download
*/
public File prepareDownloadFile(Response response) throws IOException {
String filename = null;
String contentDisposition = response.header("Content-Disposition");
if (contentDisposition != null && !"".equals(contentDisposition)) {
// Get filename from the Content-Disposition header.
Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
Matcher matcher = pattern.matcher(contentDisposition);
if (matcher.find()) {
filename = sanitizeFilename(matcher.group(1));
}
}
String prefix = null;
String suffix = null;
if (filename == null) {
prefix = "download-";
suffix = "";
} else {
int pos = filename.lastIndexOf(".");
if (pos == -1) {
prefix = filename + "-";
} else {
prefix = filename.substring(0, pos) + "-";
suffix = filename.substring(pos);
}
// Files.createTempFile requires the prefix to be at least three characters long
if (prefix.length() < 3)
prefix = "download-";
}
if (tempFolderPath == null)
return Files.createTempFile(prefix, suffix).toFile();
else
return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile();
}
/**
* {@link #execute(Call, Type)}
*
* @param <T> Type
* @param call An instance of the Call object
* @return ApiResponse<T>
* @throws ai.fideo.client.ApiException If fail to execute the call
*/
public <T> ApiResponse<T> execute(Call call) throws ApiException {
return execute(call, null);
}
/**
* Execute HTTP call and deserialize the HTTP response body into the given return type.
*
* @param returnType The return type used to deserialize HTTP response body
* @param <T> The return type corresponding to (same with) returnType
* @param call Call
* @return ApiResponse object containing response status, headers and
* data, which is a Java object deserialized from response body and would be null
* when returnType is null.
* @throws ai.fideo.client.ApiException If fail to execute the call
*/
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
try {
Response response = call.execute();
T data = handleResponse(response, returnType);
return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
} catch (IOException e) {
throw new ApiException(e);
}
}
/**
* {@link #executeAsync(Call, Type, ApiCallback)}
*
* @param <T> Type
* @param call An instance of the Call object
* @param callback ApiCallback<T>
*/
public <T> void executeAsync(Call call, ApiCallback<T> callback) {
executeAsync(call, null, callback);
}
/**
* Execute HTTP call asynchronously.
*
* @param <T> Type
* @param call The callback to be executed when the API call finishes
* @param returnType Return type
* @param callback ApiCallback
* @see #execute(Call, Type)
*/
@SuppressWarnings("unchecked")
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(new ApiException(e), 0, null);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
T result;
try {
result = (T) handleResponse(response, returnType);
} catch (ApiException e) {
callback.onFailure(e, response.code(), response.headers().toMultimap());
return;
} catch (Exception e) {
callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap());
return;
}
callback.onSuccess(result, response.code(), response.headers().toMultimap());
}
});
}
/**
* Handle the given response, return the deserialized object when the response is successful.
*
* @param <T> Type
* @param response Response
* @param returnType Return type
* @return Type
* @throws ai.fideo.client.ApiException If the response has an unsuccessful status code or
* fail to deserialize the response body
*/
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
if (response.isSuccessful()) {
if (returnType == null || response.code() == 204) {
// returning null if the returnType is not defined,
// or the status code is 204 (No Content)
if (response.body() != null) {
try {
response.body().close();
} catch (Exception e) {
throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
}
}
return null;
} else {
return deserialize(response, returnType);
}
} else {
String respBody = null;
if (response.body() != null) {
try {
respBody = response.body().string();
} catch (IOException e) {
throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
}
}
throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
}
}
/**
* Build HTTP call with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
* @param collectionQueryParams The collection query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param cookieParams The cookie parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param callback Callback for upload/download progress
* @return The HTTP call
* @throws ai.fideo.client.ApiException If fail to serialize the request body object
*/
public Call buildCall(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback);
return httpClient.newCall(request);
}
/**
* Build an HTTP request with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
* @param collectionQueryParams The collection query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param cookieParams The cookie parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param callback Callback for upload/download progress
* @return The HTTP request
* @throws ai.fideo.client.ApiException If fail to serialize the request body object
*/
public Request buildRequest(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams);
// prepare HTTP request body
RequestBody reqBody;
String contentType = headerParams.get("Content-Type");
String contentTypePure = contentType;
if (contentTypePure != null && contentTypePure.contains(";")) {
contentTypePure = contentType.substring(0, contentType.indexOf(";"));
}
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentTypePure)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentTypePure)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {
// allow calling DELETE without sending a request body
reqBody = null;
} else {
// use an empty request body (for POST, PUT and PATCH)
reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType));
}
} else {
reqBody = serialize(body, contentType);
}
List<Pair> updatedQueryParams = new ArrayList<>(queryParams);
// update parameters with authentication settings
updateParamsForAuth(authNames, updatedQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url));
final Request.Builder reqBuilder = new Request.Builder().url(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams));
processHeaderParams(headerParams, reqBuilder);
processCookieParams(cookieParams, reqBuilder);
// Associate callback with request (if not null) so interceptor can
// access it when creating ProgressResponseBody
reqBuilder.tag(callback);
Request request = null;
if (callback != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback);
request = reqBuilder.method(method, progressRequestBody).build();
} else {
request = reqBuilder.method(method, reqBody).build();
}
return request;
}
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param baseUrl The base URL
* @param path The sub path
* @param queryParams The query parameters
* @param collectionQueryParams The collection query parameters
* @return The full URL
*/
public String buildUrl(String baseUrl, String path, List<Pair> queryParams, List<Pair> collectionQueryParams) {
final StringBuilder url = new StringBuilder();
if (baseUrl != null) {
url.append(baseUrl).append(path);
} else {
String baseURL;
if (serverIndex != null) {
if (serverIndex < 0 || serverIndex >= servers.size()) {
throw new ArrayIndexOutOfBoundsException(String.format(
"Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size()
));
}
baseURL = servers.get(serverIndex).URL(serverVariables);
} else {
baseURL = basePath;
}
url.append(baseURL).append(path);
}
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) {
String prefix = url.toString().contains("?") ? "&" : "?";
for (Pair param : collectionQueryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
// collection query parameter value already escaped as part of parameterToPairs
url.append(escapeString(param.getName())).append("=").append(value);
}
}
}
return url.toString();
}
/**
* Set header parameters to the request builder, including default headers.
*
* @param headerParams Header parameters in the form of Map
* @param reqBuilder Request.Builder
*/
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : headerParams.entrySet()) {
reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
}
for (Entry<String, String> header : defaultHeaderMap.entrySet()) {
if (!headerParams.containsKey(header.getKey())) {
reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
}
}
}
/**
* Set cookie parameters to the request builder, including default cookies.
*
* @param cookieParams Cookie parameters in the form of Map
* @param reqBuilder Request.Builder
*/
public void processCookieParams(Map<String, String> cookieParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : cookieParams.entrySet()) {
reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue()));
}
for (Entry<String, String> param : defaultCookieMap.entrySet()) {
if (!cookieParams.containsKey(param.getKey())) {
reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue()));
}
}
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param cookieParams Map of cookie parameters
* @param payload HTTP request body
* @param method HTTP method
* @param uri URI
* @throws ai.fideo.client.ApiException If fails to update the parameters
*/
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams,
Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) {
throw new RuntimeException("Authentication undefined: " + authName);
}
auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri);
}
}
/**
* Build a form-encoding request body with the given form parameters.
*
* @param formParams Form parameters in the form of Map
* @return RequestBody
*/
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder();
for (Entry<String, Object> param : formParams.entrySet()) {
formBuilder.add(param.getKey(), parameterToString(param.getValue()));
}
return formBuilder.build();
}
/**
* Build a multipart (file uploading) request body with the given form parameters,
* which could contain text fields and file fields.
*
* @param formParams Form parameters in the form of Map
* @return RequestBody
*/
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (Entry<String, Object> param : formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
addPartToMultiPartBuilder(mpBuilder, param.getKey(), file);
} else if (param.getValue() instanceof List) {
List list = (List) param.getValue();
for (Object item: list) {
if (item instanceof File) {
addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item);
} else {
addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue());
}
}
} else {
addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue());
}
}
return mpBuilder.build();
}
/**
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
*
* @param file The given file
* @return The guessed Content-Type
*/
public String guessContentTypeFromFile(File file) {
String contentType = URLConnection.guessContentTypeFromName(file.getName());
if (contentType == null) {
return "application/octet-stream";
} else {
return contentType;
}
}
/**
* Add a Content-Disposition Header for the given key and file to the MultipartBody Builder.
*
* @param mpBuilder MultipartBody.Builder
* @param key The key of the Header element
* @param file The file to add to the Header
*/
private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) {
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\"");
MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType));
}
/**
* Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder.
*
* @param mpBuilder MultipartBody.Builder
* @param key The key of the Header element
* @param obj The complex object to add to the Header
*/
private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) {
RequestBody requestBody;
if (obj instanceof String) {
requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain"));
} else {
String content;
if (obj != null) {
content = JSON.serialize(obj);
} else {
content = null;
}
requestBody = RequestBody.create(content, MediaType.parse("application/json"));
}
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"");
mpBuilder.addPart(partHeaders, requestBody);
}
/**
* Get network interceptor to add it to the httpClient to track download progress for
* async requests.
*/
private Interceptor getProgressInterceptor() {
return new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
final Request request = chain.request();
final Response originalResponse = chain.proceed(request);
if (request.tag() instanceof ApiCallback) {
final ApiCallback callback = (ApiCallback) request.tag();
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), callback))
.build();
}
return originalResponse;
}
};
}
/**
* Apply SSL related settings to httpClient according to the current values of
* verifyingSsl and sslCaCert.
*/
private void applySslSettings() {
try {
TrustManager[] trustManagers;
HostnameVerifier hostnameVerifier;
if (!verifyingSsl) {
trustManagers = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
} else {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
if (sslCaCert == null) {
trustManagerFactory.init((KeyStore) null);
} else {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
KeyStore caKeyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = "ca" + (index++);
caKeyStore.setCertificateEntry(certificateAlias, certificate);
}
trustManagerFactory.init(caKeyStore);
}
trustManagers = trustManagerFactory.getTrustManagers();
hostnameVerifier = OkHostnameVerifier.INSTANCE;
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
httpClient = httpClient.newBuilder()
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0])
.hostnameVerifier(hostnameVerifier)
.build();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, password);
return keyStore;
} catch (IOException e) {
throw new AssertionError(e);
}
}
/**
* Convert the HTTP request body to a string.
*
* @param requestBody The HTTP request object
* @return The string representation of the HTTP request body
* @throws ai.fideo.client.ApiException If fail to serialize the request body object into a string
*/
private String requestBodyToString(RequestBody requestBody) throws ApiException {
if (requestBody != null) {
try {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
throw new ApiException(e);
}
}
// empty http request body
return "";
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ApiException.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import java.util.Map;
import java.util.List;
/**
* <p>ApiException class.</p>
*/
@SuppressWarnings("serial")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class ApiException extends Exception {
private static final long serialVersionUID = 1L;
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
/**
* <p>Constructor for ApiException.</p>
*/
public ApiException() {}
/**
* <p>Constructor for ApiException.</p>
*
* @param throwable a {@link java.lang.Throwable} object
*/
public ApiException(Throwable throwable) {
super(throwable);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
*/
public ApiException(String message) {
super(message);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param throwable a {@link java.lang.Throwable} object
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param throwable a {@link java.lang.Throwable} object
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
*/
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param message a {@link java.lang.String} object
*/
public ApiException(int code, String message) {
super(message);
this.code = code;
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param message the error message
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message);
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Get the HTTP response headers.
*
* @return A map of list of string
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*
* @return Response body in the form of string
*/
public String getResponseBody() {
return responseBody;
}
/**
* Get the exception message including HTTP response data.
*
* @return The exception message
*/
public String getMessage() {
return String.format("Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s",
super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders());
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ApiResponse.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import java.util.List;
import java.util.Map;
/**
* API response returned by API call.
*/
public class ApiResponse<T> {
final private int statusCode;
final private Map<String, List<String>> headers;
final private T data;
/**
* <p>Constructor for ApiResponse.</p>
*
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers) {
this(statusCode, headers, null);
}
/**
* <p>Constructor for ApiResponse.</p>
*
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
* @param data The object deserialized from response bod
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) {
this.statusCode = statusCode;
this.headers = headers;
this.data = data;
}
/**
* <p>Get the <code>status code</code>.</p>
*
* @return the status code
*/
public int getStatusCode() {
return statusCode;
}
/**
* <p>Get the <code>headers</code>.</p>
*
* @return a {@link java.util.Map} of headers
*/
public Map<String, List<String>> getHeaders() {
return headers;
}
/**
* <p>Get the <code>data</code>.</p>
*
* @return the data
*/
public T getData() {
return data;
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/Configuration.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Configuration {
public static final String VERSION = "1.0.4";
private static ApiClient defaultApiClient = new ApiClient();
/**
* Get the default API client, which would be used when creating API
* instances without providing an API client.
*
* @return Default API client
*/
public static ApiClient getDefaultApiClient() {
return defaultApiClient;
}
/**
* Set the default API client, which would be used when creating API
* instances without providing an API client.
*
* @param apiClient API client
*/
public static void setDefaultApiClient(ApiClient apiClient) {
defaultApiClient = apiClient;
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/GzipRequestInterceptor.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSink;
import okio.GzipSink;
import okio.Okio;
import java.io.IOException;
/**
* Encodes request bodies using gzip.
*
* Taken from https://github.com/square/okhttp/issues/350
*/
class GzipRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), forceContentLength(gzip(originalRequest.body())))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer.snapshot());
}
};
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override
public MediaType contentType() {
return body.contentType();
}
@Override
public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/JSON.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.JsonElement;
import io.gsonfire.GsonFireBuilder;
import io.gsonfire.TypeSelector;
import okio.ByteString;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
/*
* A JSON utility class
*
* NOTE: in the future, this class may be converted to static, which may break
* backward-compatibility
*/
public class JSON {
private static Gson gson;
private static boolean isLenientOnJson = false;
private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
@SuppressWarnings("unchecked")
public static GsonBuilder createGson() {
GsonFireBuilder fireBuilder = new GsonFireBuilder()
;
GsonBuilder builder = fireBuilder.createGsonBuilder();
return builder;
}
private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) {
JsonElement element = readElement.getAsJsonObject().get(discriminatorField);
if (null == element) {
throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">");
}
return element.getAsString();
}
/**
* Returns the Java class that implements the OpenAPI schema for the specified discriminator value.
*
* @param classByDiscriminatorValue The map of discriminator values to Java classes.
* @param discriminatorValue The value of the OpenAPI discriminator in the input data.
* @return The Java class that implements the OpenAPI schema
*/
private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) {
Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue);
if (null == clazz) {
throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">");
}
return clazz;
}
static {
GsonBuilder gsonBuilder = createGson();
gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter);
gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter);
gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter);
gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter);
gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter);
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Alias.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Demographics.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Economic.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Education.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.EducationDate.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Email.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Employment.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.EmploymentDate.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Evidence.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.IpAddress.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Location.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.LocationReq.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.MultiFieldReqWithOptions.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Name.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.NameWithAlias.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.PersonNameReq.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Phone.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.Photo.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.ScoreDetails.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.SignalsPost200Response.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.SignalsResponseV0.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.SignalsResponseV20240424.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.SocialProfileDetails.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.SocialProfileReq.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.SocialProfileUrls.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new ai.fideo.model.VerifyResponse.CustomTypeAdapterFactory());
gson = gsonBuilder.create();
}
/**
* Get Gson.
*
* @return Gson
*/
public static Gson getGson() {
return gson;
}
/**
* Set Gson.
*
* @param gson Gson
*/
public static void setGson(Gson gson) {
JSON.gson = gson;
}
public static void setLenientOnJson(boolean lenientOnJson) {
isLenientOnJson = lenientOnJson;
}
/**
* Serialize the given Java object into JSON string.
*
* @param obj Object
* @return String representation of the JSON
*/
public static String serialize(Object obj) {
return gson.toJson(obj);
}
/**
* Deserialize the given JSON string to Java object.
*
* @param <T> Type
* @param body The JSON string
* @param returnType The type to deserialize into
* @return The deserialized Java object
*/
@SuppressWarnings("unchecked")
public static <T> T deserialize(String body, Type returnType) {
try {
if (isLenientOnJson) {
JsonReader jsonReader = new JsonReader(new StringReader(body));
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
jsonReader.setLenient(true);
return gson.fromJson(jsonReader, returnType);
} else {
return gson.fromJson(body, returnType);
}
} catch (JsonParseException e) {
// Fallback processing when failed to parse JSON form response body:
// return the response body string directly for the String return type;
if (returnType.equals(String.class)) {
return (T) body;
} else {
throw (e);
}
}
}
/**
* Gson TypeAdapter for Byte Array type
*/
public static class ByteArrayAdapter extends TypeAdapter<byte[]> {
@Override
public void write(JsonWriter out, byte[] value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(ByteString.of(value).base64());
}
}
@Override
public byte[] read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String bytesAsBase64 = in.nextString();
ByteString byteString = ByteString.decodeBase64(bytesAsBase64);
return byteString.toByteArray();
}
}
}
/**
* Gson TypeAdapter for JSR310 OffsetDateTime type
*/
public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
private DateTimeFormatter formatter;
public OffsetDateTimeTypeAdapter() {
this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public OffsetDateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
if (date.endsWith("+0000")) {
date = date.substring(0, date.length()-5) + "Z";
}
return OffsetDateTime.parse(date, formatter);
}
}
}
/**
* Gson TypeAdapter for JSR310 LocalDate type
*/
public static class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private DateTimeFormatter formatter;
public LocalDateTypeAdapter() {
this(DateTimeFormatter.ISO_LOCAL_DATE);
}
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return LocalDate.parse(date, formatter);
}
}
}
public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
offsetDateTimeTypeAdapter.setFormat(dateFormat);
}
public static void setLocalDateFormat(DateTimeFormatter dateFormat) {
localDateTypeAdapter.setFormat(dateFormat);
}
/**
* Gson TypeAdapter for java.sql.Date type
* If the dateFormat is null, a simple "yyyy-MM-dd" format will be used
* (more efficient than SimpleDateFormat).
*/
public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
private DateFormat dateFormat;
public SqlDateTypeAdapter() {}
public SqlDateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, java.sql.Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = date.toString();
}
out.value(value);
}
}
@Override
public java.sql.Date read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
}
/**
* Gson TypeAdapter for java.util.Date type
* If the dateFormat is null, ISO8601Utils will be used.
*/
public static class DateTypeAdapter extends TypeAdapter<Date> {
private DateFormat dateFormat;
public DateTypeAdapter() {}
public DateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = ISO8601Utils.format(date, true);
}
out.value(value);
}
}
@Override
public Date read(JsonReader in) throws IOException {
try {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
} catch (IllegalArgumentException e) {
throw new JsonParseException(e);
}
}
}
public static void setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
}
public static void setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/Pair.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Pair {
private String name = "";
private String value = "";
public Pair (String name, String value) {
setName(name);
setValue(value);
}
private void setName(String name) {
if (!isValidString(name)) {
return;
}
this.name = name;
}
private void setValue(String value) {
if (!isValidString(value)) {
return;
}
this.value = value;
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
private boolean isValidString(String arg) {
if (arg == null) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ProgressRequestBody.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
public class ProgressRequestBody extends RequestBody {
private final RequestBody requestBody;
private final ApiCallback callback;
public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) {
this.requestBody = requestBody;
this.callback = callback;
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength);
}
};
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ProgressResponseBody.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
public class ProgressResponseBody extends ResponseBody {
private final ResponseBody responseBody;
private final ApiCallback callback;
private BufferedSource bufferedSource;
public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) {
this.responseBody = responseBody;
this.callback = callback;
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() {
return responseBody.contentLength();
}
@Override
public BufferedSource source() {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ServerConfiguration.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import java.util.Map;
/**
* Representing a Server configuration.
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class ServerConfiguration {
public String URL;
public String description;
public Map<String, ServerVariable> variables;
/**
* @param URL A URL to the target host.
* @param description A description of the host designated by the URL.
* @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
*/
public ServerConfiguration(String URL, String description, Map<String, ServerVariable> variables) {
this.URL = URL;
this.description = description;
this.variables = variables;
}
/**
* Format URL template using given variables.
*
* @param variables A map between a variable name and its value.
* @return Formatted URL.
*/
public String URL(Map<String, String> variables) {
String url = this.URL;
// go through variables and replace placeholders
for (Map.Entry<String, ServerVariable> variable: this.variables.entrySet()) {
String name = variable.getKey();
ServerVariable serverVariable = variable.getValue();
String value = serverVariable.defaultValue;
if (variables != null && variables.containsKey(name)) {
value = variables.get(name);
if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) {
throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + ".");
}
}
url = url.replace("{" + name + "}", value);
}
return url;
}
/**
* Format URL template using default server variables.
*
* @return Formatted URL.
*/
public String URL() {
return URL(null);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/ServerVariable.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import java.util.HashSet;
/**
* Representing a Server Variable for server URL template substitution.
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class ServerVariable {
public String description;
public String defaultValue;
public HashSet<String> enumValues = null;
/**
* @param description A description for the server variable.
* @param defaultValue The default value to use for substitution.
* @param enumValues An enumeration of string values to be used if the substitution options are from a limited set.
*/
public ServerVariable(String description, String defaultValue, HashSet<String> enumValues) {
this.description = description;
this.defaultValue = defaultValue;
this.enumValues = enumValues;
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/StringUtil.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client;
import java.util.Collection;
import java.util.Iterator;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class StringUtil {
/**
* Check if the given array contains the given value (with case-insensitive comparison).
*
* @param array The array
* @param value The value to search
* @return true if the array contains the value
*/
public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) {
return true;
}
if (value != null && value.equalsIgnoreCase(str)) {
return true;
}
}
return false;
}
/**
* Join an array of strings with the given separator.
* <p>
* Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency.
* </p>
*
* @param array The array of strings
* @param separator The separator
* @return the resulting string
*/
public static String join(String[] array, String separator) {
int len = array.length;
if (len == 0) {
return "";
}
StringBuilder out = new StringBuilder();
out.append(array[0]);
for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]);
}
return out.toString();
}
/**
* Join a list of strings with the given separator.
*
* @param list The list of strings
* @param separator The separator
* @return the resulting string
*/
public static String join(Collection<String> list, String separator) {
Iterator<String> iterator = list.iterator();
StringBuilder out = new StringBuilder();
if (iterator.hasNext()) {
out.append(iterator.next());
}
while (iterator.hasNext()) {
out.append(separator).append(iterator.next());
}
return out.toString();
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/auth/ApiKeyAuth.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client.auth;
import ai.fideo.client.ApiException;
import ai.fideo.client.Pair;
import java.net.URI;
import java.util.Map;
import java.util.List;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if ("query".equals(location)) {
queryParams.add(new Pair(paramName, value));
} else if ("header".equals(location)) {
headerParams.put(paramName, value);
} else if ("cookie".equals(location)) {
cookieParams.put(paramName, value);
}
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/auth/Authentication.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client.auth;
import ai.fideo.client.Pair;
import ai.fideo.client.ApiException;
import java.net.URI;
import java.util.Map;
import java.util.List;
public interface Authentication {
/**
* Apply authentication settings to header and query params.
*
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param cookieParams Map of cookie parameters
* @param payload HTTP request body
* @param method HTTP method
* @param uri URI
* @throws ApiException if failed to update the parameters
*/
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException;
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/auth/HttpBasicAuth.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client.auth;
import ai.fideo.client.Pair;
import ai.fideo.client.ApiException;
import okhttp3.Credentials;
import java.net.URI;
import java.util.Map;
import java.util.List;
public class HttpBasicAuth implements Authentication {
private String username;
private 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;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (username == null && password == null) {
return;
}
headerParams.put("Authorization", Credentials.basic(
username == null ? "" : username,
password == null ? "" : password));
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/client/auth/HttpBearerAuth.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.client.auth;
import ai.fideo.client.ApiException;
import ai.fideo.client.Pair;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class HttpBearerAuth implements Authentication {
private final String scheme;
private Supplier<String> tokenSupplier;
public HttpBearerAuth(String scheme) {
this.scheme = scheme;
}
/**
* Gets the token, which together with the scheme, will be sent as the value of the Authorization header.
*
* @return The bearer token
*/
public String getBearerToken() {
return tokenSupplier.get();
}
/**
* Sets the token, which together with the scheme, will be sent as the value of the Authorization header.
*
* @param bearerToken The bearer token to send in the Authorization header
*/
public void setBearerToken(String bearerToken) {
this.tokenSupplier = () -> bearerToken;
}
/**
* Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header.
*
* @param tokenSupplier The supplier of bearer tokens to send in the Authorization header
*/
public void setBearerToken(Supplier<String> tokenSupplier) {
this.tokenSupplier = tokenSupplier;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null);
if (bearerToken == null) {
return;
}
headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken);
}
private static String upperCaseBearer(String scheme) {
return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme;
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/AbstractOpenApiSchema.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import ai.fideo.client.ApiException;
import java.util.Objects;
import java.lang.reflect.Type;
import java.util.Map;
/**
* Abstract class for oneOf,anyOf schemas defined in OpenAPI spec
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public abstract class AbstractOpenApiSchema {
// store the actual instance of the schema/object
private Object instance;
// is nullable
private Boolean isNullable;
// schema type (e.g. oneOf, anyOf)
private final String schemaType;
public AbstractOpenApiSchema(String schemaType, Boolean isNullable) {
this.schemaType = schemaType;
this.isNullable = isNullable;
}
/**
* Get the list of oneOf/anyOf composed schemas allowed to be stored in this object
*
* @return an instance of the actual schema/object
*/
public abstract Map<String, Class<?>> getSchemas();
/**
* Get the actual instance
*
* @return an instance of the actual schema/object
*/
//@JsonValue
public Object getActualInstance() {return instance;}
/**
* Set the actual instance
*
* @param instance the actual instance of the schema/object
*/
public void setActualInstance(Object instance) {this.instance = instance;}
/**
* Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well
*
* @return an instance of the actual schema/object
*/
public Object getActualInstanceRecursively() {
return getActualInstanceRecursively(this);
}
private Object getActualInstanceRecursively(AbstractOpenApiSchema object) {
if (object.getActualInstance() == null) {
return null;
} else if (object.getActualInstance() instanceof AbstractOpenApiSchema) {
return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance());
} else {
return object.getActualInstance();
}
}
/**
* Get the schema type (e.g. anyOf, oneOf)
*
* @return the schema type
*/
public String getSchemaType() {
return schemaType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ").append(getClass()).append(" {\n");
sb.append(" instance: ").append(toIndentedString(instance)).append("\n");
sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n");
sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractOpenApiSchema a = (AbstractOpenApiSchema) o;
return Objects.equals(this.instance, a.instance) &&
Objects.equals(this.isNullable, a.isNullable) &&
Objects.equals(this.schemaType, a.schemaType);
}
@Override
public int hashCode() {
return Objects.hash(instance, isNullable, schemaType);
}
/**
* Is nullable
*
* @return true if it's nullable
*/
public Boolean isNullable() {
if (Boolean.TRUE.equals(isNullable)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Alias.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Alias
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Alias {
public static final String SERIALIZED_NAME_FIRST = "first";
@SerializedName(SERIALIZED_NAME_FIRST)
private String first;
public static final String SERIALIZED_NAME_LAST = "last";
@SerializedName(SERIALIZED_NAME_LAST)
private String last;
public static final String SERIALIZED_NAME_MIDDLE = "middle";
@SerializedName(SERIALIZED_NAME_MIDDLE)
private String middle;
public Alias() {
}
public Alias first(String first) {
this.first = first;
return this;
}
/**
* Get first
* @return first
*/
@javax.annotation.Nullable
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public Alias last(String last) {
this.last = last;
return this;
}
/**
* Get last
* @return last
*/
@javax.annotation.Nullable
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public Alias middle(String middle) {
this.middle = middle;
return this;
}
/**
* Get middle
* @return middle
*/
@javax.annotation.Nullable
public String getMiddle() {
return middle;
}
public void setMiddle(String middle) {
this.middle = middle;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Alias alias = (Alias) o;
return Objects.equals(this.first, alias.first) &&
Objects.equals(this.last, alias.last) &&
Objects.equals(this.middle, alias.middle);
}
@Override
public int hashCode() {
return Objects.hash(first, last, middle);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Alias {\n");
sb.append(" first: ").append(toIndentedString(first)).append("\n");
sb.append(" last: ").append(toIndentedString(last)).append("\n");
sb.append(" middle: ").append(toIndentedString(middle)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("first");
openapiFields.add("last");
openapiFields.add("middle");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Alias
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Alias.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Alias is not found in the empty JSON string", Alias.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Alias.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Alias` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("first") != null && !jsonObj.get("first").isJsonNull()) && !jsonObj.get("first").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `first` to be a primitive type in the JSON string but got `%s`", jsonObj.get("first").toString()));
}
if ((jsonObj.get("last") != null && !jsonObj.get("last").isJsonNull()) && !jsonObj.get("last").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `last` to be a primitive type in the JSON string but got `%s`", jsonObj.get("last").toString()));
}
if ((jsonObj.get("middle") != null && !jsonObj.get("middle").isJsonNull()) && !jsonObj.get("middle").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `middle` to be a primitive type in the JSON string but got `%s`", jsonObj.get("middle").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Alias.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Alias' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Alias> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Alias.class));
return (TypeAdapter<T>) new TypeAdapter<Alias>() {
@Override
public void write(JsonWriter out, Alias value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Alias read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Alias given an JSON string
*
* @param jsonString JSON string
* @return An instance of Alias
* @throws IOException if the JSON string is invalid with respect to Alias
*/
public static Alias fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Alias.class);
}
/**
* Convert an instance of Alias to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Demographics.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Demographics
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Demographics {
public static final String SERIALIZED_NAME_AGE = "age";
@SerializedName(SERIALIZED_NAME_AGE)
private Integer age;
public static final String SERIALIZED_NAME_AGE_RANGE = "ageRange";
@SerializedName(SERIALIZED_NAME_AGE_RANGE)
private String ageRange;
public static final String SERIALIZED_NAME_GENDER = "gender";
@SerializedName(SERIALIZED_NAME_GENDER)
private String gender;
public static final String SERIALIZED_NAME_LOCATION_GENERAL = "locationGeneral";
@SerializedName(SERIALIZED_NAME_LOCATION_GENERAL)
private String locationGeneral;
public Demographics() {
}
public Demographics age(Integer age) {
this.age = age;
return this;
}
/**
* Get age
* @return age
*/
@javax.annotation.Nullable
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Demographics ageRange(String ageRange) {
this.ageRange = ageRange;
return this;
}
/**
* Get ageRange
* @return ageRange
*/
@javax.annotation.Nullable
public String getAgeRange() {
return ageRange;
}
public void setAgeRange(String ageRange) {
this.ageRange = ageRange;
}
public Demographics gender(String gender) {
this.gender = gender;
return this;
}
/**
* Get gender
* @return gender
*/
@javax.annotation.Nullable
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Demographics locationGeneral(String locationGeneral) {
this.locationGeneral = locationGeneral;
return this;
}
/**
* Get locationGeneral
* @return locationGeneral
*/
@javax.annotation.Nullable
public String getLocationGeneral() {
return locationGeneral;
}
public void setLocationGeneral(String locationGeneral) {
this.locationGeneral = locationGeneral;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Demographics demographics = (Demographics) o;
return Objects.equals(this.age, demographics.age) &&
Objects.equals(this.ageRange, demographics.ageRange) &&
Objects.equals(this.gender, demographics.gender) &&
Objects.equals(this.locationGeneral, demographics.locationGeneral);
}
@Override
public int hashCode() {
return Objects.hash(age, ageRange, gender, locationGeneral);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Demographics {\n");
sb.append(" age: ").append(toIndentedString(age)).append("\n");
sb.append(" ageRange: ").append(toIndentedString(ageRange)).append("\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n");
sb.append(" locationGeneral: ").append(toIndentedString(locationGeneral)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("age");
openapiFields.add("ageRange");
openapiFields.add("gender");
openapiFields.add("locationGeneral");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Demographics
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Demographics.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Demographics is not found in the empty JSON string", Demographics.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Demographics.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Demographics` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("ageRange") != null && !jsonObj.get("ageRange").isJsonNull()) && !jsonObj.get("ageRange").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `ageRange` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ageRange").toString()));
}
if ((jsonObj.get("gender") != null && !jsonObj.get("gender").isJsonNull()) && !jsonObj.get("gender").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `gender` to be a primitive type in the JSON string but got `%s`", jsonObj.get("gender").toString()));
}
if ((jsonObj.get("locationGeneral") != null && !jsonObj.get("locationGeneral").isJsonNull()) && !jsonObj.get("locationGeneral").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `locationGeneral` to be a primitive type in the JSON string but got `%s`", jsonObj.get("locationGeneral").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Demographics.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Demographics' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Demographics> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Demographics.class));
return (TypeAdapter<T>) new TypeAdapter<Demographics>() {
@Override
public void write(JsonWriter out, Demographics value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Demographics read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Demographics given an JSON string
*
* @param jsonString JSON string
* @return An instance of Demographics
* @throws IOException if the JSON string is invalid with respect to Demographics
*/
public static Demographics fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Demographics.class);
}
/**
* Convert an instance of Demographics to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Economic.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Economic
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Economic {
public static final String SERIALIZED_NAME_DWELLING_TYPE = "dwellingType";
@SerializedName(SERIALIZED_NAME_DWELLING_TYPE)
private String dwellingType;
public static final String SERIALIZED_NAME_HOME_OWNERSHIP = "homeOwnership";
@SerializedName(SERIALIZED_NAME_HOME_OWNERSHIP)
private String homeOwnership;
public static final String SERIALIZED_NAME_MARITAL_STATUS = "maritalStatus";
@SerializedName(SERIALIZED_NAME_MARITAL_STATUS)
private String maritalStatus;
public static final String SERIALIZED_NAME_PRESENCE_OF_CHILDREN = "presenceOfChildren";
@SerializedName(SERIALIZED_NAME_PRESENCE_OF_CHILDREN)
private String presenceOfChildren;
public static final String SERIALIZED_NAME_INCOME = "income";
@SerializedName(SERIALIZED_NAME_INCOME)
private String income;
public static final String SERIALIZED_NAME_NET_WORTH = "netWorth";
@SerializedName(SERIALIZED_NAME_NET_WORTH)
private String netWorth;
public Economic() {
}
public Economic dwellingType(String dwellingType) {
this.dwellingType = dwellingType;
return this;
}
/**
* Get dwellingType
* @return dwellingType
*/
@javax.annotation.Nullable
public String getDwellingType() {
return dwellingType;
}
public void setDwellingType(String dwellingType) {
this.dwellingType = dwellingType;
}
public Economic homeOwnership(String homeOwnership) {
this.homeOwnership = homeOwnership;
return this;
}
/**
* Get homeOwnership
* @return homeOwnership
*/
@javax.annotation.Nullable
public String getHomeOwnership() {
return homeOwnership;
}
public void setHomeOwnership(String homeOwnership) {
this.homeOwnership = homeOwnership;
}
public Economic maritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
return this;
}
/**
* Get maritalStatus
* @return maritalStatus
*/
@javax.annotation.Nullable
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public Economic presenceOfChildren(String presenceOfChildren) {
this.presenceOfChildren = presenceOfChildren;
return this;
}
/**
* Get presenceOfChildren
* @return presenceOfChildren
*/
@javax.annotation.Nullable
public String getPresenceOfChildren() {
return presenceOfChildren;
}
public void setPresenceOfChildren(String presenceOfChildren) {
this.presenceOfChildren = presenceOfChildren;
}
public Economic income(String income) {
this.income = income;
return this;
}
/**
* Get income
* @return income
*/
@javax.annotation.Nullable
public String getIncome() {
return income;
}
public void setIncome(String income) {
this.income = income;
}
public Economic netWorth(String netWorth) {
this.netWorth = netWorth;
return this;
}
/**
* Get netWorth
* @return netWorth
*/
@javax.annotation.Nullable
public String getNetWorth() {
return netWorth;
}
public void setNetWorth(String netWorth) {
this.netWorth = netWorth;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Economic economic = (Economic) o;
return Objects.equals(this.dwellingType, economic.dwellingType) &&
Objects.equals(this.homeOwnership, economic.homeOwnership) &&
Objects.equals(this.maritalStatus, economic.maritalStatus) &&
Objects.equals(this.presenceOfChildren, economic.presenceOfChildren) &&
Objects.equals(this.income, economic.income) &&
Objects.equals(this.netWorth, economic.netWorth);
}
@Override
public int hashCode() {
return Objects.hash(dwellingType, homeOwnership, maritalStatus, presenceOfChildren, income, netWorth);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Economic {\n");
sb.append(" dwellingType: ").append(toIndentedString(dwellingType)).append("\n");
sb.append(" homeOwnership: ").append(toIndentedString(homeOwnership)).append("\n");
sb.append(" maritalStatus: ").append(toIndentedString(maritalStatus)).append("\n");
sb.append(" presenceOfChildren: ").append(toIndentedString(presenceOfChildren)).append("\n");
sb.append(" income: ").append(toIndentedString(income)).append("\n");
sb.append(" netWorth: ").append(toIndentedString(netWorth)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("dwellingType");
openapiFields.add("homeOwnership");
openapiFields.add("maritalStatus");
openapiFields.add("presenceOfChildren");
openapiFields.add("income");
openapiFields.add("netWorth");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Economic
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Economic.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Economic is not found in the empty JSON string", Economic.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Economic.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Economic` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("dwellingType") != null && !jsonObj.get("dwellingType").isJsonNull()) && !jsonObj.get("dwellingType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `dwellingType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("dwellingType").toString()));
}
if ((jsonObj.get("homeOwnership") != null && !jsonObj.get("homeOwnership").isJsonNull()) && !jsonObj.get("homeOwnership").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `homeOwnership` to be a primitive type in the JSON string but got `%s`", jsonObj.get("homeOwnership").toString()));
}
if ((jsonObj.get("maritalStatus") != null && !jsonObj.get("maritalStatus").isJsonNull()) && !jsonObj.get("maritalStatus").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `maritalStatus` to be a primitive type in the JSON string but got `%s`", jsonObj.get("maritalStatus").toString()));
}
if ((jsonObj.get("presenceOfChildren") != null && !jsonObj.get("presenceOfChildren").isJsonNull()) && !jsonObj.get("presenceOfChildren").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `presenceOfChildren` to be a primitive type in the JSON string but got `%s`", jsonObj.get("presenceOfChildren").toString()));
}
if ((jsonObj.get("income") != null && !jsonObj.get("income").isJsonNull()) && !jsonObj.get("income").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `income` to be a primitive type in the JSON string but got `%s`", jsonObj.get("income").toString()));
}
if ((jsonObj.get("netWorth") != null && !jsonObj.get("netWorth").isJsonNull()) && !jsonObj.get("netWorth").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `netWorth` to be a primitive type in the JSON string but got `%s`", jsonObj.get("netWorth").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Economic.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Economic' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Economic> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Economic.class));
return (TypeAdapter<T>) new TypeAdapter<Economic>() {
@Override
public void write(JsonWriter out, Economic value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Economic read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Economic given an JSON string
*
* @param jsonString JSON string
* @return An instance of Economic
* @throws IOException if the JSON string is invalid with respect to Economic
*/
public static Economic fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Economic.class);
}
/**
* Convert an instance of Economic to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Education.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.EducationDate;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Education
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Education {
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public static final String SERIALIZED_NAME_DEGREE = "degree";
@SerializedName(SERIALIZED_NAME_DEGREE)
private String degree;
public static final String SERIALIZED_NAME_END = "end";
@SerializedName(SERIALIZED_NAME_END)
private EducationDate end;
public Education() {
}
public Education name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
*/
@javax.annotation.Nullable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Education degree(String degree) {
this.degree = degree;
return this;
}
/**
* Get degree
* @return degree
*/
@javax.annotation.Nullable
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public Education end(EducationDate end) {
this.end = end;
return this;
}
/**
* Get end
* @return end
*/
@javax.annotation.Nullable
public EducationDate getEnd() {
return end;
}
public void setEnd(EducationDate end) {
this.end = end;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Education education = (Education) o;
return Objects.equals(this.name, education.name) &&
Objects.equals(this.degree, education.degree) &&
Objects.equals(this.end, education.end);
}
@Override
public int hashCode() {
return Objects.hash(name, degree, end);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Education {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" degree: ").append(toIndentedString(degree)).append("\n");
sb.append(" end: ").append(toIndentedString(end)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
openapiFields.add("degree");
openapiFields.add("end");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Education
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Education.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Education is not found in the empty JSON string", Education.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Education.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Education` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString()));
}
if ((jsonObj.get("degree") != null && !jsonObj.get("degree").isJsonNull()) && !jsonObj.get("degree").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `degree` to be a primitive type in the JSON string but got `%s`", jsonObj.get("degree").toString()));
}
// validate the optional field `end`
if (jsonObj.get("end") != null && !jsonObj.get("end").isJsonNull()) {
EducationDate.validateJsonElement(jsonObj.get("end"));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Education.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Education' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Education> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Education.class));
return (TypeAdapter<T>) new TypeAdapter<Education>() {
@Override
public void write(JsonWriter out, Education value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Education read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Education given an JSON string
*
* @param jsonString JSON string
* @return An instance of Education
* @throws IOException if the JSON string is invalid with respect to Education
*/
public static Education fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Education.class);
}
/**
* Convert an instance of Education to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/EducationDate.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* EducationDate
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class EducationDate {
public static final String SERIALIZED_NAME_YEAR = "year";
@SerializedName(SERIALIZED_NAME_YEAR)
private Integer year;
public static final String SERIALIZED_NAME_MONTH = "month";
@SerializedName(SERIALIZED_NAME_MONTH)
private Integer month;
public static final String SERIALIZED_NAME_DAY = "day";
@SerializedName(SERIALIZED_NAME_DAY)
private Integer day;
public EducationDate() {
}
public EducationDate year(Integer year) {
this.year = year;
return this;
}
/**
* Get year
* @return year
*/
@javax.annotation.Nullable
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public EducationDate month(Integer month) {
this.month = month;
return this;
}
/**
* Get month
* @return month
*/
@javax.annotation.Nullable
public Integer getMonth() {
return month;
}
public void setMonth(Integer month) {
this.month = month;
}
public EducationDate day(Integer day) {
this.day = day;
return this;
}
/**
* Get day
* @return day
*/
@javax.annotation.Nullable
public Integer getDay() {
return day;
}
public void setDay(Integer day) {
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EducationDate educationDate = (EducationDate) o;
return Objects.equals(this.year, educationDate.year) &&
Objects.equals(this.month, educationDate.month) &&
Objects.equals(this.day, educationDate.day);
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EducationDate {\n");
sb.append(" year: ").append(toIndentedString(year)).append("\n");
sb.append(" month: ").append(toIndentedString(month)).append("\n");
sb.append(" day: ").append(toIndentedString(day)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("year");
openapiFields.add("month");
openapiFields.add("day");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to EducationDate
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!EducationDate.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in EducationDate is not found in the empty JSON string", EducationDate.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!EducationDate.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `EducationDate` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!EducationDate.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'EducationDate' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<EducationDate> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(EducationDate.class));
return (TypeAdapter<T>) new TypeAdapter<EducationDate>() {
@Override
public void write(JsonWriter out, EducationDate value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public EducationDate read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of EducationDate given an JSON string
*
* @param jsonString JSON string
* @return An instance of EducationDate
* @throws IOException if the JSON string is invalid with respect to EducationDate
*/
public static EducationDate fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, EducationDate.class);
}
/**
* Convert an instance of EducationDate to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Email.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Email
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Email {
public static final String SERIALIZED_NAME_FIRST_SEEN_MS = "firstSeenMs";
@SerializedName(SERIALIZED_NAME_FIRST_SEEN_MS)
private Long firstSeenMs;
public static final String SERIALIZED_NAME_LAST_SEEN_MS = "lastSeenMs";
@SerializedName(SERIALIZED_NAME_LAST_SEEN_MS)
private Long lastSeenMs;
public static final String SERIALIZED_NAME_OBSERVATIONS = "observations";
@SerializedName(SERIALIZED_NAME_OBSERVATIONS)
private Integer observations;
public static final String SERIALIZED_NAME_CONFIDENCE = "confidence";
@SerializedName(SERIALIZED_NAME_CONFIDENCE)
private Double confidence;
public static final String SERIALIZED_NAME_VALUE = "value";
@SerializedName(SERIALIZED_NAME_VALUE)
private String value;
public static final String SERIALIZED_NAME_MD5 = "md5";
@SerializedName(SERIALIZED_NAME_MD5)
private String md5;
public static final String SERIALIZED_NAME_SHA1 = "sha1";
@SerializedName(SERIALIZED_NAME_SHA1)
private String sha1;
public static final String SERIALIZED_NAME_SHA256 = "sha256";
@SerializedName(SERIALIZED_NAME_SHA256)
private String sha256;
public static final String SERIALIZED_NAME_LABEL = "label";
@SerializedName(SERIALIZED_NAME_LABEL)
private String label;
public static final String SERIALIZED_NAME_ACTIVITY = "activity";
@SerializedName(SERIALIZED_NAME_ACTIVITY)
private Double activity;
public Email() {
}
public Email firstSeenMs(Long firstSeenMs) {
this.firstSeenMs = firstSeenMs;
return this;
}
/**
* Get firstSeenMs
* @return firstSeenMs
*/
@javax.annotation.Nullable
public Long getFirstSeenMs() {
return firstSeenMs;
}
public void setFirstSeenMs(Long firstSeenMs) {
this.firstSeenMs = firstSeenMs;
}
public Email lastSeenMs(Long lastSeenMs) {
this.lastSeenMs = lastSeenMs;
return this;
}
/**
* Get lastSeenMs
* @return lastSeenMs
*/
@javax.annotation.Nullable
public Long getLastSeenMs() {
return lastSeenMs;
}
public void setLastSeenMs(Long lastSeenMs) {
this.lastSeenMs = lastSeenMs;
}
public Email observations(Integer observations) {
this.observations = observations;
return this;
}
/**
* Get observations
* @return observations
*/
@javax.annotation.Nullable
public Integer getObservations() {
return observations;
}
public void setObservations(Integer observations) {
this.observations = observations;
}
public Email confidence(Double confidence) {
this.confidence = confidence;
return this;
}
/**
* Get confidence
* @return confidence
*/
@javax.annotation.Nullable
public Double getConfidence() {
return confidence;
}
public void setConfidence(Double confidence) {
this.confidence = confidence;
}
public Email value(String value) {
this.value = value;
return this;
}
/**
* Get value
* @return value
*/
@javax.annotation.Nullable
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Email md5(String md5) {
this.md5 = md5;
return this;
}
/**
* Get md5
* @return md5
*/
@javax.annotation.Nullable
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public Email sha1(String sha1) {
this.sha1 = sha1;
return this;
}
/**
* Get sha1
* @return sha1
*/
@javax.annotation.Nullable
public String getSha1() {
return sha1;
}
public void setSha1(String sha1) {
this.sha1 = sha1;
}
public Email sha256(String sha256) {
this.sha256 = sha256;
return this;
}
/**
* Get sha256
* @return sha256
*/
@javax.annotation.Nullable
public String getSha256() {
return sha256;
}
public void setSha256(String sha256) {
this.sha256 = sha256;
}
public Email label(String label) {
this.label = label;
return this;
}
/**
* Get label
* @return label
*/
@javax.annotation.Nullable
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Email activity(Double activity) {
this.activity = activity;
return this;
}
/**
* Get activity
* @return activity
*/
@javax.annotation.Nullable
public Double getActivity() {
return activity;
}
public void setActivity(Double activity) {
this.activity = activity;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Email email = (Email) o;
return Objects.equals(this.firstSeenMs, email.firstSeenMs) &&
Objects.equals(this.lastSeenMs, email.lastSeenMs) &&
Objects.equals(this.observations, email.observations) &&
Objects.equals(this.confidence, email.confidence) &&
Objects.equals(this.value, email.value) &&
Objects.equals(this.md5, email.md5) &&
Objects.equals(this.sha1, email.sha1) &&
Objects.equals(this.sha256, email.sha256) &&
Objects.equals(this.label, email.label) &&
Objects.equals(this.activity, email.activity);
}
@Override
public int hashCode() {
return Objects.hash(firstSeenMs, lastSeenMs, observations, confidence, value, md5, sha1, sha256, label, activity);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Email {\n");
sb.append(" firstSeenMs: ").append(toIndentedString(firstSeenMs)).append("\n");
sb.append(" lastSeenMs: ").append(toIndentedString(lastSeenMs)).append("\n");
sb.append(" observations: ").append(toIndentedString(observations)).append("\n");
sb.append(" confidence: ").append(toIndentedString(confidence)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append(" md5: ").append(toIndentedString(md5)).append("\n");
sb.append(" sha1: ").append(toIndentedString(sha1)).append("\n");
sb.append(" sha256: ").append(toIndentedString(sha256)).append("\n");
sb.append(" label: ").append(toIndentedString(label)).append("\n");
sb.append(" activity: ").append(toIndentedString(activity)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("firstSeenMs");
openapiFields.add("lastSeenMs");
openapiFields.add("observations");
openapiFields.add("confidence");
openapiFields.add("value");
openapiFields.add("md5");
openapiFields.add("sha1");
openapiFields.add("sha256");
openapiFields.add("label");
openapiFields.add("activity");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Email
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Email.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Email is not found in the empty JSON string", Email.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Email.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Email` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("value") != null && !jsonObj.get("value").isJsonNull()) && !jsonObj.get("value").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `value` to be a primitive type in the JSON string but got `%s`", jsonObj.get("value").toString()));
}
if ((jsonObj.get("md5") != null && !jsonObj.get("md5").isJsonNull()) && !jsonObj.get("md5").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `md5` to be a primitive type in the JSON string but got `%s`", jsonObj.get("md5").toString()));
}
if ((jsonObj.get("sha1") != null && !jsonObj.get("sha1").isJsonNull()) && !jsonObj.get("sha1").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `sha1` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sha1").toString()));
}
if ((jsonObj.get("sha256") != null && !jsonObj.get("sha256").isJsonNull()) && !jsonObj.get("sha256").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `sha256` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sha256").toString()));
}
if ((jsonObj.get("label") != null && !jsonObj.get("label").isJsonNull()) && !jsonObj.get("label").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `label` to be a primitive type in the JSON string but got `%s`", jsonObj.get("label").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Email.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Email' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Email> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Email.class));
return (TypeAdapter<T>) new TypeAdapter<Email>() {
@Override
public void write(JsonWriter out, Email value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Email read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Email given an JSON string
*
* @param jsonString JSON string
* @return An instance of Email
* @throws IOException if the JSON string is invalid with respect to Email
*/
public static Email fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Email.class);
}
/**
* Convert an instance of Email to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Employment.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.EmploymentDate;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Employment
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Employment {
public static final String SERIALIZED_NAME_CURRENT = "current";
@SerializedName(SERIALIZED_NAME_CURRENT)
private Boolean current;
public static final String SERIALIZED_NAME_COMPANY = "company";
@SerializedName(SERIALIZED_NAME_COMPANY)
private String company;
public static final String SERIALIZED_NAME_TITLE = "title";
@SerializedName(SERIALIZED_NAME_TITLE)
private String title;
public static final String SERIALIZED_NAME_DOMAIN = "domain";
@SerializedName(SERIALIZED_NAME_DOMAIN)
private String domain;
public static final String SERIALIZED_NAME_START = "start";
@SerializedName(SERIALIZED_NAME_START)
private EmploymentDate start;
public static final String SERIALIZED_NAME_END = "end";
@SerializedName(SERIALIZED_NAME_END)
private EmploymentDate end;
public Employment() {
}
public Employment current(Boolean current) {
this.current = current;
return this;
}
/**
* Get current
* @return current
*/
@javax.annotation.Nullable
public Boolean getCurrent() {
return current;
}
public void setCurrent(Boolean current) {
this.current = current;
}
public Employment company(String company) {
this.company = company;
return this;
}
/**
* Get company
* @return company
*/
@javax.annotation.Nullable
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public Employment title(String title) {
this.title = title;
return this;
}
/**
* Get title
* @return title
*/
@javax.annotation.Nullable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Employment domain(String domain) {
this.domain = domain;
return this;
}
/**
* Get domain
* @return domain
*/
@javax.annotation.Nullable
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public Employment start(EmploymentDate start) {
this.start = start;
return this;
}
/**
* Get start
* @return start
*/
@javax.annotation.Nullable
public EmploymentDate getStart() {
return start;
}
public void setStart(EmploymentDate start) {
this.start = start;
}
public Employment end(EmploymentDate end) {
this.end = end;
return this;
}
/**
* Get end
* @return end
*/
@javax.annotation.Nullable
public EmploymentDate getEnd() {
return end;
}
public void setEnd(EmploymentDate end) {
this.end = end;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Employment employment = (Employment) o;
return Objects.equals(this.current, employment.current) &&
Objects.equals(this.company, employment.company) &&
Objects.equals(this.title, employment.title) &&
Objects.equals(this.domain, employment.domain) &&
Objects.equals(this.start, employment.start) &&
Objects.equals(this.end, employment.end);
}
@Override
public int hashCode() {
return Objects.hash(current, company, title, domain, start, end);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Employment {\n");
sb.append(" current: ").append(toIndentedString(current)).append("\n");
sb.append(" company: ").append(toIndentedString(company)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" domain: ").append(toIndentedString(domain)).append("\n");
sb.append(" start: ").append(toIndentedString(start)).append("\n");
sb.append(" end: ").append(toIndentedString(end)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("current");
openapiFields.add("company");
openapiFields.add("title");
openapiFields.add("domain");
openapiFields.add("start");
openapiFields.add("end");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Employment
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Employment.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Employment is not found in the empty JSON string", Employment.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Employment.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Employment` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("company") != null && !jsonObj.get("company").isJsonNull()) && !jsonObj.get("company").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `company` to be a primitive type in the JSON string but got `%s`", jsonObj.get("company").toString()));
}
if ((jsonObj.get("title") != null && !jsonObj.get("title").isJsonNull()) && !jsonObj.get("title").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `title` to be a primitive type in the JSON string but got `%s`", jsonObj.get("title").toString()));
}
if ((jsonObj.get("domain") != null && !jsonObj.get("domain").isJsonNull()) && !jsonObj.get("domain").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `domain` to be a primitive type in the JSON string but got `%s`", jsonObj.get("domain").toString()));
}
// validate the optional field `start`
if (jsonObj.get("start") != null && !jsonObj.get("start").isJsonNull()) {
EmploymentDate.validateJsonElement(jsonObj.get("start"));
}
// validate the optional field `end`
if (jsonObj.get("end") != null && !jsonObj.get("end").isJsonNull()) {
EmploymentDate.validateJsonElement(jsonObj.get("end"));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Employment.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Employment' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Employment> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Employment.class));
return (TypeAdapter<T>) new TypeAdapter<Employment>() {
@Override
public void write(JsonWriter out, Employment value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Employment read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Employment given an JSON string
*
* @param jsonString JSON string
* @return An instance of Employment
* @throws IOException if the JSON string is invalid with respect to Employment
*/
public static Employment fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Employment.class);
}
/**
* Convert an instance of Employment to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/EmploymentDate.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* EmploymentDate
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class EmploymentDate {
public static final String SERIALIZED_NAME_YEAR = "year";
@SerializedName(SERIALIZED_NAME_YEAR)
private Integer year;
public static final String SERIALIZED_NAME_MONTH = "month";
@SerializedName(SERIALIZED_NAME_MONTH)
private Integer month;
public static final String SERIALIZED_NAME_DAY = "day";
@SerializedName(SERIALIZED_NAME_DAY)
private Integer day;
public EmploymentDate() {
}
public EmploymentDate year(Integer year) {
this.year = year;
return this;
}
/**
* Get year
* @return year
*/
@javax.annotation.Nullable
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public EmploymentDate month(Integer month) {
this.month = month;
return this;
}
/**
* Get month
* @return month
*/
@javax.annotation.Nullable
public Integer getMonth() {
return month;
}
public void setMonth(Integer month) {
this.month = month;
}
public EmploymentDate day(Integer day) {
this.day = day;
return this;
}
/**
* Get day
* @return day
*/
@javax.annotation.Nullable
public Integer getDay() {
return day;
}
public void setDay(Integer day) {
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EmploymentDate employmentDate = (EmploymentDate) o;
return Objects.equals(this.year, employmentDate.year) &&
Objects.equals(this.month, employmentDate.month) &&
Objects.equals(this.day, employmentDate.day);
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EmploymentDate {\n");
sb.append(" year: ").append(toIndentedString(year)).append("\n");
sb.append(" month: ").append(toIndentedString(month)).append("\n");
sb.append(" day: ").append(toIndentedString(day)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("year");
openapiFields.add("month");
openapiFields.add("day");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to EmploymentDate
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!EmploymentDate.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in EmploymentDate is not found in the empty JSON string", EmploymentDate.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!EmploymentDate.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `EmploymentDate` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!EmploymentDate.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'EmploymentDate' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<EmploymentDate> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(EmploymentDate.class));
return (TypeAdapter<T>) new TypeAdapter<EmploymentDate>() {
@Override
public void write(JsonWriter out, EmploymentDate value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public EmploymentDate read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of EmploymentDate given an JSON string
*
* @param jsonString JSON string
* @return An instance of EmploymentDate
* @throws IOException if the JSON string is invalid with respect to EmploymentDate
*/
public static EmploymentDate fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, EmploymentDate.class);
}
/**
* Convert an instance of EmploymentDate to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Evidence.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.IPCountry;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Evidence
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Evidence {
public static final String SERIALIZED_NAME_IP_TOR = "ipTor";
@SerializedName(SERIALIZED_NAME_IP_TOR)
private Boolean ipTor;
public static final String SERIALIZED_NAME_IP_COUNTRY = "ipCountry";
@SerializedName(SERIALIZED_NAME_IP_COUNTRY)
private IPCountry ipCountry;
public static final String SERIALIZED_NAME_COUNTRY_OF_IP = "countryOfIp";
@SerializedName(SERIALIZED_NAME_COUNTRY_OF_IP)
private String countryOfIp;
public Evidence() {
}
public Evidence ipTor(Boolean ipTor) {
this.ipTor = ipTor;
return this;
}
/**
* Get ipTor
* @return ipTor
*/
@javax.annotation.Nullable
public Boolean getIpTor() {
return ipTor;
}
public void setIpTor(Boolean ipTor) {
this.ipTor = ipTor;
}
public Evidence ipCountry(IPCountry ipCountry) {
this.ipCountry = ipCountry;
return this;
}
/**
* Get ipCountry
* @return ipCountry
*/
@javax.annotation.Nullable
public IPCountry getIpCountry() {
return ipCountry;
}
public void setIpCountry(IPCountry ipCountry) {
this.ipCountry = ipCountry;
}
public Evidence countryOfIp(String countryOfIp) {
this.countryOfIp = countryOfIp;
return this;
}
/**
* Get countryOfIp
* @return countryOfIp
*/
@javax.annotation.Nullable
public String getCountryOfIp() {
return countryOfIp;
}
public void setCountryOfIp(String countryOfIp) {
this.countryOfIp = countryOfIp;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Evidence evidence = (Evidence) o;
return Objects.equals(this.ipTor, evidence.ipTor) &&
Objects.equals(this.ipCountry, evidence.ipCountry) &&
Objects.equals(this.countryOfIp, evidence.countryOfIp);
}
@Override
public int hashCode() {
return Objects.hash(ipTor, ipCountry, countryOfIp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Evidence {\n");
sb.append(" ipTor: ").append(toIndentedString(ipTor)).append("\n");
sb.append(" ipCountry: ").append(toIndentedString(ipCountry)).append("\n");
sb.append(" countryOfIp: ").append(toIndentedString(countryOfIp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("ipTor");
openapiFields.add("ipCountry");
openapiFields.add("countryOfIp");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Evidence
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Evidence.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Evidence is not found in the empty JSON string", Evidence.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Evidence.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Evidence` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `ipCountry`
if (jsonObj.get("ipCountry") != null && !jsonObj.get("ipCountry").isJsonNull()) {
IPCountry.validateJsonElement(jsonObj.get("ipCountry"));
}
if ((jsonObj.get("countryOfIp") != null && !jsonObj.get("countryOfIp").isJsonNull()) && !jsonObj.get("countryOfIp").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `countryOfIp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("countryOfIp").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Evidence.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Evidence' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Evidence> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Evidence.class));
return (TypeAdapter<T>) new TypeAdapter<Evidence>() {
@Override
public void write(JsonWriter out, Evidence value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Evidence read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Evidence given an JSON string
*
* @param jsonString JSON string
* @return An instance of Evidence
* @throws IOException if the JSON string is invalid with respect to Evidence
*/
public static Evidence fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Evidence.class);
}
/**
* Convert an instance of Evidence to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/IPCountry.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.JsonElement;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* Gets or Sets IPCountry
*/
@JsonAdapter(IPCountry.Adapter.class)
public enum IPCountry {
DOMESTIC("DOMESTIC"),
FOREIGN("FOREIGN"),
UNKNOWN("UNKNOWN");
private String value;
IPCountry(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static IPCountry fromValue(String value) {
for (IPCountry b : IPCountry.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<IPCountry> {
@Override
public void write(final JsonWriter jsonWriter, final IPCountry enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public IPCountry read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return IPCountry.fromValue(value);
}
}
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
String value = jsonElement.getAsString();
IPCountry.fromValue(value);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/IpAddress.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* IpAddress
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class IpAddress {
public static final String SERIALIZED_NAME_FIRST_SEEN_MS = "firstSeenMs";
@SerializedName(SERIALIZED_NAME_FIRST_SEEN_MS)
private Long firstSeenMs;
public static final String SERIALIZED_NAME_LAST_SEEN_MS = "lastSeenMs";
@SerializedName(SERIALIZED_NAME_LAST_SEEN_MS)
private Long lastSeenMs;
public static final String SERIALIZED_NAME_OBSERVATIONS = "observations";
@SerializedName(SERIALIZED_NAME_OBSERVATIONS)
private Integer observations;
public static final String SERIALIZED_NAME_CONFIDENCE = "confidence";
@SerializedName(SERIALIZED_NAME_CONFIDENCE)
private Double confidence;
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private String id;
public IpAddress() {
}
public IpAddress firstSeenMs(Long firstSeenMs) {
this.firstSeenMs = firstSeenMs;
return this;
}
/**
* Get firstSeenMs
* @return firstSeenMs
*/
@javax.annotation.Nullable
public Long getFirstSeenMs() {
return firstSeenMs;
}
public void setFirstSeenMs(Long firstSeenMs) {
this.firstSeenMs = firstSeenMs;
}
public IpAddress lastSeenMs(Long lastSeenMs) {
this.lastSeenMs = lastSeenMs;
return this;
}
/**
* Get lastSeenMs
* @return lastSeenMs
*/
@javax.annotation.Nullable
public Long getLastSeenMs() {
return lastSeenMs;
}
public void setLastSeenMs(Long lastSeenMs) {
this.lastSeenMs = lastSeenMs;
}
public IpAddress observations(Integer observations) {
this.observations = observations;
return this;
}
/**
* Get observations
* @return observations
*/
@javax.annotation.Nullable
public Integer getObservations() {
return observations;
}
public void setObservations(Integer observations) {
this.observations = observations;
}
public IpAddress confidence(Double confidence) {
this.confidence = confidence;
return this;
}
/**
* Get confidence
* @return confidence
*/
@javax.annotation.Nullable
public Double getConfidence() {
return confidence;
}
public void setConfidence(Double confidence) {
this.confidence = confidence;
}
public IpAddress id(String id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
*/
@javax.annotation.Nullable
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IpAddress ipAddress = (IpAddress) o;
return Objects.equals(this.firstSeenMs, ipAddress.firstSeenMs) &&
Objects.equals(this.lastSeenMs, ipAddress.lastSeenMs) &&
Objects.equals(this.observations, ipAddress.observations) &&
Objects.equals(this.confidence, ipAddress.confidence) &&
Objects.equals(this.id, ipAddress.id);
}
@Override
public int hashCode() {
return Objects.hash(firstSeenMs, lastSeenMs, observations, confidence, id);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class IpAddress {\n");
sb.append(" firstSeenMs: ").append(toIndentedString(firstSeenMs)).append("\n");
sb.append(" lastSeenMs: ").append(toIndentedString(lastSeenMs)).append("\n");
sb.append(" observations: ").append(toIndentedString(observations)).append("\n");
sb.append(" confidence: ").append(toIndentedString(confidence)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("firstSeenMs");
openapiFields.add("lastSeenMs");
openapiFields.add("observations");
openapiFields.add("confidence");
openapiFields.add("id");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to IpAddress
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!IpAddress.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in IpAddress is not found in the empty JSON string", IpAddress.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!IpAddress.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `IpAddress` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("id") != null && !jsonObj.get("id").isJsonNull()) && !jsonObj.get("id").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!IpAddress.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'IpAddress' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<IpAddress> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(IpAddress.class));
return (TypeAdapter<T>) new TypeAdapter<IpAddress>() {
@Override
public void write(JsonWriter out, IpAddress value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public IpAddress read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of IpAddress given an JSON string
*
* @param jsonString JSON string
* @return An instance of IpAddress
* @throws IOException if the JSON string is invalid with respect to IpAddress
*/
public static IpAddress fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, IpAddress.class);
}
/**
* Convert an instance of IpAddress to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Location.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Location
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Location {
public static final String SERIALIZED_NAME_ADDRESS_LINE1 = "addressLine1";
@SerializedName(SERIALIZED_NAME_ADDRESS_LINE1)
private String addressLine1;
public static final String SERIALIZED_NAME_ADDRESS_LINE2 = "addressLine2";
@SerializedName(SERIALIZED_NAME_ADDRESS_LINE2)
private String addressLine2;
public static final String SERIALIZED_NAME_CITY = "city";
@SerializedName(SERIALIZED_NAME_CITY)
private String city;
public static final String SERIALIZED_NAME_REGION = "region";
@SerializedName(SERIALIZED_NAME_REGION)
private String region;
public static final String SERIALIZED_NAME_REGION_CODE = "regionCode";
@SerializedName(SERIALIZED_NAME_REGION_CODE)
private String regionCode;
public static final String SERIALIZED_NAME_COUNTRY = "country";
@SerializedName(SERIALIZED_NAME_COUNTRY)
private String country;
public static final String SERIALIZED_NAME_COUNTRY_CODE = "countryCode";
@SerializedName(SERIALIZED_NAME_COUNTRY_CODE)
private String countryCode;
public static final String SERIALIZED_NAME_POSTAL_CODE = "postalCode";
@SerializedName(SERIALIZED_NAME_POSTAL_CODE)
private String postalCode;
public static final String SERIALIZED_NAME_FORMATTED = "formatted";
@SerializedName(SERIALIZED_NAME_FORMATTED)
private String formatted;
public Location() {
}
public Location addressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
return this;
}
/**
* Get addressLine1
* @return addressLine1
*/
@javax.annotation.Nullable
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public Location addressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
return this;
}
/**
* Get addressLine2
* @return addressLine2
*/
@javax.annotation.Nullable
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public Location city(String city) {
this.city = city;
return this;
}
/**
* Get city
* @return city
*/
@javax.annotation.Nullable
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Location region(String region) {
this.region = region;
return this;
}
/**
* Get region
* @return region
*/
@javax.annotation.Nullable
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public Location regionCode(String regionCode) {
this.regionCode = regionCode;
return this;
}
/**
* Get regionCode
* @return regionCode
*/
@javax.annotation.Nullable
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public Location country(String country) {
this.country = country;
return this;
}
/**
* Get country
* @return country
*/
@javax.annotation.Nullable
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Location countryCode(String countryCode) {
this.countryCode = countryCode;
return this;
}
/**
* Get countryCode
* @return countryCode
*/
@javax.annotation.Nullable
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public Location postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Get postalCode
* @return postalCode
*/
@javax.annotation.Nullable
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public Location formatted(String formatted) {
this.formatted = formatted;
return this;
}
/**
* Get formatted
* @return formatted
*/
@javax.annotation.Nullable
public String getFormatted() {
return formatted;
}
public void setFormatted(String formatted) {
this.formatted = formatted;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Location location = (Location) o;
return Objects.equals(this.addressLine1, location.addressLine1) &&
Objects.equals(this.addressLine2, location.addressLine2) &&
Objects.equals(this.city, location.city) &&
Objects.equals(this.region, location.region) &&
Objects.equals(this.regionCode, location.regionCode) &&
Objects.equals(this.country, location.country) &&
Objects.equals(this.countryCode, location.countryCode) &&
Objects.equals(this.postalCode, location.postalCode) &&
Objects.equals(this.formatted, location.formatted);
}
@Override
public int hashCode() {
return Objects.hash(addressLine1, addressLine2, city, region, regionCode, country, countryCode, postalCode, formatted);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Location {\n");
sb.append(" addressLine1: ").append(toIndentedString(addressLine1)).append("\n");
sb.append(" addressLine2: ").append(toIndentedString(addressLine2)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" region: ").append(toIndentedString(region)).append("\n");
sb.append(" regionCode: ").append(toIndentedString(regionCode)).append("\n");
sb.append(" country: ").append(toIndentedString(country)).append("\n");
sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" formatted: ").append(toIndentedString(formatted)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("addressLine1");
openapiFields.add("addressLine2");
openapiFields.add("city");
openapiFields.add("region");
openapiFields.add("regionCode");
openapiFields.add("country");
openapiFields.add("countryCode");
openapiFields.add("postalCode");
openapiFields.add("formatted");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Location
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Location.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Location is not found in the empty JSON string", Location.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Location.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Location` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("addressLine1") != null && !jsonObj.get("addressLine1").isJsonNull()) && !jsonObj.get("addressLine1").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `addressLine1` to be a primitive type in the JSON string but got `%s`", jsonObj.get("addressLine1").toString()));
}
if ((jsonObj.get("addressLine2") != null && !jsonObj.get("addressLine2").isJsonNull()) && !jsonObj.get("addressLine2").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `addressLine2` to be a primitive type in the JSON string but got `%s`", jsonObj.get("addressLine2").toString()));
}
if ((jsonObj.get("city") != null && !jsonObj.get("city").isJsonNull()) && !jsonObj.get("city").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `city` to be a primitive type in the JSON string but got `%s`", jsonObj.get("city").toString()));
}
if ((jsonObj.get("region") != null && !jsonObj.get("region").isJsonNull()) && !jsonObj.get("region").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `region` to be a primitive type in the JSON string but got `%s`", jsonObj.get("region").toString()));
}
if ((jsonObj.get("regionCode") != null && !jsonObj.get("regionCode").isJsonNull()) && !jsonObj.get("regionCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `regionCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("regionCode").toString()));
}
if ((jsonObj.get("country") != null && !jsonObj.get("country").isJsonNull()) && !jsonObj.get("country").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `country` to be a primitive type in the JSON string but got `%s`", jsonObj.get("country").toString()));
}
if ((jsonObj.get("countryCode") != null && !jsonObj.get("countryCode").isJsonNull()) && !jsonObj.get("countryCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `countryCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("countryCode").toString()));
}
if ((jsonObj.get("postalCode") != null && !jsonObj.get("postalCode").isJsonNull()) && !jsonObj.get("postalCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `postalCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("postalCode").toString()));
}
if ((jsonObj.get("formatted") != null && !jsonObj.get("formatted").isJsonNull()) && !jsonObj.get("formatted").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `formatted` to be a primitive type in the JSON string but got `%s`", jsonObj.get("formatted").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Location.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Location' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Location> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Location.class));
return (TypeAdapter<T>) new TypeAdapter<Location>() {
@Override
public void write(JsonWriter out, Location value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Location read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Location given an JSON string
*
* @param jsonString JSON string
* @return An instance of Location
* @throws IOException if the JSON string is invalid with respect to Location
*/
public static Location fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Location.class);
}
/**
* Convert an instance of Location to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/LocationReq.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.LocationType;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* LocationReq
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class LocationReq {
public static final String SERIALIZED_NAME_ADDRESS_LINE1 = "addressLine1";
@SerializedName(SERIALIZED_NAME_ADDRESS_LINE1)
private String addressLine1;
public static final String SERIALIZED_NAME_ADDRESS_LINE2 = "addressLine2";
@SerializedName(SERIALIZED_NAME_ADDRESS_LINE2)
private String addressLine2;
public static final String SERIALIZED_NAME_CITY = "city";
@SerializedName(SERIALIZED_NAME_CITY)
private String city;
public static final String SERIALIZED_NAME_REGION = "region";
@SerializedName(SERIALIZED_NAME_REGION)
private String region;
public static final String SERIALIZED_NAME_REGION_CODE = "regionCode";
@SerializedName(SERIALIZED_NAME_REGION_CODE)
private String regionCode;
public static final String SERIALIZED_NAME_POSTAL_CODE = "postalCode";
@SerializedName(SERIALIZED_NAME_POSTAL_CODE)
private String postalCode;
public static final String SERIALIZED_NAME_COUNTRY = "country";
@SerializedName(SERIALIZED_NAME_COUNTRY)
private String country;
public static final String SERIALIZED_NAME_COUNTRY_CODE = "countryCode";
@SerializedName(SERIALIZED_NAME_COUNTRY_CODE)
private String countryCode;
public static final String SERIALIZED_NAME_LATITUDE = "latitude";
@SerializedName(SERIALIZED_NAME_LATITUDE)
private Double latitude;
public static final String SERIALIZED_NAME_LONGITUDE = "longitude";
@SerializedName(SERIALIZED_NAME_LONGITUDE)
private Double longitude;
public static final String SERIALIZED_NAME_TIME_ZONE = "timeZone";
@SerializedName(SERIALIZED_NAME_TIME_ZONE)
private String timeZone;
public static final String SERIALIZED_NAME_FORMATTED = "formatted";
@SerializedName(SERIALIZED_NAME_FORMATTED)
private String formatted;
public static final String SERIALIZED_NAME_TYPE = "type";
@SerializedName(SERIALIZED_NAME_TYPE)
private LocationType type;
public LocationReq() {
}
public LocationReq addressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
return this;
}
/**
* Get addressLine1
* @return addressLine1
*/
@javax.annotation.Nullable
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public LocationReq addressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
return this;
}
/**
* Get addressLine2
* @return addressLine2
*/
@javax.annotation.Nullable
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public LocationReq city(String city) {
this.city = city;
return this;
}
/**
* Get city
* @return city
*/
@javax.annotation.Nullable
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public LocationReq region(String region) {
this.region = region;
return this;
}
/**
* Get region
* @return region
*/
@javax.annotation.Nullable
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public LocationReq regionCode(String regionCode) {
this.regionCode = regionCode;
return this;
}
/**
* Get regionCode
* @return regionCode
*/
@javax.annotation.Nullable
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public LocationReq postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Get postalCode
* @return postalCode
*/
@javax.annotation.Nullable
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public LocationReq country(String country) {
this.country = country;
return this;
}
/**
* Get country
* @return country
*/
@javax.annotation.Nullable
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public LocationReq countryCode(String countryCode) {
this.countryCode = countryCode;
return this;
}
/**
* Get countryCode
* @return countryCode
*/
@javax.annotation.Nullable
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public LocationReq latitude(Double latitude) {
this.latitude = latitude;
return this;
}
/**
* Get latitude
* @return latitude
*/
@javax.annotation.Nullable
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public LocationReq longitude(Double longitude) {
this.longitude = longitude;
return this;
}
/**
* Get longitude
* @return longitude
*/
@javax.annotation.Nullable
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public LocationReq timeZone(String timeZone) {
this.timeZone = timeZone;
return this;
}
/**
* Get timeZone
* @return timeZone
*/
@javax.annotation.Nullable
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public LocationReq formatted(String formatted) {
this.formatted = formatted;
return this;
}
/**
* Get formatted
* @return formatted
*/
@javax.annotation.Nullable
public String getFormatted() {
return formatted;
}
public void setFormatted(String formatted) {
this.formatted = formatted;
}
public LocationReq type(LocationType type) {
this.type = type;
return this;
}
/**
* Get type
* @return type
*/
@javax.annotation.Nullable
public LocationType getType() {
return type;
}
public void setType(LocationType type) {
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LocationReq locationReq = (LocationReq) o;
return Objects.equals(this.addressLine1, locationReq.addressLine1) &&
Objects.equals(this.addressLine2, locationReq.addressLine2) &&
Objects.equals(this.city, locationReq.city) &&
Objects.equals(this.region, locationReq.region) &&
Objects.equals(this.regionCode, locationReq.regionCode) &&
Objects.equals(this.postalCode, locationReq.postalCode) &&
Objects.equals(this.country, locationReq.country) &&
Objects.equals(this.countryCode, locationReq.countryCode) &&
Objects.equals(this.latitude, locationReq.latitude) &&
Objects.equals(this.longitude, locationReq.longitude) &&
Objects.equals(this.timeZone, locationReq.timeZone) &&
Objects.equals(this.formatted, locationReq.formatted) &&
Objects.equals(this.type, locationReq.type);
}
@Override
public int hashCode() {
return Objects.hash(addressLine1, addressLine2, city, region, regionCode, postalCode, country, countryCode, latitude, longitude, timeZone, formatted, type);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LocationReq {\n");
sb.append(" addressLine1: ").append(toIndentedString(addressLine1)).append("\n");
sb.append(" addressLine2: ").append(toIndentedString(addressLine2)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" region: ").append(toIndentedString(region)).append("\n");
sb.append(" regionCode: ").append(toIndentedString(regionCode)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" country: ").append(toIndentedString(country)).append("\n");
sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n");
sb.append(" latitude: ").append(toIndentedString(latitude)).append("\n");
sb.append(" longitude: ").append(toIndentedString(longitude)).append("\n");
sb.append(" timeZone: ").append(toIndentedString(timeZone)).append("\n");
sb.append(" formatted: ").append(toIndentedString(formatted)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("addressLine1");
openapiFields.add("addressLine2");
openapiFields.add("city");
openapiFields.add("region");
openapiFields.add("regionCode");
openapiFields.add("postalCode");
openapiFields.add("country");
openapiFields.add("countryCode");
openapiFields.add("latitude");
openapiFields.add("longitude");
openapiFields.add("timeZone");
openapiFields.add("formatted");
openapiFields.add("type");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to LocationReq
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!LocationReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in LocationReq is not found in the empty JSON string", LocationReq.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!LocationReq.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `LocationReq` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("addressLine1") != null && !jsonObj.get("addressLine1").isJsonNull()) && !jsonObj.get("addressLine1").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `addressLine1` to be a primitive type in the JSON string but got `%s`", jsonObj.get("addressLine1").toString()));
}
if ((jsonObj.get("addressLine2") != null && !jsonObj.get("addressLine2").isJsonNull()) && !jsonObj.get("addressLine2").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `addressLine2` to be a primitive type in the JSON string but got `%s`", jsonObj.get("addressLine2").toString()));
}
if ((jsonObj.get("city") != null && !jsonObj.get("city").isJsonNull()) && !jsonObj.get("city").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `city` to be a primitive type in the JSON string but got `%s`", jsonObj.get("city").toString()));
}
if ((jsonObj.get("region") != null && !jsonObj.get("region").isJsonNull()) && !jsonObj.get("region").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `region` to be a primitive type in the JSON string but got `%s`", jsonObj.get("region").toString()));
}
if ((jsonObj.get("regionCode") != null && !jsonObj.get("regionCode").isJsonNull()) && !jsonObj.get("regionCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `regionCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("regionCode").toString()));
}
if ((jsonObj.get("postalCode") != null && !jsonObj.get("postalCode").isJsonNull()) && !jsonObj.get("postalCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `postalCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("postalCode").toString()));
}
if ((jsonObj.get("country") != null && !jsonObj.get("country").isJsonNull()) && !jsonObj.get("country").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `country` to be a primitive type in the JSON string but got `%s`", jsonObj.get("country").toString()));
}
if ((jsonObj.get("countryCode") != null && !jsonObj.get("countryCode").isJsonNull()) && !jsonObj.get("countryCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `countryCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("countryCode").toString()));
}
if ((jsonObj.get("timeZone") != null && !jsonObj.get("timeZone").isJsonNull()) && !jsonObj.get("timeZone").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `timeZone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("timeZone").toString()));
}
if ((jsonObj.get("formatted") != null && !jsonObj.get("formatted").isJsonNull()) && !jsonObj.get("formatted").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `formatted` to be a primitive type in the JSON string but got `%s`", jsonObj.get("formatted").toString()));
}
// validate the optional field `type`
if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) {
LocationType.validateJsonElement(jsonObj.get("type"));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!LocationReq.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'LocationReq' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<LocationReq> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(LocationReq.class));
return (TypeAdapter<T>) new TypeAdapter<LocationReq>() {
@Override
public void write(JsonWriter out, LocationReq value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public LocationReq read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of LocationReq given an JSON string
*
* @param jsonString JSON string
* @return An instance of LocationReq
* @throws IOException if the JSON string is invalid with respect to LocationReq
*/
public static LocationReq fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, LocationReq.class);
}
/**
* Convert an instance of LocationReq to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/LocationType.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.JsonElement;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* Gets or Sets LocationType
*/
@JsonAdapter(LocationType.Adapter.class)
public enum LocationType {
WORK("Work"),
PRIMARY("Primary"),
SECONDARY("Secondary");
private String value;
LocationType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static LocationType fromValue(String value) {
for (LocationType b : LocationType.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<LocationType> {
@Override
public void write(final JsonWriter jsonWriter, final LocationType enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public LocationType read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return LocationType.fromValue(value);
}
}
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
String value = jsonElement.getAsString();
LocationType.fromValue(value);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/MultiFieldReq.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.LocationReq;
import ai.fideo.model.PersonNameReq;
import ai.fideo.model.SocialProfileReq;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* MultiFieldReq
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class MultiFieldReq {
public static final String SERIALIZED_NAME_TWITTER = "twitter";
@SerializedName(SERIALIZED_NAME_TWITTER)
private String twitter;
public static final String SERIALIZED_NAME_LINKEDIN = "linkedin";
@SerializedName(SERIALIZED_NAME_LINKEDIN)
private String linkedin;
public static final String SERIALIZED_NAME_RECORD_ID = "recordId";
@SerializedName(SERIALIZED_NAME_RECORD_ID)
private String recordId;
public static final String SERIALIZED_NAME_PERSON_ID = "personId";
@SerializedName(SERIALIZED_NAME_PERSON_ID)
private String personId;
public static final String SERIALIZED_NAME_PARTNER_ID = "partnerId";
@SerializedName(SERIALIZED_NAME_PARTNER_ID)
private String partnerId;
public static final String SERIALIZED_NAME_LOCATION = "location";
@SerializedName(SERIALIZED_NAME_LOCATION)
private LocationReq location;
public static final String SERIALIZED_NAME_AVATAR = "avatar";
@SerializedName(SERIALIZED_NAME_AVATAR)
private String avatar;
public static final String SERIALIZED_NAME_WEBSITE = "website";
@SerializedName(SERIALIZED_NAME_WEBSITE)
private String website;
public static final String SERIALIZED_NAME_TITLE = "title";
@SerializedName(SERIALIZED_NAME_TITLE)
private String title;
public static final String SERIALIZED_NAME_ORGANIZATION = "organization";
@SerializedName(SERIALIZED_NAME_ORGANIZATION)
private String organization;
public static final String SERIALIZED_NAME_EMAILS = "emails";
@SerializedName(SERIALIZED_NAME_EMAILS)
private List<String> emails = new ArrayList<>();
public static final String SERIALIZED_NAME_PHONES = "phones";
@SerializedName(SERIALIZED_NAME_PHONES)
private List<String> phones = new ArrayList<>();
public static final String SERIALIZED_NAME_PROFILES = "profiles";
@SerializedName(SERIALIZED_NAME_PROFILES)
private List<SocialProfileReq> profiles = new ArrayList<>();
public static final String SERIALIZED_NAME_MAIDS = "maids";
@SerializedName(SERIALIZED_NAME_MAIDS)
private List<String> maids = new ArrayList<>();
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private PersonNameReq name;
public static final String SERIALIZED_NAME_PARTNER_KEYS = "partnerKeys";
@SerializedName(SERIALIZED_NAME_PARTNER_KEYS)
private Map<String, String> partnerKeys = new HashMap<>();
public static final String SERIALIZED_NAME_LI_NONID = "li_nonid";
@SerializedName(SERIALIZED_NAME_LI_NONID)
private String liNonid;
public static final String SERIALIZED_NAME_PANORAMA_ID = "panoramaId";
@SerializedName(SERIALIZED_NAME_PANORAMA_ID)
private String panoramaId;
public static final String SERIALIZED_NAME_PLACEKEY = "placekey";
@SerializedName(SERIALIZED_NAME_PLACEKEY)
private String placekey;
public static final String SERIALIZED_NAME_GENERATE_PID = "generatePid";
@SerializedName(SERIALIZED_NAME_GENERATE_PID)
private Boolean generatePid;
public static final String SERIALIZED_NAME_EMAIL = "email";
@SerializedName(SERIALIZED_NAME_EMAIL)
private String email;
public static final String SERIALIZED_NAME_PHONE = "phone";
@SerializedName(SERIALIZED_NAME_PHONE)
private String phone;
public static final String SERIALIZED_NAME_PROFILE = "profile";
@SerializedName(SERIALIZED_NAME_PROFILE)
private SocialProfileReq profile;
public static final String SERIALIZED_NAME_MAID = "maid";
@SerializedName(SERIALIZED_NAME_MAID)
private String maid;
public MultiFieldReq() {
}
public MultiFieldReq twitter(String twitter) {
this.twitter = twitter;
return this;
}
/**
* Get twitter
* @return twitter
*/
@javax.annotation.Nullable
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public MultiFieldReq linkedin(String linkedin) {
this.linkedin = linkedin;
return this;
}
/**
* Get linkedin
* @return linkedin
*/
@javax.annotation.Nullable
public String getLinkedin() {
return linkedin;
}
public void setLinkedin(String linkedin) {
this.linkedin = linkedin;
}
public MultiFieldReq recordId(String recordId) {
this.recordId = recordId;
return this;
}
/**
* Get recordId
* @return recordId
*/
@javax.annotation.Nullable
public String getRecordId() {
return recordId;
}
public void setRecordId(String recordId) {
this.recordId = recordId;
}
public MultiFieldReq personId(String personId) {
this.personId = personId;
return this;
}
/**
* Get personId
* @return personId
*/
@javax.annotation.Nullable
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public MultiFieldReq partnerId(String partnerId) {
this.partnerId = partnerId;
return this;
}
/**
* Get partnerId
* @return partnerId
*/
@javax.annotation.Nullable
public String getPartnerId() {
return partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
public MultiFieldReq location(LocationReq location) {
this.location = location;
return this;
}
/**
* Get location
* @return location
*/
@javax.annotation.Nullable
public LocationReq getLocation() {
return location;
}
public void setLocation(LocationReq location) {
this.location = location;
}
public MultiFieldReq avatar(String avatar) {
this.avatar = avatar;
return this;
}
/**
* Get avatar
* @return avatar
*/
@javax.annotation.Nullable
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public MultiFieldReq website(String website) {
this.website = website;
return this;
}
/**
* Get website
* @return website
*/
@javax.annotation.Nullable
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public MultiFieldReq title(String title) {
this.title = title;
return this;
}
/**
* Get title
* @return title
*/
@javax.annotation.Nullable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public MultiFieldReq organization(String organization) {
this.organization = organization;
return this;
}
/**
* Get organization
* @return organization
*/
@javax.annotation.Nullable
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public MultiFieldReq emails(List<String> emails) {
this.emails = emails;
return this;
}
public MultiFieldReq addEmailsItem(String emailsItem) {
if (this.emails == null) {
this.emails = new ArrayList<>();
}
this.emails.add(emailsItem);
return this;
}
/**
* Get emails
* @return emails
*/
@javax.annotation.Nullable
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
public MultiFieldReq phones(List<String> phones) {
this.phones = phones;
return this;
}
public MultiFieldReq addPhonesItem(String phonesItem) {
if (this.phones == null) {
this.phones = new ArrayList<>();
}
this.phones.add(phonesItem);
return this;
}
/**
* Get phones
* @return phones
*/
@javax.annotation.Nullable
public List<String> getPhones() {
return phones;
}
public void setPhones(List<String> phones) {
this.phones = phones;
}
public MultiFieldReq profiles(List<SocialProfileReq> profiles) {
this.profiles = profiles;
return this;
}
public MultiFieldReq addProfilesItem(SocialProfileReq profilesItem) {
if (this.profiles == null) {
this.profiles = new ArrayList<>();
}
this.profiles.add(profilesItem);
return this;
}
/**
* Get profiles
* @return profiles
*/
@javax.annotation.Nullable
public List<SocialProfileReq> getProfiles() {
return profiles;
}
public void setProfiles(List<SocialProfileReq> profiles) {
this.profiles = profiles;
}
public MultiFieldReq maids(List<String> maids) {
this.maids = maids;
return this;
}
public MultiFieldReq addMaidsItem(String maidsItem) {
if (this.maids == null) {
this.maids = new ArrayList<>();
}
this.maids.add(maidsItem);
return this;
}
/**
* Get maids
* @return maids
*/
@javax.annotation.Nullable
public List<String> getMaids() {
return maids;
}
public void setMaids(List<String> maids) {
this.maids = maids;
}
public MultiFieldReq name(PersonNameReq name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
*/
@javax.annotation.Nullable
public PersonNameReq getName() {
return name;
}
public void setName(PersonNameReq name) {
this.name = name;
}
public MultiFieldReq partnerKeys(Map<String, String> partnerKeys) {
this.partnerKeys = partnerKeys;
return this;
}
public MultiFieldReq putPartnerKeysItem(String key, String partnerKeysItem) {
if (this.partnerKeys == null) {
this.partnerKeys = new HashMap<>();
}
this.partnerKeys.put(key, partnerKeysItem);
return this;
}
/**
* Get partnerKeys
* @return partnerKeys
*/
@javax.annotation.Nullable
public Map<String, String> getPartnerKeys() {
return partnerKeys;
}
public void setPartnerKeys(Map<String, String> partnerKeys) {
this.partnerKeys = partnerKeys;
}
public MultiFieldReq liNonid(String liNonid) {
this.liNonid = liNonid;
return this;
}
/**
* Get liNonid
* @return liNonid
*/
@javax.annotation.Nullable
public String getLiNonid() {
return liNonid;
}
public void setLiNonid(String liNonid) {
this.liNonid = liNonid;
}
public MultiFieldReq panoramaId(String panoramaId) {
this.panoramaId = panoramaId;
return this;
}
/**
* Get panoramaId
* @return panoramaId
*/
@javax.annotation.Nullable
public String getPanoramaId() {
return panoramaId;
}
public void setPanoramaId(String panoramaId) {
this.panoramaId = panoramaId;
}
public MultiFieldReq placekey(String placekey) {
this.placekey = placekey;
return this;
}
/**
* Get placekey
* @return placekey
*/
@javax.annotation.Nullable
public String getPlacekey() {
return placekey;
}
public void setPlacekey(String placekey) {
this.placekey = placekey;
}
public MultiFieldReq generatePid(Boolean generatePid) {
this.generatePid = generatePid;
return this;
}
/**
* Get generatePid
* @return generatePid
*/
@javax.annotation.Nullable
public Boolean getGeneratePid() {
return generatePid;
}
public void setGeneratePid(Boolean generatePid) {
this.generatePid = generatePid;
}
public MultiFieldReq email(String email) {
this.email = email;
return this;
}
/**
* Get email
* @return email
*/
@javax.annotation.Nullable
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public MultiFieldReq phone(String phone) {
this.phone = phone;
return this;
}
/**
* Get phone
* @return phone
*/
@javax.annotation.Nullable
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public MultiFieldReq profile(SocialProfileReq profile) {
this.profile = profile;
return this;
}
/**
* Get profile
* @return profile
*/
@javax.annotation.Nullable
public SocialProfileReq getProfile() {
return profile;
}
public void setProfile(SocialProfileReq profile) {
this.profile = profile;
}
public MultiFieldReq maid(String maid) {
this.maid = maid;
return this;
}
/**
* Get maid
* @return maid
*/
@javax.annotation.Nullable
public String getMaid() {
return maid;
}
public void setMaid(String maid) {
this.maid = maid;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MultiFieldReq multiFieldReq = (MultiFieldReq) o;
return Objects.equals(this.twitter, multiFieldReq.twitter) &&
Objects.equals(this.linkedin, multiFieldReq.linkedin) &&
Objects.equals(this.recordId, multiFieldReq.recordId) &&
Objects.equals(this.personId, multiFieldReq.personId) &&
Objects.equals(this.partnerId, multiFieldReq.partnerId) &&
Objects.equals(this.location, multiFieldReq.location) &&
Objects.equals(this.avatar, multiFieldReq.avatar) &&
Objects.equals(this.website, multiFieldReq.website) &&
Objects.equals(this.title, multiFieldReq.title) &&
Objects.equals(this.organization, multiFieldReq.organization) &&
Objects.equals(this.emails, multiFieldReq.emails) &&
Objects.equals(this.phones, multiFieldReq.phones) &&
Objects.equals(this.profiles, multiFieldReq.profiles) &&
Objects.equals(this.maids, multiFieldReq.maids) &&
Objects.equals(this.name, multiFieldReq.name) &&
Objects.equals(this.partnerKeys, multiFieldReq.partnerKeys) &&
Objects.equals(this.liNonid, multiFieldReq.liNonid) &&
Objects.equals(this.panoramaId, multiFieldReq.panoramaId) &&
Objects.equals(this.placekey, multiFieldReq.placekey) &&
Objects.equals(this.generatePid, multiFieldReq.generatePid) &&
Objects.equals(this.email, multiFieldReq.email) &&
Objects.equals(this.phone, multiFieldReq.phone) &&
Objects.equals(this.profile, multiFieldReq.profile) &&
Objects.equals(this.maid, multiFieldReq.maid);
}
@Override
public int hashCode() {
return Objects.hash(twitter, linkedin, recordId, personId, partnerId, location, avatar, website, title, organization, emails, phones, profiles, maids, name, partnerKeys, liNonid, panoramaId, placekey, generatePid, email, phone, profile, maid);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class MultiFieldReq {\n");
sb.append(" twitter: ").append(toIndentedString(twitter)).append("\n");
sb.append(" linkedin: ").append(toIndentedString(linkedin)).append("\n");
sb.append(" recordId: ").append(toIndentedString(recordId)).append("\n");
sb.append(" personId: ").append(toIndentedString(personId)).append("\n");
sb.append(" partnerId: ").append(toIndentedString(partnerId)).append("\n");
sb.append(" location: ").append(toIndentedString(location)).append("\n");
sb.append(" avatar: ").append(toIndentedString(avatar)).append("\n");
sb.append(" website: ").append(toIndentedString(website)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" organization: ").append(toIndentedString(organization)).append("\n");
sb.append(" emails: ").append(toIndentedString(emails)).append("\n");
sb.append(" phones: ").append(toIndentedString(phones)).append("\n");
sb.append(" profiles: ").append(toIndentedString(profiles)).append("\n");
sb.append(" maids: ").append(toIndentedString(maids)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" partnerKeys: ").append(toIndentedString(partnerKeys)).append("\n");
sb.append(" liNonid: ").append(toIndentedString(liNonid)).append("\n");
sb.append(" panoramaId: ").append(toIndentedString(panoramaId)).append("\n");
sb.append(" placekey: ").append(toIndentedString(placekey)).append("\n");
sb.append(" generatePid: ").append(toIndentedString(generatePid)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" profile: ").append(toIndentedString(profile)).append("\n");
sb.append(" maid: ").append(toIndentedString(maid)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("twitter");
openapiFields.add("linkedin");
openapiFields.add("recordId");
openapiFields.add("personId");
openapiFields.add("partnerId");
openapiFields.add("location");
openapiFields.add("avatar");
openapiFields.add("website");
openapiFields.add("title");
openapiFields.add("organization");
openapiFields.add("emails");
openapiFields.add("phones");
openapiFields.add("profiles");
openapiFields.add("maids");
openapiFields.add("name");
openapiFields.add("partnerKeys");
openapiFields.add("li_nonid");
openapiFields.add("panoramaId");
openapiFields.add("placekey");
openapiFields.add("generatePid");
openapiFields.add("email");
openapiFields.add("phone");
openapiFields.add("profile");
openapiFields.add("maid");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to MultiFieldReq
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!MultiFieldReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in MultiFieldReq is not found in the empty JSON string", MultiFieldReq.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("twitter") != null && !jsonObj.get("twitter").isJsonNull()) && !jsonObj.get("twitter").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `twitter` to be a primitive type in the JSON string but got `%s`", jsonObj.get("twitter").toString()));
}
if ((jsonObj.get("linkedin") != null && !jsonObj.get("linkedin").isJsonNull()) && !jsonObj.get("linkedin").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `linkedin` to be a primitive type in the JSON string but got `%s`", jsonObj.get("linkedin").toString()));
}
if ((jsonObj.get("recordId") != null && !jsonObj.get("recordId").isJsonNull()) && !jsonObj.get("recordId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `recordId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("recordId").toString()));
}
if ((jsonObj.get("personId") != null && !jsonObj.get("personId").isJsonNull()) && !jsonObj.get("personId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `personId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("personId").toString()));
}
if ((jsonObj.get("partnerId") != null && !jsonObj.get("partnerId").isJsonNull()) && !jsonObj.get("partnerId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `partnerId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("partnerId").toString()));
}
// validate the optional field `location`
if (jsonObj.get("location") != null && !jsonObj.get("location").isJsonNull()) {
LocationReq.validateJsonElement(jsonObj.get("location"));
}
if ((jsonObj.get("avatar") != null && !jsonObj.get("avatar").isJsonNull()) && !jsonObj.get("avatar").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `avatar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("avatar").toString()));
}
if ((jsonObj.get("website") != null && !jsonObj.get("website").isJsonNull()) && !jsonObj.get("website").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `website` to be a primitive type in the JSON string but got `%s`", jsonObj.get("website").toString()));
}
if ((jsonObj.get("title") != null && !jsonObj.get("title").isJsonNull()) && !jsonObj.get("title").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `title` to be a primitive type in the JSON string but got `%s`", jsonObj.get("title").toString()));
}
if ((jsonObj.get("organization") != null && !jsonObj.get("organization").isJsonNull()) && !jsonObj.get("organization").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `organization` to be a primitive type in the JSON string but got `%s`", jsonObj.get("organization").toString()));
}
// ensure the optional json data is an array if present
if (jsonObj.get("emails") != null && !jsonObj.get("emails").isJsonNull() && !jsonObj.get("emails").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `emails` to be an array in the JSON string but got `%s`", jsonObj.get("emails").toString()));
}
// ensure the optional json data is an array if present
if (jsonObj.get("phones") != null && !jsonObj.get("phones").isJsonNull() && !jsonObj.get("phones").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `phones` to be an array in the JSON string but got `%s`", jsonObj.get("phones").toString()));
}
if (jsonObj.get("profiles") != null && !jsonObj.get("profiles").isJsonNull()) {
JsonArray jsonArrayprofiles = jsonObj.getAsJsonArray("profiles");
if (jsonArrayprofiles != null) {
// ensure the json data is an array
if (!jsonObj.get("profiles").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `profiles` to be an array in the JSON string but got `%s`", jsonObj.get("profiles").toString()));
}
// validate the optional field `profiles` (array)
for (int i = 0; i < jsonArrayprofiles.size(); i++) {
SocialProfileReq.validateJsonElement(jsonArrayprofiles.get(i));
};
}
}
// ensure the optional json data is an array if present
if (jsonObj.get("maids") != null && !jsonObj.get("maids").isJsonNull() && !jsonObj.get("maids").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `maids` to be an array in the JSON string but got `%s`", jsonObj.get("maids").toString()));
}
// validate the optional field `name`
if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) {
PersonNameReq.validateJsonElement(jsonObj.get("name"));
}
if ((jsonObj.get("li_nonid") != null && !jsonObj.get("li_nonid").isJsonNull()) && !jsonObj.get("li_nonid").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `li_nonid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("li_nonid").toString()));
}
if ((jsonObj.get("panoramaId") != null && !jsonObj.get("panoramaId").isJsonNull()) && !jsonObj.get("panoramaId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `panoramaId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("panoramaId").toString()));
}
if ((jsonObj.get("placekey") != null && !jsonObj.get("placekey").isJsonNull()) && !jsonObj.get("placekey").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `placekey` to be a primitive type in the JSON string but got `%s`", jsonObj.get("placekey").toString()));
}
if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString()));
}
if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString()));
}
// validate the optional field `profile`
if (jsonObj.get("profile") != null && !jsonObj.get("profile").isJsonNull()) {
SocialProfileReq.validateJsonElement(jsonObj.get("profile"));
}
if ((jsonObj.get("maid") != null && !jsonObj.get("maid").isJsonNull()) && !jsonObj.get("maid").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `maid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("maid").toString()));
}
}
/**
* Create an instance of MultiFieldReq given an JSON string
*
* @param jsonString JSON string
* @return An instance of MultiFieldReq
* @throws IOException if the JSON string is invalid with respect to MultiFieldReq
*/
public static MultiFieldReq fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, MultiFieldReq.class);
}
/**
* Convert an instance of MultiFieldReq to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/MultiFieldReqWithOptions.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.LocationReq;
import ai.fideo.model.MultiFieldReq;
import ai.fideo.model.PersonNameReq;
import ai.fideo.model.SocialProfileReq;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openapitools.jackson.nullable.JsonNullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* MultiFieldReqWithOptions
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class MultiFieldReqWithOptions extends MultiFieldReq {
public static final String SERIALIZED_NAME_INFER = "infer";
@SerializedName(SERIALIZED_NAME_INFER)
private Boolean infer;
public static final String SERIALIZED_NAME_CONFIDENCE = "confidence";
@SerializedName(SERIALIZED_NAME_CONFIDENCE)
private String confidence = "LOW";
public static final String SERIALIZED_NAME_BIRTHDAY = "birthday";
@SerializedName(SERIALIZED_NAME_BIRTHDAY)
private String birthday;
public static final String SERIALIZED_NAME_IP_ADDRESS = "ipAddress";
@SerializedName(SERIALIZED_NAME_IP_ADDRESS)
private String ipAddress;
public static final String SERIALIZED_NAME_COUNTRIES = "countries";
@SerializedName(SERIALIZED_NAME_COUNTRIES)
private List<String> countries;
public static final String SERIALIZED_NAME_EXCLUDED_COUNTRIES = "excludedCountries";
@SerializedName(SERIALIZED_NAME_EXCLUDED_COUNTRIES)
private List<String> excludedCountries;
public MultiFieldReqWithOptions() {
}
public MultiFieldReqWithOptions infer(Boolean infer) {
this.infer = infer;
return this;
}
/**
* Get infer
* @return infer
*/
@javax.annotation.Nullable
public Boolean getInfer() {
return infer;
}
public void setInfer(Boolean infer) {
this.infer = infer;
}
public MultiFieldReqWithOptions confidence(String confidence) {
this.confidence = confidence;
return this;
}
/**
* Get confidence
* @return confidence
*/
@javax.annotation.Nullable
public String getConfidence() {
return confidence;
}
public void setConfidence(String confidence) {
this.confidence = confidence;
}
public MultiFieldReqWithOptions birthday(String birthday) {
this.birthday = birthday;
return this;
}
/**
* Get birthday
* @return birthday
*/
@javax.annotation.Nullable
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public MultiFieldReqWithOptions ipAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
/**
* Get ipAddress
* @return ipAddress
*/
@javax.annotation.Nullable
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public MultiFieldReqWithOptions countries(List<String> countries) {
this.countries = countries;
return this;
}
public MultiFieldReqWithOptions addCountriesItem(String countriesItem) {
if (this.countries == null) {
this.countries = new ArrayList<>();
}
this.countries.add(countriesItem);
return this;
}
/**
* Get countries
* @return countries
*/
@javax.annotation.Nullable
public List<String> getCountries() {
return countries;
}
public void setCountries(List<String> countries) {
this.countries = countries;
}
public MultiFieldReqWithOptions excludedCountries(List<String> excludedCountries) {
this.excludedCountries = excludedCountries;
return this;
}
public MultiFieldReqWithOptions addExcludedCountriesItem(String excludedCountriesItem) {
if (this.excludedCountries == null) {
this.excludedCountries = new ArrayList<>();
}
this.excludedCountries.add(excludedCountriesItem);
return this;
}
/**
* Get excludedCountries
* @return excludedCountries
*/
@javax.annotation.Nullable
public List<String> getExcludedCountries() {
return excludedCountries;
}
public void setExcludedCountries(List<String> excludedCountries) {
this.excludedCountries = excludedCountries;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MultiFieldReqWithOptions multiFieldReqWithOptions = (MultiFieldReqWithOptions) o;
return Objects.equals(this.infer, multiFieldReqWithOptions.infer) &&
Objects.equals(this.confidence, multiFieldReqWithOptions.confidence) &&
Objects.equals(this.birthday, multiFieldReqWithOptions.birthday) &&
Objects.equals(this.ipAddress, multiFieldReqWithOptions.ipAddress) &&
Objects.equals(this.countries, multiFieldReqWithOptions.countries) &&
Objects.equals(this.excludedCountries, multiFieldReqWithOptions.excludedCountries) &&
super.equals(o);
}
private static <T> boolean equalsNullable(JsonNullable<T> a, JsonNullable<T> b) {
return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get()));
}
@Override
public int hashCode() {
return Objects.hash(infer, confidence, birthday, ipAddress, countries, excludedCountries, super.hashCode());
}
private static <T> int hashCodeNullable(JsonNullable<T> a) {
if (a == null) {
return 1;
}
return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class MultiFieldReqWithOptions {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" infer: ").append(toIndentedString(infer)).append("\n");
sb.append(" confidence: ").append(toIndentedString(confidence)).append("\n");
sb.append(" birthday: ").append(toIndentedString(birthday)).append("\n");
sb.append(" ipAddress: ").append(toIndentedString(ipAddress)).append("\n");
sb.append(" countries: ").append(toIndentedString(countries)).append("\n");
sb.append(" excludedCountries: ").append(toIndentedString(excludedCountries)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("twitter");
openapiFields.add("linkedin");
openapiFields.add("recordId");
openapiFields.add("personId");
openapiFields.add("partnerId");
openapiFields.add("location");
openapiFields.add("avatar");
openapiFields.add("website");
openapiFields.add("title");
openapiFields.add("organization");
openapiFields.add("emails");
openapiFields.add("phones");
openapiFields.add("profiles");
openapiFields.add("maids");
openapiFields.add("name");
openapiFields.add("partnerKeys");
openapiFields.add("li_nonid");
openapiFields.add("panoramaId");
openapiFields.add("placekey");
openapiFields.add("generatePid");
openapiFields.add("email");
openapiFields.add("phone");
openapiFields.add("profile");
openapiFields.add("maid");
openapiFields.add("infer");
openapiFields.add("confidence");
openapiFields.add("birthday");
openapiFields.add("ipAddress");
openapiFields.add("countries");
openapiFields.add("excludedCountries");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to MultiFieldReqWithOptions
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!MultiFieldReqWithOptions.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in MultiFieldReqWithOptions is not found in the empty JSON string", MultiFieldReqWithOptions.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!MultiFieldReqWithOptions.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MultiFieldReqWithOptions` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("confidence") != null && !jsonObj.get("confidence").isJsonNull()) && !jsonObj.get("confidence").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `confidence` to be a primitive type in the JSON string but got `%s`", jsonObj.get("confidence").toString()));
}
if ((jsonObj.get("birthday") != null && !jsonObj.get("birthday").isJsonNull()) && !jsonObj.get("birthday").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `birthday` to be a primitive type in the JSON string but got `%s`", jsonObj.get("birthday").toString()));
}
if ((jsonObj.get("ipAddress") != null && !jsonObj.get("ipAddress").isJsonNull()) && !jsonObj.get("ipAddress").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `ipAddress` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ipAddress").toString()));
}
// ensure the optional json data is an array if present
if (jsonObj.get("countries") != null && !jsonObj.get("countries").isJsonNull() && !jsonObj.get("countries").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `countries` to be an array in the JSON string but got `%s`", jsonObj.get("countries").toString()));
}
// ensure the optional json data is an array if present
if (jsonObj.get("excludedCountries") != null && !jsonObj.get("excludedCountries").isJsonNull() && !jsonObj.get("excludedCountries").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `excludedCountries` to be an array in the JSON string but got `%s`", jsonObj.get("excludedCountries").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!MultiFieldReqWithOptions.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'MultiFieldReqWithOptions' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<MultiFieldReqWithOptions> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(MultiFieldReqWithOptions.class));
return (TypeAdapter<T>) new TypeAdapter<MultiFieldReqWithOptions>() {
@Override
public void write(JsonWriter out, MultiFieldReqWithOptions value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public MultiFieldReqWithOptions read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of MultiFieldReqWithOptions given an JSON string
*
* @param jsonString JSON string
* @return An instance of MultiFieldReqWithOptions
* @throws IOException if the JSON string is invalid with respect to MultiFieldReqWithOptions
*/
public static MultiFieldReqWithOptions fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, MultiFieldReqWithOptions.class);
}
/**
* Convert an instance of MultiFieldReqWithOptions to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Name.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Name
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Name {
public static final String SERIALIZED_NAME_GIVEN_NAME = "givenName";
@SerializedName(SERIALIZED_NAME_GIVEN_NAME)
private String givenName;
public static final String SERIALIZED_NAME_FAMILY_NAME = "familyName";
@SerializedName(SERIALIZED_NAME_FAMILY_NAME)
private String familyName;
public Name() {
}
public Name givenName(String givenName) {
this.givenName = givenName;
return this;
}
/**
* Get givenName
* @return givenName
*/
@javax.annotation.Nullable
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public Name familyName(String familyName) {
this.familyName = familyName;
return this;
}
/**
* Get familyName
* @return familyName
*/
@javax.annotation.Nullable
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Name name = (Name) o;
return Objects.equals(this.givenName, name.givenName) &&
Objects.equals(this.familyName, name.familyName);
}
@Override
public int hashCode() {
return Objects.hash(givenName, familyName);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Name {\n");
sb.append(" givenName: ").append(toIndentedString(givenName)).append("\n");
sb.append(" familyName: ").append(toIndentedString(familyName)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("givenName");
openapiFields.add("familyName");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Name
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Name.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Name is not found in the empty JSON string", Name.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Name.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Name` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("givenName") != null && !jsonObj.get("givenName").isJsonNull()) && !jsonObj.get("givenName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `givenName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("givenName").toString()));
}
if ((jsonObj.get("familyName") != null && !jsonObj.get("familyName").isJsonNull()) && !jsonObj.get("familyName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `familyName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("familyName").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Name.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Name' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Name> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Name.class));
return (TypeAdapter<T>) new TypeAdapter<Name>() {
@Override
public void write(JsonWriter out, Name value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Name read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Name given an JSON string
*
* @param jsonString JSON string
* @return An instance of Name
* @throws IOException if the JSON string is invalid with respect to Name
*/
public static Name fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Name.class);
}
/**
* Convert an instance of Name to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/NameWithAlias.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.Alias;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* NameWithAlias
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class NameWithAlias {
public static final String SERIALIZED_NAME_FIRST = "first";
@SerializedName(SERIALIZED_NAME_FIRST)
private String first;
public static final String SERIALIZED_NAME_LAST = "last";
@SerializedName(SERIALIZED_NAME_LAST)
private String last;
public static final String SERIALIZED_NAME_MIDDLE = "middle";
@SerializedName(SERIALIZED_NAME_MIDDLE)
private String middle;
public static final String SERIALIZED_NAME_GIVEN_NAME = "givenName";
@SerializedName(SERIALIZED_NAME_GIVEN_NAME)
private String givenName;
public static final String SERIALIZED_NAME_FAMILY_NAME = "familyName";
@SerializedName(SERIALIZED_NAME_FAMILY_NAME)
private String familyName;
public static final String SERIALIZED_NAME_ALIASES = "aliases";
@SerializedName(SERIALIZED_NAME_ALIASES)
private List<Alias> aliases = new ArrayList<>();
public NameWithAlias() {
}
public NameWithAlias first(String first) {
this.first = first;
return this;
}
/**
* Get first
* @return first
*/
@javax.annotation.Nullable
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public NameWithAlias last(String last) {
this.last = last;
return this;
}
/**
* Get last
* @return last
*/
@javax.annotation.Nullable
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public NameWithAlias middle(String middle) {
this.middle = middle;
return this;
}
/**
* Get middle
* @return middle
*/
@javax.annotation.Nullable
public String getMiddle() {
return middle;
}
public void setMiddle(String middle) {
this.middle = middle;
}
public NameWithAlias givenName(String givenName) {
this.givenName = givenName;
return this;
}
/**
* Get givenName
* @return givenName
*/
@javax.annotation.Nullable
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public NameWithAlias familyName(String familyName) {
this.familyName = familyName;
return this;
}
/**
* Get familyName
* @return familyName
*/
@javax.annotation.Nullable
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public NameWithAlias aliases(List<Alias> aliases) {
this.aliases = aliases;
return this;
}
public NameWithAlias addAliasesItem(Alias aliasesItem) {
if (this.aliases == null) {
this.aliases = new ArrayList<>();
}
this.aliases.add(aliasesItem);
return this;
}
/**
* Get aliases
* @return aliases
*/
@javax.annotation.Nullable
public List<Alias> getAliases() {
return aliases;
}
public void setAliases(List<Alias> aliases) {
this.aliases = aliases;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NameWithAlias nameWithAlias = (NameWithAlias) o;
return Objects.equals(this.first, nameWithAlias.first) &&
Objects.equals(this.last, nameWithAlias.last) &&
Objects.equals(this.middle, nameWithAlias.middle) &&
Objects.equals(this.givenName, nameWithAlias.givenName) &&
Objects.equals(this.familyName, nameWithAlias.familyName) &&
Objects.equals(this.aliases, nameWithAlias.aliases);
}
@Override
public int hashCode() {
return Objects.hash(first, last, middle, givenName, familyName, aliases);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class NameWithAlias {\n");
sb.append(" first: ").append(toIndentedString(first)).append("\n");
sb.append(" last: ").append(toIndentedString(last)).append("\n");
sb.append(" middle: ").append(toIndentedString(middle)).append("\n");
sb.append(" givenName: ").append(toIndentedString(givenName)).append("\n");
sb.append(" familyName: ").append(toIndentedString(familyName)).append("\n");
sb.append(" aliases: ").append(toIndentedString(aliases)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("first");
openapiFields.add("last");
openapiFields.add("middle");
openapiFields.add("givenName");
openapiFields.add("familyName");
openapiFields.add("aliases");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to NameWithAlias
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!NameWithAlias.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in NameWithAlias is not found in the empty JSON string", NameWithAlias.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!NameWithAlias.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `NameWithAlias` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("first") != null && !jsonObj.get("first").isJsonNull()) && !jsonObj.get("first").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `first` to be a primitive type in the JSON string but got `%s`", jsonObj.get("first").toString()));
}
if ((jsonObj.get("last") != null && !jsonObj.get("last").isJsonNull()) && !jsonObj.get("last").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `last` to be a primitive type in the JSON string but got `%s`", jsonObj.get("last").toString()));
}
if ((jsonObj.get("middle") != null && !jsonObj.get("middle").isJsonNull()) && !jsonObj.get("middle").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `middle` to be a primitive type in the JSON string but got `%s`", jsonObj.get("middle").toString()));
}
if ((jsonObj.get("givenName") != null && !jsonObj.get("givenName").isJsonNull()) && !jsonObj.get("givenName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `givenName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("givenName").toString()));
}
if ((jsonObj.get("familyName") != null && !jsonObj.get("familyName").isJsonNull()) && !jsonObj.get("familyName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `familyName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("familyName").toString()));
}
if (jsonObj.get("aliases") != null && !jsonObj.get("aliases").isJsonNull()) {
JsonArray jsonArrayaliases = jsonObj.getAsJsonArray("aliases");
if (jsonArrayaliases != null) {
// ensure the json data is an array
if (!jsonObj.get("aliases").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `aliases` to be an array in the JSON string but got `%s`", jsonObj.get("aliases").toString()));
}
// validate the optional field `aliases` (array)
for (int i = 0; i < jsonArrayaliases.size(); i++) {
Alias.validateJsonElement(jsonArrayaliases.get(i));
};
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!NameWithAlias.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'NameWithAlias' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<NameWithAlias> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(NameWithAlias.class));
return (TypeAdapter<T>) new TypeAdapter<NameWithAlias>() {
@Override
public void write(JsonWriter out, NameWithAlias value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public NameWithAlias read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of NameWithAlias given an JSON string
*
* @param jsonString JSON string
* @return An instance of NameWithAlias
* @throws IOException if the JSON string is invalid with respect to NameWithAlias
*/
public static NameWithAlias fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, NameWithAlias.class);
}
/**
* Convert an instance of NameWithAlias to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/PersonNameReq.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* PersonNameReq
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class PersonNameReq {
public static final String SERIALIZED_NAME_GIVEN = "given";
@SerializedName(SERIALIZED_NAME_GIVEN)
private String given;
public static final String SERIALIZED_NAME_FAMILY = "family";
@SerializedName(SERIALIZED_NAME_FAMILY)
private String family;
public static final String SERIALIZED_NAME_MIDDLE = "middle";
@SerializedName(SERIALIZED_NAME_MIDDLE)
private String middle;
public static final String SERIALIZED_NAME_PREFIX = "prefix";
@SerializedName(SERIALIZED_NAME_PREFIX)
private String prefix;
public static final String SERIALIZED_NAME_SUFFIX = "suffix";
@SerializedName(SERIALIZED_NAME_SUFFIX)
private String suffix;
public static final String SERIALIZED_NAME_NICKNAME = "nickname";
@SerializedName(SERIALIZED_NAME_NICKNAME)
private String nickname;
public static final String SERIALIZED_NAME_FULL = "full";
@SerializedName(SERIALIZED_NAME_FULL)
private String full;
public PersonNameReq() {
}
public PersonNameReq given(String given) {
this.given = given;
return this;
}
/**
* Get given
* @return given
*/
@javax.annotation.Nullable
public String getGiven() {
return given;
}
public void setGiven(String given) {
this.given = given;
}
public PersonNameReq family(String family) {
this.family = family;
return this;
}
/**
* Get family
* @return family
*/
@javax.annotation.Nullable
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
public PersonNameReq middle(String middle) {
this.middle = middle;
return this;
}
/**
* Get middle
* @return middle
*/
@javax.annotation.Nullable
public String getMiddle() {
return middle;
}
public void setMiddle(String middle) {
this.middle = middle;
}
public PersonNameReq prefix(String prefix) {
this.prefix = prefix;
return this;
}
/**
* Get prefix
* @return prefix
*/
@javax.annotation.Nullable
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public PersonNameReq suffix(String suffix) {
this.suffix = suffix;
return this;
}
/**
* Get suffix
* @return suffix
*/
@javax.annotation.Nullable
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public PersonNameReq nickname(String nickname) {
this.nickname = nickname;
return this;
}
/**
* Get nickname
* @return nickname
*/
@javax.annotation.Nullable
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public PersonNameReq full(String full) {
this.full = full;
return this;
}
/**
* Get full
* @return full
*/
@javax.annotation.Nullable
public String getFull() {
return full;
}
public void setFull(String full) {
this.full = full;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PersonNameReq personNameReq = (PersonNameReq) o;
return Objects.equals(this.given, personNameReq.given) &&
Objects.equals(this.family, personNameReq.family) &&
Objects.equals(this.middle, personNameReq.middle) &&
Objects.equals(this.prefix, personNameReq.prefix) &&
Objects.equals(this.suffix, personNameReq.suffix) &&
Objects.equals(this.nickname, personNameReq.nickname) &&
Objects.equals(this.full, personNameReq.full);
}
@Override
public int hashCode() {
return Objects.hash(given, family, middle, prefix, suffix, nickname, full);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PersonNameReq {\n");
sb.append(" given: ").append(toIndentedString(given)).append("\n");
sb.append(" family: ").append(toIndentedString(family)).append("\n");
sb.append(" middle: ").append(toIndentedString(middle)).append("\n");
sb.append(" prefix: ").append(toIndentedString(prefix)).append("\n");
sb.append(" suffix: ").append(toIndentedString(suffix)).append("\n");
sb.append(" nickname: ").append(toIndentedString(nickname)).append("\n");
sb.append(" full: ").append(toIndentedString(full)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("given");
openapiFields.add("family");
openapiFields.add("middle");
openapiFields.add("prefix");
openapiFields.add("suffix");
openapiFields.add("nickname");
openapiFields.add("full");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to PersonNameReq
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!PersonNameReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in PersonNameReq is not found in the empty JSON string", PersonNameReq.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!PersonNameReq.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `PersonNameReq` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("given") != null && !jsonObj.get("given").isJsonNull()) && !jsonObj.get("given").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `given` to be a primitive type in the JSON string but got `%s`", jsonObj.get("given").toString()));
}
if ((jsonObj.get("family") != null && !jsonObj.get("family").isJsonNull()) && !jsonObj.get("family").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `family` to be a primitive type in the JSON string but got `%s`", jsonObj.get("family").toString()));
}
if ((jsonObj.get("middle") != null && !jsonObj.get("middle").isJsonNull()) && !jsonObj.get("middle").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `middle` to be a primitive type in the JSON string but got `%s`", jsonObj.get("middle").toString()));
}
if ((jsonObj.get("prefix") != null && !jsonObj.get("prefix").isJsonNull()) && !jsonObj.get("prefix").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `prefix` to be a primitive type in the JSON string but got `%s`", jsonObj.get("prefix").toString()));
}
if ((jsonObj.get("suffix") != null && !jsonObj.get("suffix").isJsonNull()) && !jsonObj.get("suffix").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `suffix` to be a primitive type in the JSON string but got `%s`", jsonObj.get("suffix").toString()));
}
if ((jsonObj.get("nickname") != null && !jsonObj.get("nickname").isJsonNull()) && !jsonObj.get("nickname").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `nickname` to be a primitive type in the JSON string but got `%s`", jsonObj.get("nickname").toString()));
}
if ((jsonObj.get("full") != null && !jsonObj.get("full").isJsonNull()) && !jsonObj.get("full").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `full` to be a primitive type in the JSON string but got `%s`", jsonObj.get("full").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!PersonNameReq.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'PersonNameReq' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<PersonNameReq> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(PersonNameReq.class));
return (TypeAdapter<T>) new TypeAdapter<PersonNameReq>() {
@Override
public void write(JsonWriter out, PersonNameReq value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public PersonNameReq read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of PersonNameReq given an JSON string
*
* @param jsonString JSON string
* @return An instance of PersonNameReq
* @throws IOException if the JSON string is invalid with respect to PersonNameReq
*/
public static PersonNameReq fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, PersonNameReq.class);
}
/**
* Convert an instance of PersonNameReq to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Phone.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Phone
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Phone {
public static final String SERIALIZED_NAME_FIRST_SEEN_MS = "firstSeenMs";
@SerializedName(SERIALIZED_NAME_FIRST_SEEN_MS)
private Long firstSeenMs;
public static final String SERIALIZED_NAME_LAST_SEEN_MS = "lastSeenMs";
@SerializedName(SERIALIZED_NAME_LAST_SEEN_MS)
private Long lastSeenMs;
public static final String SERIALIZED_NAME_OBSERVATIONS = "observations";
@SerializedName(SERIALIZED_NAME_OBSERVATIONS)
private Integer observations;
public static final String SERIALIZED_NAME_CONFIDENCE = "confidence";
@SerializedName(SERIALIZED_NAME_CONFIDENCE)
private Double confidence;
public static final String SERIALIZED_NAME_LABEL = "label";
@SerializedName(SERIALIZED_NAME_LABEL)
private String label;
public static final String SERIALIZED_NAME_VALUE = "value";
@SerializedName(SERIALIZED_NAME_VALUE)
private String value;
public Phone() {
}
public Phone firstSeenMs(Long firstSeenMs) {
this.firstSeenMs = firstSeenMs;
return this;
}
/**
* Get firstSeenMs
* @return firstSeenMs
*/
@javax.annotation.Nullable
public Long getFirstSeenMs() {
return firstSeenMs;
}
public void setFirstSeenMs(Long firstSeenMs) {
this.firstSeenMs = firstSeenMs;
}
public Phone lastSeenMs(Long lastSeenMs) {
this.lastSeenMs = lastSeenMs;
return this;
}
/**
* Get lastSeenMs
* @return lastSeenMs
*/
@javax.annotation.Nullable
public Long getLastSeenMs() {
return lastSeenMs;
}
public void setLastSeenMs(Long lastSeenMs) {
this.lastSeenMs = lastSeenMs;
}
public Phone observations(Integer observations) {
this.observations = observations;
return this;
}
/**
* Get observations
* @return observations
*/
@javax.annotation.Nullable
public Integer getObservations() {
return observations;
}
public void setObservations(Integer observations) {
this.observations = observations;
}
public Phone confidence(Double confidence) {
this.confidence = confidence;
return this;
}
/**
* Get confidence
* @return confidence
*/
@javax.annotation.Nullable
public Double getConfidence() {
return confidence;
}
public void setConfidence(Double confidence) {
this.confidence = confidence;
}
public Phone label(String label) {
this.label = label;
return this;
}
/**
* Get label
* @return label
*/
@javax.annotation.Nullable
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Phone value(String value) {
this.value = value;
return this;
}
/**
* Get value
* @return value
*/
@javax.annotation.Nullable
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Phone phone = (Phone) o;
return Objects.equals(this.firstSeenMs, phone.firstSeenMs) &&
Objects.equals(this.lastSeenMs, phone.lastSeenMs) &&
Objects.equals(this.observations, phone.observations) &&
Objects.equals(this.confidence, phone.confidence) &&
Objects.equals(this.label, phone.label) &&
Objects.equals(this.value, phone.value);
}
@Override
public int hashCode() {
return Objects.hash(firstSeenMs, lastSeenMs, observations, confidence, label, value);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Phone {\n");
sb.append(" firstSeenMs: ").append(toIndentedString(firstSeenMs)).append("\n");
sb.append(" lastSeenMs: ").append(toIndentedString(lastSeenMs)).append("\n");
sb.append(" observations: ").append(toIndentedString(observations)).append("\n");
sb.append(" confidence: ").append(toIndentedString(confidence)).append("\n");
sb.append(" label: ").append(toIndentedString(label)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("firstSeenMs");
openapiFields.add("lastSeenMs");
openapiFields.add("observations");
openapiFields.add("confidence");
openapiFields.add("label");
openapiFields.add("value");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Phone
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Phone.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Phone is not found in the empty JSON string", Phone.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Phone.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Phone` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("label") != null && !jsonObj.get("label").isJsonNull()) && !jsonObj.get("label").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `label` to be a primitive type in the JSON string but got `%s`", jsonObj.get("label").toString()));
}
if ((jsonObj.get("value") != null && !jsonObj.get("value").isJsonNull()) && !jsonObj.get("value").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `value` to be a primitive type in the JSON string but got `%s`", jsonObj.get("value").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Phone.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Phone' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Phone> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Phone.class));
return (TypeAdapter<T>) new TypeAdapter<Phone>() {
@Override
public void write(JsonWriter out, Phone value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Phone read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Phone given an JSON string
*
* @param jsonString JSON string
* @return An instance of Phone
* @throws IOException if the JSON string is invalid with respect to Phone
*/
public static Phone fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Phone.class);
}
/**
* Convert an instance of Phone to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/Photo.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* Photo
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class Photo {
public static final String SERIALIZED_NAME_URL = "url";
@SerializedName(SERIALIZED_NAME_URL)
private String url;
public static final String SERIALIZED_NAME_LABEL = "label";
@SerializedName(SERIALIZED_NAME_LABEL)
private String label;
public Photo() {
}
public Photo url(String url) {
this.url = url;
return this;
}
/**
* Get url
* @return url
*/
@javax.annotation.Nullable
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Photo label(String label) {
this.label = label;
return this;
}
/**
* Get label
* @return label
*/
@javax.annotation.Nullable
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Photo photo = (Photo) o;
return Objects.equals(this.url, photo.url) &&
Objects.equals(this.label, photo.label);
}
@Override
public int hashCode() {
return Objects.hash(url, label);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Photo {\n");
sb.append(" url: ").append(toIndentedString(url)).append("\n");
sb.append(" label: ").append(toIndentedString(label)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("url");
openapiFields.add("label");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Photo
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Photo.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Photo is not found in the empty JSON string", Photo.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!Photo.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Photo` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("url") != null && !jsonObj.get("url").isJsonNull()) && !jsonObj.get("url").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `url` to be a primitive type in the JSON string but got `%s`", jsonObj.get("url").toString()));
}
if ((jsonObj.get("label") != null && !jsonObj.get("label").isJsonNull()) && !jsonObj.get("label").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `label` to be a primitive type in the JSON string but got `%s`", jsonObj.get("label").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Photo.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Photo' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Photo> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Photo.class));
return (TypeAdapter<T>) new TypeAdapter<Photo>() {
@Override
public void write(JsonWriter out, Photo value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Photo read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of Photo given an JSON string
*
* @param jsonString JSON string
* @return An instance of Photo
* @throws IOException if the JSON string is invalid with respect to Photo
*/
public static Photo fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Photo.class);
}
/**
* Convert an instance of Photo to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/ScoreDetails.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* ScoreDetails
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class ScoreDetails {
public static final String SERIALIZED_NAME_SCORER = "scorer";
@SerializedName(SERIALIZED_NAME_SCORER)
private String scorer;
public static final String SERIALIZED_NAME_SCORE = "score";
@SerializedName(SERIALIZED_NAME_SCORE)
private Double score;
public static final String SERIALIZED_NAME_EVIDENCE = "evidence";
@SerializedName(SERIALIZED_NAME_EVIDENCE)
private Map<String, Object> evidence = new HashMap<>();
public static final String SERIALIZED_NAME_WEIGHT = "weight";
@SerializedName(SERIALIZED_NAME_WEIGHT)
private Double weight;
public ScoreDetails() {
}
public ScoreDetails scorer(String scorer) {
this.scorer = scorer;
return this;
}
/**
* Get scorer
* @return scorer
*/
@javax.annotation.Nullable
public String getScorer() {
return scorer;
}
public void setScorer(String scorer) {
this.scorer = scorer;
}
public ScoreDetails score(Double score) {
this.score = score;
return this;
}
/**
* Get score
* @return score
*/
@javax.annotation.Nullable
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public ScoreDetails evidence(Map<String, Object> evidence) {
this.evidence = evidence;
return this;
}
public ScoreDetails putEvidenceItem(String key, Object evidenceItem) {
if (this.evidence == null) {
this.evidence = new HashMap<>();
}
this.evidence.put(key, evidenceItem);
return this;
}
/**
* Get evidence
* @return evidence
*/
@javax.annotation.Nullable
public Map<String, Object> getEvidence() {
return evidence;
}
public void setEvidence(Map<String, Object> evidence) {
this.evidence = evidence;
}
public ScoreDetails weight(Double weight) {
this.weight = weight;
return this;
}
/**
* Get weight
* @return weight
*/
@javax.annotation.Nullable
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ScoreDetails scoreDetails = (ScoreDetails) o;
return Objects.equals(this.scorer, scoreDetails.scorer) &&
Objects.equals(this.score, scoreDetails.score) &&
Objects.equals(this.evidence, scoreDetails.evidence) &&
Objects.equals(this.weight, scoreDetails.weight);
}
@Override
public int hashCode() {
return Objects.hash(scorer, score, evidence, weight);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ScoreDetails {\n");
sb.append(" scorer: ").append(toIndentedString(scorer)).append("\n");
sb.append(" score: ").append(toIndentedString(score)).append("\n");
sb.append(" evidence: ").append(toIndentedString(evidence)).append("\n");
sb.append(" weight: ").append(toIndentedString(weight)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("scorer");
openapiFields.add("score");
openapiFields.add("evidence");
openapiFields.add("weight");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ScoreDetails
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ScoreDetails.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ScoreDetails is not found in the empty JSON string", ScoreDetails.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!ScoreDetails.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ScoreDetails` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("scorer") != null && !jsonObj.get("scorer").isJsonNull()) && !jsonObj.get("scorer").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `scorer` to be a primitive type in the JSON string but got `%s`", jsonObj.get("scorer").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ScoreDetails.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ScoreDetails' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ScoreDetails> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ScoreDetails.class));
return (TypeAdapter<T>) new TypeAdapter<ScoreDetails>() {
@Override
public void write(JsonWriter out, ScoreDetails value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ScoreDetails read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of ScoreDetails given an JSON string
*
* @param jsonString JSON string
* @return An instance of ScoreDetails
* @throws IOException if the JSON string is invalid with respect to ScoreDetails
*/
public static ScoreDetails fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ScoreDetails.class);
}
/**
* Convert an instance of ScoreDetails to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/SignalsPost200Response.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.Demographics;
import ai.fideo.model.Economic;
import ai.fideo.model.Education;
import ai.fideo.model.Email;
import ai.fideo.model.Employment;
import ai.fideo.model.IpAddress;
import ai.fideo.model.Location;
import ai.fideo.model.NameWithAlias;
import ai.fideo.model.Phone;
import ai.fideo.model.Photo;
import ai.fideo.model.SignalsResponseV0;
import ai.fideo.model.SignalsResponseV20240424;
import ai.fideo.model.SocialProfileDetails;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.JsonPrimitive;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonParseException;
import ai.fideo.client.JSON;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class SignalsPost200Response extends AbstractOpenApiSchema {
private static final Logger log = Logger.getLogger(SignalsPost200Response.class.getName());
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!SignalsPost200Response.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'SignalsPost200Response' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<SignalsResponseV0> adapterSignalsResponseV0 = gson.getDelegateAdapter(this, TypeToken.get(SignalsResponseV0.class));
final TypeAdapter<SignalsResponseV20240424> adapterSignalsResponseV20240424 = gson.getDelegateAdapter(this, TypeToken.get(SignalsResponseV20240424.class));
return (TypeAdapter<T>) new TypeAdapter<SignalsPost200Response>() {
@Override
public void write(JsonWriter out, SignalsPost200Response value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `SignalsResponseV0`
if (value.getActualInstance() instanceof SignalsResponseV0) {
JsonElement element = adapterSignalsResponseV0.toJsonTree((SignalsResponseV0)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `SignalsResponseV20240424`
if (value.getActualInstance() instanceof SignalsResponseV20240424) {
JsonElement element = adapterSignalsResponseV20240424.toJsonTree((SignalsResponseV20240424)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: SignalsResponseV0, SignalsResponseV20240424");
}
@Override
public SignalsPost200Response read(JsonReader in) throws IOException {
Object deserialized = null;
JsonElement jsonElement = elementAdapter.read(in);
int match = 0;
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize SignalsResponseV0
try {
// validate the JSON object to see if any exception is thrown
SignalsResponseV0.validateJsonElement(jsonElement);
actualAdapter = adapterSignalsResponseV0;
match++;
log.log(Level.FINER, "Input data matches schema 'SignalsResponseV0'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for SignalsResponseV0 failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'SignalsResponseV0'", e);
}
// deserialize SignalsResponseV20240424
try {
// validate the JSON object to see if any exception is thrown
SignalsResponseV20240424.validateJsonElement(jsonElement);
actualAdapter = adapterSignalsResponseV20240424;
match++;
log.log(Level.FINER, "Input data matches schema 'SignalsResponseV20240424'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for SignalsResponseV20240424 failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'SignalsResponseV20240424'", e);
}
if (match == 1) {
SignalsPost200Response ret = new SignalsPost200Response();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for SignalsPost200Response: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
}
// store a list of schema names defined in oneOf
public static final Map<String, Class<?>> schemas = new HashMap<String, Class<?>>();
public SignalsPost200Response() {
super("oneOf", Boolean.FALSE);
}
public SignalsPost200Response(Object o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
static {
schemas.put("SignalsResponseV0", SignalsResponseV0.class);
schemas.put("SignalsResponseV20240424", SignalsResponseV20240424.class);
}
@Override
public Map<String, Class<?>> getSchemas() {
return SignalsPost200Response.schemas;
}
/**
* Set the instance that matches the oneOf child schema, check
* the instance parameter is valid against the oneOf child schemas:
* SignalsResponseV0, SignalsResponseV20240424
*
* It could be an instance of the 'oneOf' schemas.
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof SignalsResponseV0) {
super.setActualInstance(instance);
return;
}
if (instance instanceof SignalsResponseV20240424) {
super.setActualInstance(instance);
return;
}
throw new RuntimeException("Invalid instance type. Must be SignalsResponseV0, SignalsResponseV20240424");
}
/**
* Get the actual instance, which can be the following:
* SignalsResponseV0, SignalsResponseV20240424
*
* @return The actual instance (SignalsResponseV0, SignalsResponseV20240424)
*/
@SuppressWarnings("unchecked")
@Override
public Object getActualInstance() {
return super.getActualInstance();
}
/**
* Get the actual instance of `SignalsResponseV0`. If the actual instance is not `SignalsResponseV0`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `SignalsResponseV0`
* @throws ClassCastException if the instance is not `SignalsResponseV0`
*/
public SignalsResponseV0 getSignalsResponseV0() throws ClassCastException {
return (SignalsResponseV0)super.getActualInstance();
}
/**
* Get the actual instance of `SignalsResponseV20240424`. If the actual instance is not `SignalsResponseV20240424`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `SignalsResponseV20240424`
* @throws ClassCastException if the instance is not `SignalsResponseV20240424`
*/
public SignalsResponseV20240424 getSignalsResponseV20240424() throws ClassCastException {
return (SignalsResponseV20240424)super.getActualInstance();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SignalsPost200Response
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with SignalsResponseV0
try {
SignalsResponseV0.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for SignalsResponseV0 failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with SignalsResponseV20240424
try {
SignalsResponseV20240424.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for SignalsResponseV20240424 failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for SignalsPost200Response with oneOf schemas: SignalsResponseV0, SignalsResponseV20240424. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}
/**
* Create an instance of SignalsPost200Response given an JSON string
*
* @param jsonString JSON string
* @return An instance of SignalsPost200Response
* @throws IOException if the JSON string is invalid with respect to SignalsPost200Response
*/
public static SignalsPost200Response fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, SignalsPost200Response.class);
}
/**
* Convert an instance of SignalsPost200Response to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/SignalsResponseV0.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.Demographics;
import ai.fideo.model.Email;
import ai.fideo.model.Employment;
import ai.fideo.model.IpAddress;
import ai.fideo.model.Location;
import ai.fideo.model.Name;
import ai.fideo.model.Phone;
import ai.fideo.model.SocialProfileUrls;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* SignalsResponseV0
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class SignalsResponseV0 {
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private Name name;
public static final String SERIALIZED_NAME_DEMOGRAPHICS = "demographics";
@SerializedName(SERIALIZED_NAME_DEMOGRAPHICS)
private Demographics demographics;
public static final String SERIALIZED_NAME_LOCATIONS = "locations";
@SerializedName(SERIALIZED_NAME_LOCATIONS)
private List<Location> locations = new ArrayList<>();
public static final String SERIALIZED_NAME_EMAILS = "emails";
@SerializedName(SERIALIZED_NAME_EMAILS)
private List<Email> emails = new ArrayList<>();
public static final String SERIALIZED_NAME_PHONES = "phones";
@SerializedName(SERIALIZED_NAME_PHONES)
private List<Phone> phones = new ArrayList<>();
public static final String SERIALIZED_NAME_PERSON_IDS = "personIds";
@SerializedName(SERIALIZED_NAME_PERSON_IDS)
private List<String> personIds = new ArrayList<>();
public static final String SERIALIZED_NAME_IP_ADDRESSES = "ipAddresses";
@SerializedName(SERIALIZED_NAME_IP_ADDRESSES)
private List<IpAddress> ipAddresses = new ArrayList<>();
public static final String SERIALIZED_NAME_MESSAGE = "message";
@SerializedName(SERIALIZED_NAME_MESSAGE)
private String message;
public static final String SERIALIZED_NAME_SOCIAL_PROFILES = "socialProfiles";
@SerializedName(SERIALIZED_NAME_SOCIAL_PROFILES)
private SocialProfileUrls socialProfiles;
public static final String SERIALIZED_NAME_EMPLOYMENT = "employment";
@SerializedName(SERIALIZED_NAME_EMPLOYMENT)
private Employment employment;
public SignalsResponseV0() {
}
public SignalsResponseV0 name(Name name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
*/
@javax.annotation.Nullable
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public SignalsResponseV0 demographics(Demographics demographics) {
this.demographics = demographics;
return this;
}
/**
* Get demographics
* @return demographics
*/
@javax.annotation.Nullable
public Demographics getDemographics() {
return demographics;
}
public void setDemographics(Demographics demographics) {
this.demographics = demographics;
}
public SignalsResponseV0 locations(List<Location> locations) {
this.locations = locations;
return this;
}
public SignalsResponseV0 addLocationsItem(Location locationsItem) {
if (this.locations == null) {
this.locations = new ArrayList<>();
}
this.locations.add(locationsItem);
return this;
}
/**
* Get locations
* @return locations
*/
@javax.annotation.Nullable
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public SignalsResponseV0 emails(List<Email> emails) {
this.emails = emails;
return this;
}
public SignalsResponseV0 addEmailsItem(Email emailsItem) {
if (this.emails == null) {
this.emails = new ArrayList<>();
}
this.emails.add(emailsItem);
return this;
}
/**
* Get emails
* @return emails
*/
@javax.annotation.Nullable
public List<Email> getEmails() {
return emails;
}
public void setEmails(List<Email> emails) {
this.emails = emails;
}
public SignalsResponseV0 phones(List<Phone> phones) {
this.phones = phones;
return this;
}
public SignalsResponseV0 addPhonesItem(Phone phonesItem) {
if (this.phones == null) {
this.phones = new ArrayList<>();
}
this.phones.add(phonesItem);
return this;
}
/**
* Get phones
* @return phones
*/
@javax.annotation.Nullable
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
public SignalsResponseV0 personIds(List<String> personIds) {
this.personIds = personIds;
return this;
}
public SignalsResponseV0 addPersonIdsItem(String personIdsItem) {
if (this.personIds == null) {
this.personIds = new ArrayList<>();
}
this.personIds.add(personIdsItem);
return this;
}
/**
* Get personIds
* @return personIds
*/
@javax.annotation.Nullable
public List<String> getPersonIds() {
return personIds;
}
public void setPersonIds(List<String> personIds) {
this.personIds = personIds;
}
public SignalsResponseV0 ipAddresses(List<IpAddress> ipAddresses) {
this.ipAddresses = ipAddresses;
return this;
}
public SignalsResponseV0 addIpAddressesItem(IpAddress ipAddressesItem) {
if (this.ipAddresses == null) {
this.ipAddresses = new ArrayList<>();
}
this.ipAddresses.add(ipAddressesItem);
return this;
}
/**
* Get ipAddresses
* @return ipAddresses
*/
@javax.annotation.Nullable
public List<IpAddress> getIpAddresses() {
return ipAddresses;
}
public void setIpAddresses(List<IpAddress> ipAddresses) {
this.ipAddresses = ipAddresses;
}
public SignalsResponseV0 message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
*/
@javax.annotation.Nullable
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SignalsResponseV0 socialProfiles(SocialProfileUrls socialProfiles) {
this.socialProfiles = socialProfiles;
return this;
}
/**
* Get socialProfiles
* @return socialProfiles
*/
@javax.annotation.Nullable
public SocialProfileUrls getSocialProfiles() {
return socialProfiles;
}
public void setSocialProfiles(SocialProfileUrls socialProfiles) {
this.socialProfiles = socialProfiles;
}
public SignalsResponseV0 employment(Employment employment) {
this.employment = employment;
return this;
}
/**
* Get employment
* @return employment
*/
@javax.annotation.Nullable
public Employment getEmployment() {
return employment;
}
public void setEmployment(Employment employment) {
this.employment = employment;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SignalsResponseV0 signalsResponseV0 = (SignalsResponseV0) o;
return Objects.equals(this.name, signalsResponseV0.name) &&
Objects.equals(this.demographics, signalsResponseV0.demographics) &&
Objects.equals(this.locations, signalsResponseV0.locations) &&
Objects.equals(this.emails, signalsResponseV0.emails) &&
Objects.equals(this.phones, signalsResponseV0.phones) &&
Objects.equals(this.personIds, signalsResponseV0.personIds) &&
Objects.equals(this.ipAddresses, signalsResponseV0.ipAddresses) &&
Objects.equals(this.message, signalsResponseV0.message) &&
Objects.equals(this.socialProfiles, signalsResponseV0.socialProfiles) &&
Objects.equals(this.employment, signalsResponseV0.employment);
}
@Override
public int hashCode() {
return Objects.hash(name, demographics, locations, emails, phones, personIds, ipAddresses, message, socialProfiles, employment);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SignalsResponseV0 {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" demographics: ").append(toIndentedString(demographics)).append("\n");
sb.append(" locations: ").append(toIndentedString(locations)).append("\n");
sb.append(" emails: ").append(toIndentedString(emails)).append("\n");
sb.append(" phones: ").append(toIndentedString(phones)).append("\n");
sb.append(" personIds: ").append(toIndentedString(personIds)).append("\n");
sb.append(" ipAddresses: ").append(toIndentedString(ipAddresses)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append(" socialProfiles: ").append(toIndentedString(socialProfiles)).append("\n");
sb.append(" employment: ").append(toIndentedString(employment)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
openapiFields.add("demographics");
openapiFields.add("locations");
openapiFields.add("emails");
openapiFields.add("phones");
openapiFields.add("personIds");
openapiFields.add("ipAddresses");
openapiFields.add("message");
openapiFields.add("socialProfiles");
openapiFields.add("employment");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SignalsResponseV0
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!SignalsResponseV0.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in SignalsResponseV0 is not found in the empty JSON string", SignalsResponseV0.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!SignalsResponseV0.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SignalsResponseV0` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `name`
if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) {
Name.validateJsonElement(jsonObj.get("name"));
}
// validate the optional field `demographics`
if (jsonObj.get("demographics") != null && !jsonObj.get("demographics").isJsonNull()) {
Demographics.validateJsonElement(jsonObj.get("demographics"));
}
if (jsonObj.get("locations") != null && !jsonObj.get("locations").isJsonNull()) {
JsonArray jsonArraylocations = jsonObj.getAsJsonArray("locations");
if (jsonArraylocations != null) {
// ensure the json data is an array
if (!jsonObj.get("locations").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `locations` to be an array in the JSON string but got `%s`", jsonObj.get("locations").toString()));
}
// validate the optional field `locations` (array)
for (int i = 0; i < jsonArraylocations.size(); i++) {
Location.validateJsonElement(jsonArraylocations.get(i));
};
}
}
if (jsonObj.get("emails") != null && !jsonObj.get("emails").isJsonNull()) {
JsonArray jsonArrayemails = jsonObj.getAsJsonArray("emails");
if (jsonArrayemails != null) {
// ensure the json data is an array
if (!jsonObj.get("emails").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `emails` to be an array in the JSON string but got `%s`", jsonObj.get("emails").toString()));
}
// validate the optional field `emails` (array)
for (int i = 0; i < jsonArrayemails.size(); i++) {
Email.validateJsonElement(jsonArrayemails.get(i));
};
}
}
if (jsonObj.get("phones") != null && !jsonObj.get("phones").isJsonNull()) {
JsonArray jsonArrayphones = jsonObj.getAsJsonArray("phones");
if (jsonArrayphones != null) {
// ensure the json data is an array
if (!jsonObj.get("phones").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `phones` to be an array in the JSON string but got `%s`", jsonObj.get("phones").toString()));
}
// validate the optional field `phones` (array)
for (int i = 0; i < jsonArrayphones.size(); i++) {
Phone.validateJsonElement(jsonArrayphones.get(i));
};
}
}
// ensure the optional json data is an array if present
if (jsonObj.get("personIds") != null && !jsonObj.get("personIds").isJsonNull() && !jsonObj.get("personIds").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `personIds` to be an array in the JSON string but got `%s`", jsonObj.get("personIds").toString()));
}
if (jsonObj.get("ipAddresses") != null && !jsonObj.get("ipAddresses").isJsonNull()) {
JsonArray jsonArrayipAddresses = jsonObj.getAsJsonArray("ipAddresses");
if (jsonArrayipAddresses != null) {
// ensure the json data is an array
if (!jsonObj.get("ipAddresses").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `ipAddresses` to be an array in the JSON string but got `%s`", jsonObj.get("ipAddresses").toString()));
}
// validate the optional field `ipAddresses` (array)
for (int i = 0; i < jsonArrayipAddresses.size(); i++) {
IpAddress.validateJsonElement(jsonArrayipAddresses.get(i));
};
}
}
if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString()));
}
// validate the optional field `socialProfiles`
if (jsonObj.get("socialProfiles") != null && !jsonObj.get("socialProfiles").isJsonNull()) {
SocialProfileUrls.validateJsonElement(jsonObj.get("socialProfiles"));
}
// validate the optional field `employment`
if (jsonObj.get("employment") != null && !jsonObj.get("employment").isJsonNull()) {
Employment.validateJsonElement(jsonObj.get("employment"));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!SignalsResponseV0.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'SignalsResponseV0' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<SignalsResponseV0> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(SignalsResponseV0.class));
return (TypeAdapter<T>) new TypeAdapter<SignalsResponseV0>() {
@Override
public void write(JsonWriter out, SignalsResponseV0 value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public SignalsResponseV0 read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of SignalsResponseV0 given an JSON string
*
* @param jsonString JSON string
* @return An instance of SignalsResponseV0
* @throws IOException if the JSON string is invalid with respect to SignalsResponseV0
*/
public static SignalsResponseV0 fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, SignalsResponseV0.class);
}
/**
* Convert an instance of SignalsResponseV0 to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/SignalsResponseV20240424.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.Demographics;
import ai.fideo.model.Economic;
import ai.fideo.model.Education;
import ai.fideo.model.Email;
import ai.fideo.model.Employment;
import ai.fideo.model.IpAddress;
import ai.fideo.model.Location;
import ai.fideo.model.NameWithAlias;
import ai.fideo.model.Phone;
import ai.fideo.model.Photo;
import ai.fideo.model.SocialProfileDetails;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* SignalsResponseV20240424
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class SignalsResponseV20240424 {
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private NameWithAlias name;
public static final String SERIALIZED_NAME_DEMOGRAPHICS = "demographics";
@SerializedName(SERIALIZED_NAME_DEMOGRAPHICS)
private Demographics demographics;
public static final String SERIALIZED_NAME_LOCATIONS = "locations";
@SerializedName(SERIALIZED_NAME_LOCATIONS)
private List<Location> locations = new ArrayList<>();
public static final String SERIALIZED_NAME_EMAILS = "emails";
@SerializedName(SERIALIZED_NAME_EMAILS)
private List<Email> emails = new ArrayList<>();
public static final String SERIALIZED_NAME_PHONES = "phones";
@SerializedName(SERIALIZED_NAME_PHONES)
private List<Phone> phones = new ArrayList<>();
public static final String SERIALIZED_NAME_PERSON_IDS = "personIds";
@SerializedName(SERIALIZED_NAME_PERSON_IDS)
private List<String> personIds = new ArrayList<>();
public static final String SERIALIZED_NAME_IP_ADDRESSES = "ipAddresses";
@SerializedName(SERIALIZED_NAME_IP_ADDRESSES)
private List<IpAddress> ipAddresses = new ArrayList<>();
public static final String SERIALIZED_NAME_MESSAGE = "message";
@SerializedName(SERIALIZED_NAME_MESSAGE)
private String message;
public static final String SERIALIZED_NAME_SOCIAL_PROFILES = "socialProfiles";
@SerializedName(SERIALIZED_NAME_SOCIAL_PROFILES)
private List<SocialProfileDetails> socialProfiles = new ArrayList<>();
public static final String SERIALIZED_NAME_EMPLOYMENT = "employment";
@SerializedName(SERIALIZED_NAME_EMPLOYMENT)
private List<Employment> employment = new ArrayList<>();
public static final String SERIALIZED_NAME_EDUCATION = "education";
@SerializedName(SERIALIZED_NAME_EDUCATION)
private List<Education> education = new ArrayList<>();
public static final String SERIALIZED_NAME_PHOTOS = "photos";
@SerializedName(SERIALIZED_NAME_PHOTOS)
private List<Photo> photos = new ArrayList<>();
public static final String SERIALIZED_NAME_ECONOMIC = "economic";
@SerializedName(SERIALIZED_NAME_ECONOMIC)
private Economic economic;
public SignalsResponseV20240424() {
}
public SignalsResponseV20240424 name(NameWithAlias name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
*/
@javax.annotation.Nullable
public NameWithAlias getName() {
return name;
}
public void setName(NameWithAlias name) {
this.name = name;
}
public SignalsResponseV20240424 demographics(Demographics demographics) {
this.demographics = demographics;
return this;
}
/**
* Get demographics
* @return demographics
*/
@javax.annotation.Nullable
public Demographics getDemographics() {
return demographics;
}
public void setDemographics(Demographics demographics) {
this.demographics = demographics;
}
public SignalsResponseV20240424 locations(List<Location> locations) {
this.locations = locations;
return this;
}
public SignalsResponseV20240424 addLocationsItem(Location locationsItem) {
if (this.locations == null) {
this.locations = new ArrayList<>();
}
this.locations.add(locationsItem);
return this;
}
/**
* Get locations
* @return locations
*/
@javax.annotation.Nullable
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public SignalsResponseV20240424 emails(List<Email> emails) {
this.emails = emails;
return this;
}
public SignalsResponseV20240424 addEmailsItem(Email emailsItem) {
if (this.emails == null) {
this.emails = new ArrayList<>();
}
this.emails.add(emailsItem);
return this;
}
/**
* Get emails
* @return emails
*/
@javax.annotation.Nullable
public List<Email> getEmails() {
return emails;
}
public void setEmails(List<Email> emails) {
this.emails = emails;
}
public SignalsResponseV20240424 phones(List<Phone> phones) {
this.phones = phones;
return this;
}
public SignalsResponseV20240424 addPhonesItem(Phone phonesItem) {
if (this.phones == null) {
this.phones = new ArrayList<>();
}
this.phones.add(phonesItem);
return this;
}
/**
* Get phones
* @return phones
*/
@javax.annotation.Nullable
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
public SignalsResponseV20240424 personIds(List<String> personIds) {
this.personIds = personIds;
return this;
}
public SignalsResponseV20240424 addPersonIdsItem(String personIdsItem) {
if (this.personIds == null) {
this.personIds = new ArrayList<>();
}
this.personIds.add(personIdsItem);
return this;
}
/**
* Get personIds
* @return personIds
*/
@javax.annotation.Nullable
public List<String> getPersonIds() {
return personIds;
}
public void setPersonIds(List<String> personIds) {
this.personIds = personIds;
}
public SignalsResponseV20240424 ipAddresses(List<IpAddress> ipAddresses) {
this.ipAddresses = ipAddresses;
return this;
}
public SignalsResponseV20240424 addIpAddressesItem(IpAddress ipAddressesItem) {
if (this.ipAddresses == null) {
this.ipAddresses = new ArrayList<>();
}
this.ipAddresses.add(ipAddressesItem);
return this;
}
/**
* Get ipAddresses
* @return ipAddresses
*/
@javax.annotation.Nullable
public List<IpAddress> getIpAddresses() {
return ipAddresses;
}
public void setIpAddresses(List<IpAddress> ipAddresses) {
this.ipAddresses = ipAddresses;
}
public SignalsResponseV20240424 message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
*/
@javax.annotation.Nullable
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SignalsResponseV20240424 socialProfiles(List<SocialProfileDetails> socialProfiles) {
this.socialProfiles = socialProfiles;
return this;
}
public SignalsResponseV20240424 addSocialProfilesItem(SocialProfileDetails socialProfilesItem) {
if (this.socialProfiles == null) {
this.socialProfiles = new ArrayList<>();
}
this.socialProfiles.add(socialProfilesItem);
return this;
}
/**
* Get socialProfiles
* @return socialProfiles
*/
@javax.annotation.Nullable
public List<SocialProfileDetails> getSocialProfiles() {
return socialProfiles;
}
public void setSocialProfiles(List<SocialProfileDetails> socialProfiles) {
this.socialProfiles = socialProfiles;
}
public SignalsResponseV20240424 employment(List<Employment> employment) {
this.employment = employment;
return this;
}
public SignalsResponseV20240424 addEmploymentItem(Employment employmentItem) {
if (this.employment == null) {
this.employment = new ArrayList<>();
}
this.employment.add(employmentItem);
return this;
}
/**
* Get employment
* @return employment
*/
@javax.annotation.Nullable
public List<Employment> getEmployment() {
return employment;
}
public void setEmployment(List<Employment> employment) {
this.employment = employment;
}
public SignalsResponseV20240424 education(List<Education> education) {
this.education = education;
return this;
}
public SignalsResponseV20240424 addEducationItem(Education educationItem) {
if (this.education == null) {
this.education = new ArrayList<>();
}
this.education.add(educationItem);
return this;
}
/**
* Get education
* @return education
*/
@javax.annotation.Nullable
public List<Education> getEducation() {
return education;
}
public void setEducation(List<Education> education) {
this.education = education;
}
public SignalsResponseV20240424 photos(List<Photo> photos) {
this.photos = photos;
return this;
}
public SignalsResponseV20240424 addPhotosItem(Photo photosItem) {
if (this.photos == null) {
this.photos = new ArrayList<>();
}
this.photos.add(photosItem);
return this;
}
/**
* Get photos
* @return photos
*/
@javax.annotation.Nullable
public List<Photo> getPhotos() {
return photos;
}
public void setPhotos(List<Photo> photos) {
this.photos = photos;
}
public SignalsResponseV20240424 economic(Economic economic) {
this.economic = economic;
return this;
}
/**
* Get economic
* @return economic
*/
@javax.annotation.Nullable
public Economic getEconomic() {
return economic;
}
public void setEconomic(Economic economic) {
this.economic = economic;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SignalsResponseV20240424 signalsResponseV20240424 = (SignalsResponseV20240424) o;
return Objects.equals(this.name, signalsResponseV20240424.name) &&
Objects.equals(this.demographics, signalsResponseV20240424.demographics) &&
Objects.equals(this.locations, signalsResponseV20240424.locations) &&
Objects.equals(this.emails, signalsResponseV20240424.emails) &&
Objects.equals(this.phones, signalsResponseV20240424.phones) &&
Objects.equals(this.personIds, signalsResponseV20240424.personIds) &&
Objects.equals(this.ipAddresses, signalsResponseV20240424.ipAddresses) &&
Objects.equals(this.message, signalsResponseV20240424.message) &&
Objects.equals(this.socialProfiles, signalsResponseV20240424.socialProfiles) &&
Objects.equals(this.employment, signalsResponseV20240424.employment) &&
Objects.equals(this.education, signalsResponseV20240424.education) &&
Objects.equals(this.photos, signalsResponseV20240424.photos) &&
Objects.equals(this.economic, signalsResponseV20240424.economic);
}
@Override
public int hashCode() {
return Objects.hash(name, demographics, locations, emails, phones, personIds, ipAddresses, message, socialProfiles, employment, education, photos, economic);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SignalsResponseV20240424 {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" demographics: ").append(toIndentedString(demographics)).append("\n");
sb.append(" locations: ").append(toIndentedString(locations)).append("\n");
sb.append(" emails: ").append(toIndentedString(emails)).append("\n");
sb.append(" phones: ").append(toIndentedString(phones)).append("\n");
sb.append(" personIds: ").append(toIndentedString(personIds)).append("\n");
sb.append(" ipAddresses: ").append(toIndentedString(ipAddresses)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append(" socialProfiles: ").append(toIndentedString(socialProfiles)).append("\n");
sb.append(" employment: ").append(toIndentedString(employment)).append("\n");
sb.append(" education: ").append(toIndentedString(education)).append("\n");
sb.append(" photos: ").append(toIndentedString(photos)).append("\n");
sb.append(" economic: ").append(toIndentedString(economic)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
openapiFields.add("demographics");
openapiFields.add("locations");
openapiFields.add("emails");
openapiFields.add("phones");
openapiFields.add("personIds");
openapiFields.add("ipAddresses");
openapiFields.add("message");
openapiFields.add("socialProfiles");
openapiFields.add("employment");
openapiFields.add("education");
openapiFields.add("photos");
openapiFields.add("economic");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SignalsResponseV20240424
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!SignalsResponseV20240424.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in SignalsResponseV20240424 is not found in the empty JSON string", SignalsResponseV20240424.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!SignalsResponseV20240424.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SignalsResponseV20240424` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `name`
if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) {
NameWithAlias.validateJsonElement(jsonObj.get("name"));
}
// validate the optional field `demographics`
if (jsonObj.get("demographics") != null && !jsonObj.get("demographics").isJsonNull()) {
Demographics.validateJsonElement(jsonObj.get("demographics"));
}
if (jsonObj.get("locations") != null && !jsonObj.get("locations").isJsonNull()) {
JsonArray jsonArraylocations = jsonObj.getAsJsonArray("locations");
if (jsonArraylocations != null) {
// ensure the json data is an array
if (!jsonObj.get("locations").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `locations` to be an array in the JSON string but got `%s`", jsonObj.get("locations").toString()));
}
// validate the optional field `locations` (array)
for (int i = 0; i < jsonArraylocations.size(); i++) {
Location.validateJsonElement(jsonArraylocations.get(i));
};
}
}
if (jsonObj.get("emails") != null && !jsonObj.get("emails").isJsonNull()) {
JsonArray jsonArrayemails = jsonObj.getAsJsonArray("emails");
if (jsonArrayemails != null) {
// ensure the json data is an array
if (!jsonObj.get("emails").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `emails` to be an array in the JSON string but got `%s`", jsonObj.get("emails").toString()));
}
// validate the optional field `emails` (array)
for (int i = 0; i < jsonArrayemails.size(); i++) {
Email.validateJsonElement(jsonArrayemails.get(i));
};
}
}
if (jsonObj.get("phones") != null && !jsonObj.get("phones").isJsonNull()) {
JsonArray jsonArrayphones = jsonObj.getAsJsonArray("phones");
if (jsonArrayphones != null) {
// ensure the json data is an array
if (!jsonObj.get("phones").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `phones` to be an array in the JSON string but got `%s`", jsonObj.get("phones").toString()));
}
// validate the optional field `phones` (array)
for (int i = 0; i < jsonArrayphones.size(); i++) {
Phone.validateJsonElement(jsonArrayphones.get(i));
};
}
}
// ensure the optional json data is an array if present
if (jsonObj.get("personIds") != null && !jsonObj.get("personIds").isJsonNull() && !jsonObj.get("personIds").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `personIds` to be an array in the JSON string but got `%s`", jsonObj.get("personIds").toString()));
}
if (jsonObj.get("ipAddresses") != null && !jsonObj.get("ipAddresses").isJsonNull()) {
JsonArray jsonArrayipAddresses = jsonObj.getAsJsonArray("ipAddresses");
if (jsonArrayipAddresses != null) {
// ensure the json data is an array
if (!jsonObj.get("ipAddresses").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `ipAddresses` to be an array in the JSON string but got `%s`", jsonObj.get("ipAddresses").toString()));
}
// validate the optional field `ipAddresses` (array)
for (int i = 0; i < jsonArrayipAddresses.size(); i++) {
IpAddress.validateJsonElement(jsonArrayipAddresses.get(i));
};
}
}
if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString()));
}
if (jsonObj.get("socialProfiles") != null && !jsonObj.get("socialProfiles").isJsonNull()) {
JsonArray jsonArraysocialProfiles = jsonObj.getAsJsonArray("socialProfiles");
if (jsonArraysocialProfiles != null) {
// ensure the json data is an array
if (!jsonObj.get("socialProfiles").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `socialProfiles` to be an array in the JSON string but got `%s`", jsonObj.get("socialProfiles").toString()));
}
// validate the optional field `socialProfiles` (array)
for (int i = 0; i < jsonArraysocialProfiles.size(); i++) {
SocialProfileDetails.validateJsonElement(jsonArraysocialProfiles.get(i));
};
}
}
if (jsonObj.get("employment") != null && !jsonObj.get("employment").isJsonNull()) {
JsonArray jsonArrayemployment = jsonObj.getAsJsonArray("employment");
if (jsonArrayemployment != null) {
// ensure the json data is an array
if (!jsonObj.get("employment").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `employment` to be an array in the JSON string but got `%s`", jsonObj.get("employment").toString()));
}
// validate the optional field `employment` (array)
for (int i = 0; i < jsonArrayemployment.size(); i++) {
Employment.validateJsonElement(jsonArrayemployment.get(i));
};
}
}
if (jsonObj.get("education") != null && !jsonObj.get("education").isJsonNull()) {
JsonArray jsonArrayeducation = jsonObj.getAsJsonArray("education");
if (jsonArrayeducation != null) {
// ensure the json data is an array
if (!jsonObj.get("education").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `education` to be an array in the JSON string but got `%s`", jsonObj.get("education").toString()));
}
// validate the optional field `education` (array)
for (int i = 0; i < jsonArrayeducation.size(); i++) {
Education.validateJsonElement(jsonArrayeducation.get(i));
};
}
}
if (jsonObj.get("photos") != null && !jsonObj.get("photos").isJsonNull()) {
JsonArray jsonArrayphotos = jsonObj.getAsJsonArray("photos");
if (jsonArrayphotos != null) {
// ensure the json data is an array
if (!jsonObj.get("photos").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `photos` to be an array in the JSON string but got `%s`", jsonObj.get("photos").toString()));
}
// validate the optional field `photos` (array)
for (int i = 0; i < jsonArrayphotos.size(); i++) {
Photo.validateJsonElement(jsonArrayphotos.get(i));
};
}
}
// validate the optional field `economic`
if (jsonObj.get("economic") != null && !jsonObj.get("economic").isJsonNull()) {
Economic.validateJsonElement(jsonObj.get("economic"));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!SignalsResponseV20240424.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'SignalsResponseV20240424' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<SignalsResponseV20240424> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(SignalsResponseV20240424.class));
return (TypeAdapter<T>) new TypeAdapter<SignalsResponseV20240424>() {
@Override
public void write(JsonWriter out, SignalsResponseV20240424 value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public SignalsResponseV20240424 read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of SignalsResponseV20240424 given an JSON string
*
* @param jsonString JSON string
* @return An instance of SignalsResponseV20240424
* @throws IOException if the JSON string is invalid with respect to SignalsResponseV20240424
*/
public static SignalsResponseV20240424 fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, SignalsResponseV20240424.class);
}
/**
* Convert an instance of SignalsResponseV20240424 to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/SocialProfileDetails.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* SocialProfileDetails
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class SocialProfileDetails {
public static final String SERIALIZED_NAME_USERNAME = "username";
@SerializedName(SERIALIZED_NAME_USERNAME)
private String username;
public static final String SERIALIZED_NAME_USERID = "userid";
@SerializedName(SERIALIZED_NAME_USERID)
private String userid;
public static final String SERIALIZED_NAME_URL = "url";
@SerializedName(SERIALIZED_NAME_URL)
private String url;
public static final String SERIALIZED_NAME_BIO = "bio";
@SerializedName(SERIALIZED_NAME_BIO)
private String bio;
public static final String SERIALIZED_NAME_SERVICE = "service";
@SerializedName(SERIALIZED_NAME_SERVICE)
private String service;
public static final String SERIALIZED_NAME_FOLLOWERS = "followers";
@SerializedName(SERIALIZED_NAME_FOLLOWERS)
private Integer followers;
public static final String SERIALIZED_NAME_FOLLOWING = "following";
@SerializedName(SERIALIZED_NAME_FOLLOWING)
private Integer following;
public SocialProfileDetails() {
}
public SocialProfileDetails username(String username) {
this.username = username;
return this;
}
/**
* Get username
* @return username
*/
@javax.annotation.Nullable
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public SocialProfileDetails userid(String userid) {
this.userid = userid;
return this;
}
/**
* Get userid
* @return userid
*/
@javax.annotation.Nullable
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public SocialProfileDetails url(String url) {
this.url = url;
return this;
}
/**
* Get url
* @return url
*/
@javax.annotation.Nullable
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public SocialProfileDetails bio(String bio) {
this.bio = bio;
return this;
}
/**
* Get bio
* @return bio
*/
@javax.annotation.Nullable
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public SocialProfileDetails service(String service) {
this.service = service;
return this;
}
/**
* Get service
* @return service
*/
@javax.annotation.Nullable
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public SocialProfileDetails followers(Integer followers) {
this.followers = followers;
return this;
}
/**
* Get followers
* @return followers
*/
@javax.annotation.Nullable
public Integer getFollowers() {
return followers;
}
public void setFollowers(Integer followers) {
this.followers = followers;
}
public SocialProfileDetails following(Integer following) {
this.following = following;
return this;
}
/**
* Get following
* @return following
*/
@javax.annotation.Nullable
public Integer getFollowing() {
return following;
}
public void setFollowing(Integer following) {
this.following = following;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SocialProfileDetails socialProfileDetails = (SocialProfileDetails) o;
return Objects.equals(this.username, socialProfileDetails.username) &&
Objects.equals(this.userid, socialProfileDetails.userid) &&
Objects.equals(this.url, socialProfileDetails.url) &&
Objects.equals(this.bio, socialProfileDetails.bio) &&
Objects.equals(this.service, socialProfileDetails.service) &&
Objects.equals(this.followers, socialProfileDetails.followers) &&
Objects.equals(this.following, socialProfileDetails.following);
}
@Override
public int hashCode() {
return Objects.hash(username, userid, url, bio, service, followers, following);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SocialProfileDetails {\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" userid: ").append(toIndentedString(userid)).append("\n");
sb.append(" url: ").append(toIndentedString(url)).append("\n");
sb.append(" bio: ").append(toIndentedString(bio)).append("\n");
sb.append(" service: ").append(toIndentedString(service)).append("\n");
sb.append(" followers: ").append(toIndentedString(followers)).append("\n");
sb.append(" following: ").append(toIndentedString(following)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("username");
openapiFields.add("userid");
openapiFields.add("url");
openapiFields.add("bio");
openapiFields.add("service");
openapiFields.add("followers");
openapiFields.add("following");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SocialProfileDetails
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!SocialProfileDetails.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in SocialProfileDetails is not found in the empty JSON string", SocialProfileDetails.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!SocialProfileDetails.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SocialProfileDetails` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString()));
}
if ((jsonObj.get("userid") != null && !jsonObj.get("userid").isJsonNull()) && !jsonObj.get("userid").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `userid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("userid").toString()));
}
if ((jsonObj.get("url") != null && !jsonObj.get("url").isJsonNull()) && !jsonObj.get("url").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `url` to be a primitive type in the JSON string but got `%s`", jsonObj.get("url").toString()));
}
if ((jsonObj.get("bio") != null && !jsonObj.get("bio").isJsonNull()) && !jsonObj.get("bio").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `bio` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bio").toString()));
}
if ((jsonObj.get("service") != null && !jsonObj.get("service").isJsonNull()) && !jsonObj.get("service").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `service` to be a primitive type in the JSON string but got `%s`", jsonObj.get("service").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!SocialProfileDetails.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'SocialProfileDetails' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<SocialProfileDetails> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(SocialProfileDetails.class));
return (TypeAdapter<T>) new TypeAdapter<SocialProfileDetails>() {
@Override
public void write(JsonWriter out, SocialProfileDetails value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public SocialProfileDetails read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of SocialProfileDetails given an JSON string
*
* @param jsonString JSON string
* @return An instance of SocialProfileDetails
* @throws IOException if the JSON string is invalid with respect to SocialProfileDetails
*/
public static SocialProfileDetails fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, SocialProfileDetails.class);
}
/**
* Convert an instance of SocialProfileDetails to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/SocialProfileReq.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* SocialProfileReq
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class SocialProfileReq {
public static final String SERIALIZED_NAME_USERNAME = "username";
@SerializedName(SERIALIZED_NAME_USERNAME)
private String username;
public static final String SERIALIZED_NAME_USERID = "userid";
@SerializedName(SERIALIZED_NAME_USERID)
private String userid;
public static final String SERIALIZED_NAME_URL = "url";
@SerializedName(SERIALIZED_NAME_URL)
private String url;
public static final String SERIALIZED_NAME_BIO = "bio";
@SerializedName(SERIALIZED_NAME_BIO)
private String bio;
public static final String SERIALIZED_NAME_SERVICE = "service";
@SerializedName(SERIALIZED_NAME_SERVICE)
private String service;
public static final String SERIALIZED_NAME_FOLLOWERS = "followers";
@SerializedName(SERIALIZED_NAME_FOLLOWERS)
private Integer followers;
public static final String SERIALIZED_NAME_FOLLOWING = "following";
@SerializedName(SERIALIZED_NAME_FOLLOWING)
private Integer following;
public static final String SERIALIZED_NAME_SCORE = "score";
@SerializedName(SERIALIZED_NAME_SCORE)
private Integer score;
public SocialProfileReq() {
}
public SocialProfileReq username(String username) {
this.username = username;
return this;
}
/**
* Get username
* @return username
*/
@javax.annotation.Nullable
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public SocialProfileReq userid(String userid) {
this.userid = userid;
return this;
}
/**
* Get userid
* @return userid
*/
@javax.annotation.Nullable
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public SocialProfileReq url(String url) {
this.url = url;
return this;
}
/**
* Get url
* @return url
*/
@javax.annotation.Nullable
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public SocialProfileReq bio(String bio) {
this.bio = bio;
return this;
}
/**
* Get bio
* @return bio
*/
@javax.annotation.Nullable
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public SocialProfileReq service(String service) {
this.service = service;
return this;
}
/**
* Get service
* @return service
*/
@javax.annotation.Nullable
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public SocialProfileReq followers(Integer followers) {
this.followers = followers;
return this;
}
/**
* Get followers
* @return followers
*/
@javax.annotation.Nullable
public Integer getFollowers() {
return followers;
}
public void setFollowers(Integer followers) {
this.followers = followers;
}
public SocialProfileReq following(Integer following) {
this.following = following;
return this;
}
/**
* Get following
* @return following
*/
@javax.annotation.Nullable
public Integer getFollowing() {
return following;
}
public void setFollowing(Integer following) {
this.following = following;
}
public SocialProfileReq score(Integer score) {
this.score = score;
return this;
}
/**
* Get score
* @return score
*/
@javax.annotation.Nullable
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SocialProfileReq socialProfileReq = (SocialProfileReq) o;
return Objects.equals(this.username, socialProfileReq.username) &&
Objects.equals(this.userid, socialProfileReq.userid) &&
Objects.equals(this.url, socialProfileReq.url) &&
Objects.equals(this.bio, socialProfileReq.bio) &&
Objects.equals(this.service, socialProfileReq.service) &&
Objects.equals(this.followers, socialProfileReq.followers) &&
Objects.equals(this.following, socialProfileReq.following) &&
Objects.equals(this.score, socialProfileReq.score);
}
@Override
public int hashCode() {
return Objects.hash(username, userid, url, bio, service, followers, following, score);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SocialProfileReq {\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" userid: ").append(toIndentedString(userid)).append("\n");
sb.append(" url: ").append(toIndentedString(url)).append("\n");
sb.append(" bio: ").append(toIndentedString(bio)).append("\n");
sb.append(" service: ").append(toIndentedString(service)).append("\n");
sb.append(" followers: ").append(toIndentedString(followers)).append("\n");
sb.append(" following: ").append(toIndentedString(following)).append("\n");
sb.append(" score: ").append(toIndentedString(score)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("username");
openapiFields.add("userid");
openapiFields.add("url");
openapiFields.add("bio");
openapiFields.add("service");
openapiFields.add("followers");
openapiFields.add("following");
openapiFields.add("score");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SocialProfileReq
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!SocialProfileReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in SocialProfileReq is not found in the empty JSON string", SocialProfileReq.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!SocialProfileReq.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SocialProfileReq` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString()));
}
if ((jsonObj.get("userid") != null && !jsonObj.get("userid").isJsonNull()) && !jsonObj.get("userid").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `userid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("userid").toString()));
}
if ((jsonObj.get("url") != null && !jsonObj.get("url").isJsonNull()) && !jsonObj.get("url").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `url` to be a primitive type in the JSON string but got `%s`", jsonObj.get("url").toString()));
}
if ((jsonObj.get("bio") != null && !jsonObj.get("bio").isJsonNull()) && !jsonObj.get("bio").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `bio` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bio").toString()));
}
if ((jsonObj.get("service") != null && !jsonObj.get("service").isJsonNull()) && !jsonObj.get("service").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `service` to be a primitive type in the JSON string but got `%s`", jsonObj.get("service").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!SocialProfileReq.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'SocialProfileReq' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<SocialProfileReq> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(SocialProfileReq.class));
return (TypeAdapter<T>) new TypeAdapter<SocialProfileReq>() {
@Override
public void write(JsonWriter out, SocialProfileReq value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public SocialProfileReq read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of SocialProfileReq given an JSON string
*
* @param jsonString JSON string
* @return An instance of SocialProfileReq
* @throws IOException if the JSON string is invalid with respect to SocialProfileReq
*/
public static SocialProfileReq fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, SocialProfileReq.class);
}
/**
* Convert an instance of SocialProfileReq to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/SocialProfileUrls.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* SocialProfileUrls
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class SocialProfileUrls {
public static final String SERIALIZED_NAME_TWITTER_URL = "twitterUrl";
@SerializedName(SERIALIZED_NAME_TWITTER_URL)
private String twitterUrl;
public static final String SERIALIZED_NAME_LINKED_IN_URL = "linkedInUrl";
@SerializedName(SERIALIZED_NAME_LINKED_IN_URL)
private String linkedInUrl;
public SocialProfileUrls() {
}
public SocialProfileUrls twitterUrl(String twitterUrl) {
this.twitterUrl = twitterUrl;
return this;
}
/**
* Get twitterUrl
* @return twitterUrl
*/
@javax.annotation.Nullable
public String getTwitterUrl() {
return twitterUrl;
}
public void setTwitterUrl(String twitterUrl) {
this.twitterUrl = twitterUrl;
}
public SocialProfileUrls linkedInUrl(String linkedInUrl) {
this.linkedInUrl = linkedInUrl;
return this;
}
/**
* Get linkedInUrl
* @return linkedInUrl
*/
@javax.annotation.Nullable
public String getLinkedInUrl() {
return linkedInUrl;
}
public void setLinkedInUrl(String linkedInUrl) {
this.linkedInUrl = linkedInUrl;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SocialProfileUrls socialProfileUrls = (SocialProfileUrls) o;
return Objects.equals(this.twitterUrl, socialProfileUrls.twitterUrl) &&
Objects.equals(this.linkedInUrl, socialProfileUrls.linkedInUrl);
}
@Override
public int hashCode() {
return Objects.hash(twitterUrl, linkedInUrl);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SocialProfileUrls {\n");
sb.append(" twitterUrl: ").append(toIndentedString(twitterUrl)).append("\n");
sb.append(" linkedInUrl: ").append(toIndentedString(linkedInUrl)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("twitterUrl");
openapiFields.add("linkedInUrl");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SocialProfileUrls
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!SocialProfileUrls.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in SocialProfileUrls is not found in the empty JSON string", SocialProfileUrls.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!SocialProfileUrls.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SocialProfileUrls` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("twitterUrl") != null && !jsonObj.get("twitterUrl").isJsonNull()) && !jsonObj.get("twitterUrl").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `twitterUrl` to be a primitive type in the JSON string but got `%s`", jsonObj.get("twitterUrl").toString()));
}
if ((jsonObj.get("linkedInUrl") != null && !jsonObj.get("linkedInUrl").isJsonNull()) && !jsonObj.get("linkedInUrl").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `linkedInUrl` to be a primitive type in the JSON string but got `%s`", jsonObj.get("linkedInUrl").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!SocialProfileUrls.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'SocialProfileUrls' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<SocialProfileUrls> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(SocialProfileUrls.class));
return (TypeAdapter<T>) new TypeAdapter<SocialProfileUrls>() {
@Override
public void write(JsonWriter out, SocialProfileUrls value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public SocialProfileUrls read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of SocialProfileUrls given an JSON string
*
* @param jsonString JSON string
* @return An instance of SocialProfileUrls
* @throws IOException if the JSON string is invalid with respect to SocialProfileUrls
*/
public static SocialProfileUrls fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, SocialProfileUrls.class);
}
/**
* Convert an instance of SocialProfileUrls to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo
|
java-sources/ai/fideo/client-java/1.0.4/ai/fideo/model/VerifyResponse.java
|
/*
* Fideo API
* Fideo Intelligence offers an identity intelligence product that protects the public good. - [Fideo Privacy Policy](https://www.fideo.ai/privacy-policy/)
*
* The version of the OpenAPI document: 1.0.4
* Contact: support@fideo.ai
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package ai.fideo.model;
import java.util.Objects;
import ai.fideo.model.Evidence;
import ai.fideo.model.ScoreDetails;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.fideo.client.JSON;
/**
* VerifyResponse
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.8.0")
public class VerifyResponse {
public static final String SERIALIZED_NAME_ADDRESS_LINE1 = "addressLine1";
@SerializedName(SERIALIZED_NAME_ADDRESS_LINE1)
private String addressLine1;
public static final String SERIALIZED_NAME_ADDRESS_LINE2 = "addressLine2";
@SerializedName(SERIALIZED_NAME_ADDRESS_LINE2)
private String addressLine2;
public static final String SERIALIZED_NAME_CITY = "city";
@SerializedName(SERIALIZED_NAME_CITY)
private String city;
public static final String SERIALIZED_NAME_REGION = "region";
@SerializedName(SERIALIZED_NAME_REGION)
private String region;
public static final String SERIALIZED_NAME_REGION_CODE = "regionCode";
@SerializedName(SERIALIZED_NAME_REGION_CODE)
private String regionCode;
public static final String SERIALIZED_NAME_COUNTRY = "country";
@SerializedName(SERIALIZED_NAME_COUNTRY)
private String country;
public static final String SERIALIZED_NAME_CONTINENT = "continent";
@SerializedName(SERIALIZED_NAME_CONTINENT)
private String continent;
public static final String SERIALIZED_NAME_POSTAL_CODE = "postalCode";
@SerializedName(SERIALIZED_NAME_POSTAL_CODE)
private String postalCode;
public static final String SERIALIZED_NAME_FAMILY_NAME = "familyName";
@SerializedName(SERIALIZED_NAME_FAMILY_NAME)
private String familyName;
public static final String SERIALIZED_NAME_GIVEN_NAME = "givenName";
@SerializedName(SERIALIZED_NAME_GIVEN_NAME)
private String givenName;
public static final String SERIALIZED_NAME_FULL_NAME = "fullName";
@SerializedName(SERIALIZED_NAME_FULL_NAME)
private String fullName;
public static final String SERIALIZED_NAME_PHONE = "phone";
@SerializedName(SERIALIZED_NAME_PHONE)
private String phone;
public static final String SERIALIZED_NAME_EMAIL = "email";
@SerializedName(SERIALIZED_NAME_EMAIL)
private String email;
public static final String SERIALIZED_NAME_MAID = "maid";
@SerializedName(SERIALIZED_NAME_MAID)
private String maid;
public static final String SERIALIZED_NAME_SOCIAL = "social";
@SerializedName(SERIALIZED_NAME_SOCIAL)
private String social;
public static final String SERIALIZED_NAME_NON_ID = "nonId";
@SerializedName(SERIALIZED_NAME_NON_ID)
private String nonId;
public static final String SERIALIZED_NAME_PANORAMA_ID = "panoramaId";
@SerializedName(SERIALIZED_NAME_PANORAMA_ID)
private String panoramaId;
public static final String SERIALIZED_NAME_IP_ADDRESS = "ipAddress";
@SerializedName(SERIALIZED_NAME_IP_ADDRESS)
private String ipAddress;
public static final String SERIALIZED_NAME_BIRTHDAY = "birthday";
@SerializedName(SERIALIZED_NAME_BIRTHDAY)
private String birthday;
public static final String SERIALIZED_NAME_TITLE = "title";
@SerializedName(SERIALIZED_NAME_TITLE)
private String title;
public static final String SERIALIZED_NAME_ORGANIZATION = "organization";
@SerializedName(SERIALIZED_NAME_ORGANIZATION)
private String organization;
public static final String SERIALIZED_NAME_RISK = "risk";
@SerializedName(SERIALIZED_NAME_RISK)
private Double risk;
public static final String SERIALIZED_NAME_EVIDENCE = "evidence";
@SerializedName(SERIALIZED_NAME_EVIDENCE)
private Evidence evidence;
public static final String SERIALIZED_NAME_RISK_V2 = "riskV2";
@SerializedName(SERIALIZED_NAME_RISK_V2)
private Double riskV2;
public static final String SERIALIZED_NAME_RISK_V3 = "riskV3";
@SerializedName(SERIALIZED_NAME_RISK_V3)
private Double riskV3;
public static final String SERIALIZED_NAME_SCORE_DETAILS = "scoreDetails";
@SerializedName(SERIALIZED_NAME_SCORE_DETAILS)
private List<ScoreDetails> scoreDetails = new ArrayList<>();
public VerifyResponse() {
}
public VerifyResponse addressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
return this;
}
/**
* Get addressLine1
* @return addressLine1
*/
@javax.annotation.Nullable
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public VerifyResponse addressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
return this;
}
/**
* Get addressLine2
* @return addressLine2
*/
@javax.annotation.Nullable
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public VerifyResponse city(String city) {
this.city = city;
return this;
}
/**
* Get city
* @return city
*/
@javax.annotation.Nullable
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public VerifyResponse region(String region) {
this.region = region;
return this;
}
/**
* Get region
* @return region
*/
@javax.annotation.Nullable
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public VerifyResponse regionCode(String regionCode) {
this.regionCode = regionCode;
return this;
}
/**
* Get regionCode
* @return regionCode
*/
@javax.annotation.Nullable
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public VerifyResponse country(String country) {
this.country = country;
return this;
}
/**
* Get country
* @return country
*/
@javax.annotation.Nullable
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public VerifyResponse continent(String continent) {
this.continent = continent;
return this;
}
/**
* Get continent
* @return continent
*/
@javax.annotation.Nullable
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public VerifyResponse postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Get postalCode
* @return postalCode
*/
@javax.annotation.Nullable
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public VerifyResponse familyName(String familyName) {
this.familyName = familyName;
return this;
}
/**
* Get familyName
* @return familyName
*/
@javax.annotation.Nullable
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public VerifyResponse givenName(String givenName) {
this.givenName = givenName;
return this;
}
/**
* Get givenName
* @return givenName
*/
@javax.annotation.Nullable
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public VerifyResponse fullName(String fullName) {
this.fullName = fullName;
return this;
}
/**
* Get fullName
* @return fullName
*/
@javax.annotation.Nullable
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public VerifyResponse phone(String phone) {
this.phone = phone;
return this;
}
/**
* Get phone
* @return phone
*/
@javax.annotation.Nullable
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public VerifyResponse email(String email) {
this.email = email;
return this;
}
/**
* Get email
* @return email
*/
@javax.annotation.Nullable
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public VerifyResponse maid(String maid) {
this.maid = maid;
return this;
}
/**
* Get maid
* @return maid
*/
@javax.annotation.Nullable
public String getMaid() {
return maid;
}
public void setMaid(String maid) {
this.maid = maid;
}
public VerifyResponse social(String social) {
this.social = social;
return this;
}
/**
* Get social
* @return social
*/
@javax.annotation.Nullable
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public VerifyResponse nonId(String nonId) {
this.nonId = nonId;
return this;
}
/**
* Get nonId
* @return nonId
*/
@javax.annotation.Nullable
public String getNonId() {
return nonId;
}
public void setNonId(String nonId) {
this.nonId = nonId;
}
public VerifyResponse panoramaId(String panoramaId) {
this.panoramaId = panoramaId;
return this;
}
/**
* Get panoramaId
* @return panoramaId
*/
@javax.annotation.Nullable
public String getPanoramaId() {
return panoramaId;
}
public void setPanoramaId(String panoramaId) {
this.panoramaId = panoramaId;
}
public VerifyResponse ipAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
/**
* Get ipAddress
* @return ipAddress
*/
@javax.annotation.Nullable
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public VerifyResponse birthday(String birthday) {
this.birthday = birthday;
return this;
}
/**
* Get birthday
* @return birthday
*/
@javax.annotation.Nullable
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public VerifyResponse title(String title) {
this.title = title;
return this;
}
/**
* Get title
* @return title
*/
@javax.annotation.Nullable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public VerifyResponse organization(String organization) {
this.organization = organization;
return this;
}
/**
* Get organization
* @return organization
*/
@javax.annotation.Nullable
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public VerifyResponse risk(Double risk) {
this.risk = risk;
return this;
}
/**
* Get risk
* @return risk
*/
@javax.annotation.Nullable
public Double getRisk() {
return risk;
}
public void setRisk(Double risk) {
this.risk = risk;
}
public VerifyResponse evidence(Evidence evidence) {
this.evidence = evidence;
return this;
}
/**
* Get evidence
* @return evidence
*/
@javax.annotation.Nullable
public Evidence getEvidence() {
return evidence;
}
public void setEvidence(Evidence evidence) {
this.evidence = evidence;
}
public VerifyResponse riskV2(Double riskV2) {
this.riskV2 = riskV2;
return this;
}
/**
* Get riskV2
* @return riskV2
*/
@javax.annotation.Nullable
public Double getRiskV2() {
return riskV2;
}
public void setRiskV2(Double riskV2) {
this.riskV2 = riskV2;
}
public VerifyResponse riskV3(Double riskV3) {
this.riskV3 = riskV3;
return this;
}
/**
* Get riskV3
* @return riskV3
*/
@javax.annotation.Nullable
public Double getRiskV3() {
return riskV3;
}
public void setRiskV3(Double riskV3) {
this.riskV3 = riskV3;
}
public VerifyResponse scoreDetails(List<ScoreDetails> scoreDetails) {
this.scoreDetails = scoreDetails;
return this;
}
public VerifyResponse addScoreDetailsItem(ScoreDetails scoreDetailsItem) {
if (this.scoreDetails == null) {
this.scoreDetails = new ArrayList<>();
}
this.scoreDetails.add(scoreDetailsItem);
return this;
}
/**
* Get scoreDetails
* @return scoreDetails
*/
@javax.annotation.Nullable
public List<ScoreDetails> getScoreDetails() {
return scoreDetails;
}
public void setScoreDetails(List<ScoreDetails> scoreDetails) {
this.scoreDetails = scoreDetails;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VerifyResponse verifyResponse = (VerifyResponse) o;
return Objects.equals(this.addressLine1, verifyResponse.addressLine1) &&
Objects.equals(this.addressLine2, verifyResponse.addressLine2) &&
Objects.equals(this.city, verifyResponse.city) &&
Objects.equals(this.region, verifyResponse.region) &&
Objects.equals(this.regionCode, verifyResponse.regionCode) &&
Objects.equals(this.country, verifyResponse.country) &&
Objects.equals(this.continent, verifyResponse.continent) &&
Objects.equals(this.postalCode, verifyResponse.postalCode) &&
Objects.equals(this.familyName, verifyResponse.familyName) &&
Objects.equals(this.givenName, verifyResponse.givenName) &&
Objects.equals(this.fullName, verifyResponse.fullName) &&
Objects.equals(this.phone, verifyResponse.phone) &&
Objects.equals(this.email, verifyResponse.email) &&
Objects.equals(this.maid, verifyResponse.maid) &&
Objects.equals(this.social, verifyResponse.social) &&
Objects.equals(this.nonId, verifyResponse.nonId) &&
Objects.equals(this.panoramaId, verifyResponse.panoramaId) &&
Objects.equals(this.ipAddress, verifyResponse.ipAddress) &&
Objects.equals(this.birthday, verifyResponse.birthday) &&
Objects.equals(this.title, verifyResponse.title) &&
Objects.equals(this.organization, verifyResponse.organization) &&
Objects.equals(this.risk, verifyResponse.risk) &&
Objects.equals(this.evidence, verifyResponse.evidence) &&
Objects.equals(this.riskV2, verifyResponse.riskV2) &&
Objects.equals(this.riskV3, verifyResponse.riskV3) &&
Objects.equals(this.scoreDetails, verifyResponse.scoreDetails);
}
@Override
public int hashCode() {
return Objects.hash(addressLine1, addressLine2, city, region, regionCode, country, continent, postalCode, familyName, givenName, fullName, phone, email, maid, social, nonId, panoramaId, ipAddress, birthday, title, organization, risk, evidence, riskV2, riskV3, scoreDetails);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class VerifyResponse {\n");
sb.append(" addressLine1: ").append(toIndentedString(addressLine1)).append("\n");
sb.append(" addressLine2: ").append(toIndentedString(addressLine2)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" region: ").append(toIndentedString(region)).append("\n");
sb.append(" regionCode: ").append(toIndentedString(regionCode)).append("\n");
sb.append(" country: ").append(toIndentedString(country)).append("\n");
sb.append(" continent: ").append(toIndentedString(continent)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" familyName: ").append(toIndentedString(familyName)).append("\n");
sb.append(" givenName: ").append(toIndentedString(givenName)).append("\n");
sb.append(" fullName: ").append(toIndentedString(fullName)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" maid: ").append(toIndentedString(maid)).append("\n");
sb.append(" social: ").append(toIndentedString(social)).append("\n");
sb.append(" nonId: ").append(toIndentedString(nonId)).append("\n");
sb.append(" panoramaId: ").append(toIndentedString(panoramaId)).append("\n");
sb.append(" ipAddress: ").append(toIndentedString(ipAddress)).append("\n");
sb.append(" birthday: ").append(toIndentedString(birthday)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" organization: ").append(toIndentedString(organization)).append("\n");
sb.append(" risk: ").append(toIndentedString(risk)).append("\n");
sb.append(" evidence: ").append(toIndentedString(evidence)).append("\n");
sb.append(" riskV2: ").append(toIndentedString(riskV2)).append("\n");
sb.append(" riskV3: ").append(toIndentedString(riskV3)).append("\n");
sb.append(" scoreDetails: ").append(toIndentedString(scoreDetails)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("addressLine1");
openapiFields.add("addressLine2");
openapiFields.add("city");
openapiFields.add("region");
openapiFields.add("regionCode");
openapiFields.add("country");
openapiFields.add("continent");
openapiFields.add("postalCode");
openapiFields.add("familyName");
openapiFields.add("givenName");
openapiFields.add("fullName");
openapiFields.add("phone");
openapiFields.add("email");
openapiFields.add("maid");
openapiFields.add("social");
openapiFields.add("nonId");
openapiFields.add("panoramaId");
openapiFields.add("ipAddress");
openapiFields.add("birthday");
openapiFields.add("title");
openapiFields.add("organization");
openapiFields.add("risk");
openapiFields.add("evidence");
openapiFields.add("riskV2");
openapiFields.add("riskV3");
openapiFields.add("scoreDetails");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to VerifyResponse
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!VerifyResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in VerifyResponse is not found in the empty JSON string", VerifyResponse.openapiRequiredFields.toString()));
}
}
Set<Map.Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Map.Entry<String, JsonElement> entry : entries) {
if (!VerifyResponse.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `VerifyResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("addressLine1") != null && !jsonObj.get("addressLine1").isJsonNull()) && !jsonObj.get("addressLine1").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `addressLine1` to be a primitive type in the JSON string but got `%s`", jsonObj.get("addressLine1").toString()));
}
if ((jsonObj.get("addressLine2") != null && !jsonObj.get("addressLine2").isJsonNull()) && !jsonObj.get("addressLine2").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `addressLine2` to be a primitive type in the JSON string but got `%s`", jsonObj.get("addressLine2").toString()));
}
if ((jsonObj.get("city") != null && !jsonObj.get("city").isJsonNull()) && !jsonObj.get("city").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `city` to be a primitive type in the JSON string but got `%s`", jsonObj.get("city").toString()));
}
if ((jsonObj.get("region") != null && !jsonObj.get("region").isJsonNull()) && !jsonObj.get("region").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `region` to be a primitive type in the JSON string but got `%s`", jsonObj.get("region").toString()));
}
if ((jsonObj.get("regionCode") != null && !jsonObj.get("regionCode").isJsonNull()) && !jsonObj.get("regionCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `regionCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("regionCode").toString()));
}
if ((jsonObj.get("country") != null && !jsonObj.get("country").isJsonNull()) && !jsonObj.get("country").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `country` to be a primitive type in the JSON string but got `%s`", jsonObj.get("country").toString()));
}
if ((jsonObj.get("continent") != null && !jsonObj.get("continent").isJsonNull()) && !jsonObj.get("continent").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `continent` to be a primitive type in the JSON string but got `%s`", jsonObj.get("continent").toString()));
}
if ((jsonObj.get("postalCode") != null && !jsonObj.get("postalCode").isJsonNull()) && !jsonObj.get("postalCode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `postalCode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("postalCode").toString()));
}
if ((jsonObj.get("familyName") != null && !jsonObj.get("familyName").isJsonNull()) && !jsonObj.get("familyName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `familyName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("familyName").toString()));
}
if ((jsonObj.get("givenName") != null && !jsonObj.get("givenName").isJsonNull()) && !jsonObj.get("givenName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `givenName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("givenName").toString()));
}
if ((jsonObj.get("fullName") != null && !jsonObj.get("fullName").isJsonNull()) && !jsonObj.get("fullName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `fullName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("fullName").toString()));
}
if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString()));
}
if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString()));
}
if ((jsonObj.get("maid") != null && !jsonObj.get("maid").isJsonNull()) && !jsonObj.get("maid").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `maid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("maid").toString()));
}
if ((jsonObj.get("social") != null && !jsonObj.get("social").isJsonNull()) && !jsonObj.get("social").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `social` to be a primitive type in the JSON string but got `%s`", jsonObj.get("social").toString()));
}
if ((jsonObj.get("nonId") != null && !jsonObj.get("nonId").isJsonNull()) && !jsonObj.get("nonId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `nonId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("nonId").toString()));
}
if ((jsonObj.get("panoramaId") != null && !jsonObj.get("panoramaId").isJsonNull()) && !jsonObj.get("panoramaId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `panoramaId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("panoramaId").toString()));
}
if ((jsonObj.get("ipAddress") != null && !jsonObj.get("ipAddress").isJsonNull()) && !jsonObj.get("ipAddress").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `ipAddress` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ipAddress").toString()));
}
if ((jsonObj.get("birthday") != null && !jsonObj.get("birthday").isJsonNull()) && !jsonObj.get("birthday").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `birthday` to be a primitive type in the JSON string but got `%s`", jsonObj.get("birthday").toString()));
}
if ((jsonObj.get("title") != null && !jsonObj.get("title").isJsonNull()) && !jsonObj.get("title").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `title` to be a primitive type in the JSON string but got `%s`", jsonObj.get("title").toString()));
}
if ((jsonObj.get("organization") != null && !jsonObj.get("organization").isJsonNull()) && !jsonObj.get("organization").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `organization` to be a primitive type in the JSON string but got `%s`", jsonObj.get("organization").toString()));
}
// validate the optional field `evidence`
if (jsonObj.get("evidence") != null && !jsonObj.get("evidence").isJsonNull()) {
Evidence.validateJsonElement(jsonObj.get("evidence"));
}
if (jsonObj.get("scoreDetails") != null && !jsonObj.get("scoreDetails").isJsonNull()) {
JsonArray jsonArrayscoreDetails = jsonObj.getAsJsonArray("scoreDetails");
if (jsonArrayscoreDetails != null) {
// ensure the json data is an array
if (!jsonObj.get("scoreDetails").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `scoreDetails` to be an array in the JSON string but got `%s`", jsonObj.get("scoreDetails").toString()));
}
// validate the optional field `scoreDetails` (array)
for (int i = 0; i < jsonArrayscoreDetails.size(); i++) {
ScoreDetails.validateJsonElement(jsonArrayscoreDetails.get(i));
};
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!VerifyResponse.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'VerifyResponse' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<VerifyResponse> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(VerifyResponse.class));
return (TypeAdapter<T>) new TypeAdapter<VerifyResponse>() {
@Override
public void write(JsonWriter out, VerifyResponse value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public VerifyResponse read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
/**
* Create an instance of VerifyResponse given an JSON string
*
* @param jsonString JSON string
* @return An instance of VerifyResponse
* @throws IOException if the JSON string is invalid with respect to VerifyResponse
*/
public static VerifyResponse fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, VerifyResponse.class);
}
/**
* Convert an instance of VerifyResponse to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/floom/java-sdk/1.0.0/ai
|
java-sources/ai/floom/java-sdk/1.0.0/ai/floom/FloomClient.java
|
package ai.floom;
import ai.floom.request.FloomRequest;
import ai.floom.response.FloomResponse;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import com.fasterxml.jackson.databind.ObjectMapper;
public class FloomClient {
private final String url;
private final String apiKey;
public FloomClient(String url, String apiKey) {
this.url = url;
this.apiKey = apiKey;
}
private HttpRequest buildRequest(String pipelineId, String chatId, String input, Map<String, String> variables) throws Exception {
FloomRequest floomRequest = new FloomRequest();
floomRequest.setPipelineId(pipelineId);
floomRequest.setChatId(chatId);
floomRequest.setInput(input);
floomRequest.setVariables(variables);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(floomRequest);
return HttpRequest.newBuilder()
.uri(URI.create(url + "/v1/Pipelines/Run"))
.header("Api-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
}
public FloomResponse run(String pipelineId, String chatId, String input, Map<String, String> variables) throws Exception {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(160))
.build();
HttpRequest request = buildRequest(pipelineId, chatId, input, variables);
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 200 && response.statusCode() < 300) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(response.body(), FloomResponse.class);
} else {
throw new Exception("Failed to run the pipeline: " + response.body());
}
}
public CompletableFuture<FloomResponse> runAsync(String pipelineId, String chatId, String input, Map<String, String> variables) {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(160))
.build();
HttpRequest request;
try {
request = buildRequest(pipelineId, chatId, input, variables);
} catch (Exception e) {
return CompletableFuture.failedFuture(e);
}
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() >= 200 && response.statusCode() < 300) {
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(response.body(), FloomResponse.class);
} catch (Exception e) {
throw new RuntimeException("Failed to parse response: " + response.body(), e);
}
} else {
throw new RuntimeException("Failed to run the pipeline: " + response.body());
}
});
}
}
|
0
|
java-sources/ai/floom/java-sdk/1.0.0/ai/floom
|
java-sources/ai/floom/java-sdk/1.0.0/ai/floom/request/FloomRequest.java
|
package ai.floom.request;
import lombok.Data;
import java.util.Map;
@Data
public class FloomRequest {
private String pipelineId;
private String chatId;
private String input;
private Map<String, String> variables;
}
|
0
|
java-sources/ai/floom/java-sdk/1.0.0/ai/floom
|
java-sources/ai/floom/java-sdk/1.0.0/ai/floom/response/FloomResponse.java
|
package ai.floom.response;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.util.List;
@Data
public class FloomResponse {
private String messageId;
private String chatId;
private List<FloomResponseValue> values;
private int processingTime;
@JsonIgnore
private Object tokenUsage;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.