repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
Lomeli12/Equivalency | src/main/java/net/lomeli/equivalency/recipes/ForestryRecipes.java | // Path: src/main/java/net/lomeli/equivalency/Equivalency.java
// @Mod(modid = ModVars.MOD_ID, name = ModVars.MOD_NAME, version = ModVars.VERSION, dependencies = "required-after:LomLib;required-after:EE3")
// public class Equivalency {
// public static TransmutationHelper instance;
// public static LogHelper logger = new LogHelper(ModVars.MOD_NAME);
// public static UpdateHelper updater = new UpdateHelper(ModVars.MOD_ID);
// private boolean checkUpdate;
//
// public static void loadModRecipes(String modName) {
// logger.logInfo("Loading " + modName + " recipes...");
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
//
// config.load();
//
// ModVars.emeraldTransmute = config.getBoolean("defaultEmeraldTransmute", Configuration.CATEGORY_GENERAL, true, ModVars.emeraldDesc);
// ModVars.blazeTransmute = config.getBoolean("blazeTransmute", Configuration.CATEGORY_GENERAL, false, ModVars.blazeDesc);
// ModVars.cQTransmute = config.getBoolean("cqTransmute", Configuration.CATEGORY_GENERAL, true, ModVars.cQDesc);
// ModVars.steelTransmute = config.getBoolean("steelTransmute", Configuration.CATEGORY_GENERAL, true, "Disables steel transmutation");
// ModVars.quratzRecipe = config.getBoolean("enableAEQuratzRecipe", Configuration.CATEGORY_GENERAL, true, "Disable Applied Energistics Quartz recipes");
// ModVars.ic2Recipe = config.getBoolean("ic2Uranium", Configuration.CATEGORY_GENERAL, true, "Disable Uranium transmutations if they cause you to crash.");
// ModVars.glowStone = config.getBoolean("glowredstone", Configuration.CATEGORY_GENERAL, true, "Enables glowstone to redstone transmutation");
// checkUpdate = config.getBoolean("updateCheck", Configuration.CATEGORY_GENERAL, true, "Check for Updates");
//
// config.save();
//
// if (checkUpdate) {
// try {
// updater.check(ModVars.UPDATE_XML, ModVars.MAJOR, ModVars.MINOR, ModVars.REVISION);
// } catch (Exception e) {
// }
// }
// }
//
// @Mod.EventHandler
// public void main(FMLInitializationEvent event) {
// if (ModLoaded.isModInstalled(ModVars.EE3_ID, true)) {
// logger.logInfo("Getting transmutation stones");
// TransmutationHelper.addStones();
// FMLCommonHandler.instance().bus().register(new CraftingHandler());
// }
// }
//
// @Mod.EventHandler
// public void postLoad(FMLPostInitializationEvent event) {
// if (ModLoaded.isModInstalled(ModVars.EE3_ID)) {
// if (!TransmutationHelper.transmutationStones.isEmpty()) {
// logger.logInfo("Loading Vanilla Recipes.");
// VanillaRecipes.loadRecipes();
//
// logger.logInfo("Searching for additional mods and loading additional recipes.");
// if (ModLoaded.isModInstalled(ModVars.IC2_ID))
// IC2Recipes.loadRecipes(ModVars.IC2_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.TF_ID))
// // TFRecipes.loadRecipes(ModVars.TF_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.FORESTRY_ID))
// // ForestryRecipes.loadRecipes(ModVars.FORESTRY_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.DART_ID))
// // DartCraftRecipes.loadRecipes(ModVars.DART_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.TC_ID))
// // ThaumCraftRecipes.loadRecipes(ModVars.TC_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.RC_ID))
// // RailCraftRecipes.loadRecipes(ModVars.RC_ID);
//
// if (ModLoaded.isModInstalled(ModVars.AE_ID))
// AppliedEnergisticsRecipes.loadRecipes(ModVars.AE_ID);
//
// if (ModLoaded.isModInstalled(ModVars.TINKER_ID))
// TConstructRecipes.loadRecipes(ModVars.TINKER_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.ARS_ID))
// // ArsMagicaRecipes.loadRecipes(ModVars.ARS_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.PRED_ID))
// // ProjectRedRecipes.loadRecipes(ModVars.PRED_ID);
//
// UniversalRecipes.loadRecipes();
//
// //VanillaRecipes.smelting();
// }
// }
// }
// }
| import java.lang.reflect.Method;
import net.minecraft.item.ItemStack;
import net.lomeli.equivalency.Equivalency; | package net.lomeli.equivalency.recipes;
public class ForestryRecipes {
public static ItemStack copperIngot = getForestryItem("ingotCopper");
public static ItemStack tinIngot = getForestryItem("ingotTin");
public static ItemStack bronzeIngot = getForestryItem("ingotBronze");
public static void loadRecipes(String modName) { | // Path: src/main/java/net/lomeli/equivalency/Equivalency.java
// @Mod(modid = ModVars.MOD_ID, name = ModVars.MOD_NAME, version = ModVars.VERSION, dependencies = "required-after:LomLib;required-after:EE3")
// public class Equivalency {
// public static TransmutationHelper instance;
// public static LogHelper logger = new LogHelper(ModVars.MOD_NAME);
// public static UpdateHelper updater = new UpdateHelper(ModVars.MOD_ID);
// private boolean checkUpdate;
//
// public static void loadModRecipes(String modName) {
// logger.logInfo("Loading " + modName + " recipes...");
// }
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
//
// config.load();
//
// ModVars.emeraldTransmute = config.getBoolean("defaultEmeraldTransmute", Configuration.CATEGORY_GENERAL, true, ModVars.emeraldDesc);
// ModVars.blazeTransmute = config.getBoolean("blazeTransmute", Configuration.CATEGORY_GENERAL, false, ModVars.blazeDesc);
// ModVars.cQTransmute = config.getBoolean("cqTransmute", Configuration.CATEGORY_GENERAL, true, ModVars.cQDesc);
// ModVars.steelTransmute = config.getBoolean("steelTransmute", Configuration.CATEGORY_GENERAL, true, "Disables steel transmutation");
// ModVars.quratzRecipe = config.getBoolean("enableAEQuratzRecipe", Configuration.CATEGORY_GENERAL, true, "Disable Applied Energistics Quartz recipes");
// ModVars.ic2Recipe = config.getBoolean("ic2Uranium", Configuration.CATEGORY_GENERAL, true, "Disable Uranium transmutations if they cause you to crash.");
// ModVars.glowStone = config.getBoolean("glowredstone", Configuration.CATEGORY_GENERAL, true, "Enables glowstone to redstone transmutation");
// checkUpdate = config.getBoolean("updateCheck", Configuration.CATEGORY_GENERAL, true, "Check for Updates");
//
// config.save();
//
// if (checkUpdate) {
// try {
// updater.check(ModVars.UPDATE_XML, ModVars.MAJOR, ModVars.MINOR, ModVars.REVISION);
// } catch (Exception e) {
// }
// }
// }
//
// @Mod.EventHandler
// public void main(FMLInitializationEvent event) {
// if (ModLoaded.isModInstalled(ModVars.EE3_ID, true)) {
// logger.logInfo("Getting transmutation stones");
// TransmutationHelper.addStones();
// FMLCommonHandler.instance().bus().register(new CraftingHandler());
// }
// }
//
// @Mod.EventHandler
// public void postLoad(FMLPostInitializationEvent event) {
// if (ModLoaded.isModInstalled(ModVars.EE3_ID)) {
// if (!TransmutationHelper.transmutationStones.isEmpty()) {
// logger.logInfo("Loading Vanilla Recipes.");
// VanillaRecipes.loadRecipes();
//
// logger.logInfo("Searching for additional mods and loading additional recipes.");
// if (ModLoaded.isModInstalled(ModVars.IC2_ID))
// IC2Recipes.loadRecipes(ModVars.IC2_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.TF_ID))
// // TFRecipes.loadRecipes(ModVars.TF_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.FORESTRY_ID))
// // ForestryRecipes.loadRecipes(ModVars.FORESTRY_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.DART_ID))
// // DartCraftRecipes.loadRecipes(ModVars.DART_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.TC_ID))
// // ThaumCraftRecipes.loadRecipes(ModVars.TC_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.RC_ID))
// // RailCraftRecipes.loadRecipes(ModVars.RC_ID);
//
// if (ModLoaded.isModInstalled(ModVars.AE_ID))
// AppliedEnergisticsRecipes.loadRecipes(ModVars.AE_ID);
//
// if (ModLoaded.isModInstalled(ModVars.TINKER_ID))
// TConstructRecipes.loadRecipes(ModVars.TINKER_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.ARS_ID))
// // ArsMagicaRecipes.loadRecipes(ModVars.ARS_ID);
//
// //if (ModLoaded.isModInstalled(ModVars.PRED_ID))
// // ProjectRedRecipes.loadRecipes(ModVars.PRED_ID);
//
// UniversalRecipes.loadRecipes();
//
// //VanillaRecipes.smelting();
// }
// }
// }
// }
// Path: src/main/java/net/lomeli/equivalency/recipes/ForestryRecipes.java
import java.lang.reflect.Method;
import net.minecraft.item.ItemStack;
import net.lomeli.equivalency.Equivalency;
package net.lomeli.equivalency.recipes;
public class ForestryRecipes {
public static ItemStack copperIngot = getForestryItem("ingotCopper");
public static ItemStack tinIngot = getForestryItem("ingotTin");
public static ItemStack bronzeIngot = getForestryItem("ingotBronze");
public static void loadRecipes(String modName) { | Equivalency.loadModRecipes(modName); |
zielmicha/freeciv-android | android/project/src/main/java/com/zielm/freeciv/DropboxHelper.java | // Path: android/project/src/main/java/com/zielm/freeciv/FreecivActivity.java
// public class FreecivActivity extends SDLActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
// private Object requestPermissionsMonitor = new Object();
//
// public static SDLActivity getSingleton() {
// return mSingleton;
// }
//
// @Override
// protected String[] getLibraries() {
// return new String[] { "SDL2", "SDL2_image", "SDL2_mixer", "SDL2_ttf", "python2.7", "freeciv-client", "main" };
// }
//
// // Called by onCreate()
// @Override
// public void loadLibraries() {
// super.loadLibraries();
// requestStoragePermissions();
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState); // Calls loadLibraries()
// if (haveStoragePermissions()) {
// setWindowStyle(true); // fullscreen
// } else {
// // Avoid to start the app because it'll crash.
// // Replace the startup thread with an empty thread.
// mSDLThread = new Thread(new Runnable() {
// @Override public void run() {}
// },
// "SDLThread");
// mSDLThread.start();
//
// AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
// dlgAlert.setMessage("Freeciv cannot start without access to storage.");
// dlgAlert.setTitle("Storage access required");
// dlgAlert.setPositiveButton("Exit",
// new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog,int id) {
// // if this button is clicked, close current activity
// SDLActivity.mSingleton.finish();
// }
// });
// dlgAlert.setCancelable(false);
// dlgAlert.create().show();
// }
// }
//
// private void requestStoragePermissions() {
// if (!haveStoragePermissions()) {
// String[] requiredPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
// ActivityCompat.requestPermissions(this, requiredPermissions, 1);
// synchronized(requestPermissionsMonitor) {
// try {
// // Dirty fix because I don't know why requestPermissionsMonitor.wait(0) never wakes up
// // => lets'do some polling during a maximum of 1 minute
// for (int i=0; i<240 && !haveStoragePermissions();i++) {
// requestPermissionsMonitor.wait(250);
// }
// } catch (InterruptedException ex) {
// ex.printStackTrace();
// }
// }
// }
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
// synchronized(requestPermissionsMonitor) {
// requestPermissionsMonitor.notify();
// }
// }
//
// private boolean haveStoragePermissions() {
// return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
// && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
// }
// }
| import com.dropbox.client2.*;
import com.dropbox.client2.session.*;
import com.dropbox.client2.android.*;
import com.dropbox.client2.exception.*;
import com.zielm.freeciv.FreecivActivity;
import java.io.*;
import java.util.*;
import android.util.Log; | package com.zielm.freeciv;
public class DropboxHelper {
final static private String APP_KEY = "31sn2p1jkkwev8c";
final static private String APP_SECRET = "mf7kp87rgzy332k";
final static private Session.AccessType ACCESS_TYPE =
Session.AccessType.APP_FOLDER;
private static DropboxAPI<AndroidAuthSession> mDBApi;
final static private String TAG = "freeciv-dropbox";
public static String tokenKey = null;
public static String tokenSecret = null;
public static boolean authFinished;
public static boolean needAuth = false;
public static boolean downloaded = false;
public static boolean downloadedSuccess = false;
static Queue<String> messages = new LinkedList<String>();
public synchronized static String getMessage() {
return messages.poll();
}
synchronized static void addMessage(String s) {
messages.offer(s);
}
public synchronized static void init() { | // Path: android/project/src/main/java/com/zielm/freeciv/FreecivActivity.java
// public class FreecivActivity extends SDLActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
// private Object requestPermissionsMonitor = new Object();
//
// public static SDLActivity getSingleton() {
// return mSingleton;
// }
//
// @Override
// protected String[] getLibraries() {
// return new String[] { "SDL2", "SDL2_image", "SDL2_mixer", "SDL2_ttf", "python2.7", "freeciv-client", "main" };
// }
//
// // Called by onCreate()
// @Override
// public void loadLibraries() {
// super.loadLibraries();
// requestStoragePermissions();
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState); // Calls loadLibraries()
// if (haveStoragePermissions()) {
// setWindowStyle(true); // fullscreen
// } else {
// // Avoid to start the app because it'll crash.
// // Replace the startup thread with an empty thread.
// mSDLThread = new Thread(new Runnable() {
// @Override public void run() {}
// },
// "SDLThread");
// mSDLThread.start();
//
// AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
// dlgAlert.setMessage("Freeciv cannot start without access to storage.");
// dlgAlert.setTitle("Storage access required");
// dlgAlert.setPositiveButton("Exit",
// new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog,int id) {
// // if this button is clicked, close current activity
// SDLActivity.mSingleton.finish();
// }
// });
// dlgAlert.setCancelable(false);
// dlgAlert.create().show();
// }
// }
//
// private void requestStoragePermissions() {
// if (!haveStoragePermissions()) {
// String[] requiredPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
// ActivityCompat.requestPermissions(this, requiredPermissions, 1);
// synchronized(requestPermissionsMonitor) {
// try {
// // Dirty fix because I don't know why requestPermissionsMonitor.wait(0) never wakes up
// // => lets'do some polling during a maximum of 1 minute
// for (int i=0; i<240 && !haveStoragePermissions();i++) {
// requestPermissionsMonitor.wait(250);
// }
// } catch (InterruptedException ex) {
// ex.printStackTrace();
// }
// }
// }
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
// synchronized(requestPermissionsMonitor) {
// requestPermissionsMonitor.notify();
// }
// }
//
// private boolean haveStoragePermissions() {
// return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
// && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
// }
// }
// Path: android/project/src/main/java/com/zielm/freeciv/DropboxHelper.java
import com.dropbox.client2.*;
import com.dropbox.client2.session.*;
import com.dropbox.client2.android.*;
import com.dropbox.client2.exception.*;
import com.zielm.freeciv.FreecivActivity;
import java.io.*;
import java.util.*;
import android.util.Log;
package com.zielm.freeciv;
public class DropboxHelper {
final static private String APP_KEY = "31sn2p1jkkwev8c";
final static private String APP_SECRET = "mf7kp87rgzy332k";
final static private Session.AccessType ACCESS_TYPE =
Session.AccessType.APP_FOLDER;
private static DropboxAPI<AndroidAuthSession> mDBApi;
final static private String TAG = "freeciv-dropbox";
public static String tokenKey = null;
public static String tokenSecret = null;
public static boolean authFinished;
public static boolean needAuth = false;
public static boolean downloaded = false;
public static boolean downloadedSuccess = false;
static Queue<String> messages = new LinkedList<String>();
public synchronized static String getMessage() {
return messages.poll();
}
synchronized static void addMessage(String s) {
messages.offer(s);
}
public synchronized static void init() { | FreecivActivity.getSingleton().runOnUiThread(new Runnable() { |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/model/TestNGMethod.java | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static Method findDataSupplier(final ITestNGMethod testMethod) {
// var annotationMetaData = testMethod.isTest()
// ? getTestAnnotationMetaData(testMethod)
// : getFactoryAnnotationMetaData(testMethod);
// return getDataSupplierMethod(annotationMetaData._1, annotationMetaData._2);
// }
| import io.github.sskorol.core.DataSupplier;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import java.lang.reflect.Method;
import java.util.function.Function;
import static io.github.sskorol.utils.ReflectionUtils.findDataSupplier;
import static io.vavr.API.*;
import static java.util.Arrays.stream;
import static java.util.Optional.ofNullable; | package io.github.sskorol.model;
/**
* Internal entity required for storing TestNG meta data retrieved from listeners.
*/
public class TestNGMethod {
private final ITestNGMethod testMethod;
private final Method dataSupplierMethod;
private final ITestContext context;
private final DataSupplier dataSupplier;
public TestNGMethod(final ITestContext context, final ITestNGMethod testMethod) {
this.context = context;
this.testMethod = testMethod; | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static Method findDataSupplier(final ITestNGMethod testMethod) {
// var annotationMetaData = testMethod.isTest()
// ? getTestAnnotationMetaData(testMethod)
// : getFactoryAnnotationMetaData(testMethod);
// return getDataSupplierMethod(annotationMetaData._1, annotationMetaData._2);
// }
// Path: src/main/java/io/github/sskorol/model/TestNGMethod.java
import io.github.sskorol.core.DataSupplier;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import java.lang.reflect.Method;
import java.util.function.Function;
import static io.github.sskorol.utils.ReflectionUtils.findDataSupplier;
import static io.vavr.API.*;
import static java.util.Arrays.stream;
import static java.util.Optional.ofNullable;
package io.github.sskorol.model;
/**
* Internal entity required for storing TestNG meta data retrieved from listeners.
*/
public class TestNGMethod {
private final ITestNGMethod testMethod;
private final Method dataSupplierMethod;
private final ITestContext context;
private final DataSupplier dataSupplier;
public TestNGMethod(final ITestContext context, final ITestNGMethod testMethod) {
this.context = context;
this.testMethod = testMethod; | this.dataSupplierMethod = findDataSupplier(testMethod); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java | // Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.entities.User;
import io.vavr.Tuple;
import one.util.streamex.StreamEx;
import org.testng.annotations.DataProvider;
import java.util.Iterator;
import java.util.List;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList; | package io.github.sskorol.datasuppliers;
public class ExternalDataSuppliers {
@DataSupplier(transpose = true) | // Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.entities.User;
import io.vavr.Tuple;
import one.util.streamex.StreamEx;
import org.testng.annotations.DataProvider;
import java.util.Iterator;
import java.util.List;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
package io.github.sskorol.datasuppliers;
public class ExternalDataSuppliers {
@DataSupplier(transpose = true) | public User[] getExternalArrayData() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/ArraysDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test; | package io.github.sskorol.testcases;
public class ArraysDataSupplierTests {
@DataSupplier(transpose = true)
public String[] extractCommonArrayData() {
return new String[] {"data1", "data2"};
}
@DataSupplier(flatMap = true)
public StreamEx extractNestedArrayData() {
return StreamEx.of("data3", "data4", "data5").map(ob -> new String[] {ob, ob});
}
@DataSupplier | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/ArraysDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
package io.github.sskorol.testcases;
public class ArraysDataSupplierTests {
@DataSupplier(transpose = true)
public String[] extractCommonArrayData() {
return new String[] {"data1", "data2"};
}
@DataSupplier(flatMap = true)
public StreamEx extractNestedArrayData() {
return StreamEx.of("data3", "data4", "data5").map(ob -> new String[] {ob, ob});
}
@DataSupplier | public User[] getCustomArrayData() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/ArraysDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test; | longs[1] = 6L;
longs[2] = 100L;
return longs;
}
@Test(dataProvider = "extractCommonArrayData")
public void supplyExtractedArrayData(final String ob1, final String ob2) {
// not implemented
}
@Test(dataProvider = "getPrimitiveDoubleArrayData")
public void supplyPrimitiveDoubleArrayData(final double ob) {
// not implemented
}
@Test(dataProvider = "getPrimitiveIntArrayData")
public void supplyPrimitiveIntArrayData(final int ob) {
// not implemented
}
@Test(dataProvider = "getPrimitiveLongArrayData")
public void supplyPrimitiveLongArrayData(final long ob) {
// not implemented
}
@Test(dataProvider = "getCustomArrayData")
public void supplyCustomArrayData(final User user) {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/ArraysDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
longs[1] = 6L;
longs[2] = 100L;
return longs;
}
@Test(dataProvider = "extractCommonArrayData")
public void supplyExtractedArrayData(final String ob1, final String ob2) {
// not implemented
}
@Test(dataProvider = "getPrimitiveDoubleArrayData")
public void supplyPrimitiveDoubleArrayData(final double ob) {
// not implemented
}
@Test(dataProvider = "getPrimitiveIntArrayData")
public void supplyPrimitiveIntArrayData(final int ob) {
// not implemented
}
@Test(dataProvider = "getPrimitiveLongArrayData")
public void supplyPrimitiveLongArrayData(final long ob) {
// not implemented
}
@Test(dataProvider = "getCustomArrayData")
public void supplyCustomArrayData(final User user) {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "getExternalArrayData") |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CommonDataProviderTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
| import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Iterator;
import java.util.stream.Stream; | package io.github.sskorol.testcases;
public class CommonDataProviderTests {
@DataProvider
public Iterator<Object[]> getData() {
return Stream.of("data").map(d -> new Object[] {d}).iterator();
}
@Test
public void shouldPassWithoutDataProvider() {
// not implemented
}
@Test(dataProvider = "getData")
public void shouldPassWithCommonDataProvider(final String ob) {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
// Path: src/test/java/io/github/sskorol/testcases/CommonDataProviderTests.java
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Iterator;
import java.util.stream.Stream;
package io.github.sskorol.testcases;
public class CommonDataProviderTests {
@DataProvider
public Iterator<Object[]> getData() {
return Stream.of("data").map(d -> new Object[] {d}).iterator();
}
@Test
public void shouldPassWithoutDataProvider() {
// not implemented
}
@Test(dataProvider = "getData")
public void shouldPassWithCommonDataProvider(final String ob) {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "getCommonData") |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/utils/ReflectionUtils.java | // Path: src/main/java/io/github/sskorol/model/TypeMappings.java
// @AllArgsConstructor
// public enum TypeMappings {
//
// COLLECTION(Collection.class, d -> StreamEx.of((Collection<?>) d)),
// MAP(Map.class, d -> EntryStream.of((Map<?, ?>) d).mapKeyValue(AbstractMap.SimpleEntry::new)),
// ENTRY(Map.Entry.class, d -> StreamEx.of(((Map.Entry) d).getKey(), ((Map.Entry) d).getValue())),
// OBJECT_ARRAY(Object[].class, d -> StreamEx.of((Object[]) d)),
// DOUBLE_ARRAY(double[].class, d -> DoubleStreamEx.of((double[]) d).boxed()),
// INT_ARRAY(int[].class, d -> IntStreamEx.of((int[]) d).boxed()),
// LONG_ARRAY(long[].class, d -> LongStreamEx.of((long[]) d).boxed()),
// STREAM(Stream.class, d -> StreamEx.of((Stream<?>) d)),
// TUPLE(Tuple.class, d -> StreamEx.of(((Tuple) d).toSeq().toJavaArray()));
//
// private final Class<?> typeClass;
// private final Function<Object, StreamEx<?>> mapper;
//
// public boolean isInstanceOf(final Object ob) {
// return ob != null && typeClass.isAssignableFrom(ob.getClass());
// }
//
// @SuppressWarnings("unchecked")
// public <T> StreamEx<T> streamOf(final T ob) {
// return (StreamEx<T>) mapper.apply(ob);
// }
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.FieldName;
import io.github.sskorol.data.Source;
import io.github.sskorol.model.TypeMappings;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.control.Try;
import lombok.experimental.UtilityClass;
import one.util.streamex.StreamEx;
import org.reflections.Reflections;
import org.testng.ITestNGMethod;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.testng.internal.annotations.IDataProvidable;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import static java.lang.ClassLoader.getSystemResource;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static java.util.Optional.ofNullable;
import static org.joor.Reflect.onClass; | public static <T> Class<T[]> castToArray(final Class<T> entityClass) {
return (Class<T[]>) (entityClass.isArray() ? entityClass : Array.newInstance(entityClass, 1).getClass());
}
@SuppressWarnings("unchecked")
public static <T> Class<T> castToObject(final Class<T> entityClass) {
return (Class<T>) (entityClass.isArray() ? entityClass.getComponentType() : entityClass);
}
public static String getFieldName(final Field field) {
var fieldAnnotation = field.getDeclaredAnnotation(FieldName.class);
return isNull(fieldAnnotation) ? field.getName() : fieldAnnotation.value();
}
public static <T> URL getSourcePath(final Class<T> entity) throws IOException {
return getSourcePath(ofNullable(entity.getDeclaredAnnotation(Source.class))
.map(Source::path)
.orElse(""));
}
public static URL getSourcePath(final String path) throws IOException {
return ofNullable(Try.of(() -> new URL(path)).getOrElseGet(ex -> getSystemResource(path)))
.orElseThrow(() -> new IOException("Unable to access resource specified by " + path + " path"));
}
public static <T> StreamEx<T> streamOf(final T data) {
if (isNull(data)) {
throw new IllegalArgumentException("Nothing to return from data supplier. Test will be skipped.");
}
| // Path: src/main/java/io/github/sskorol/model/TypeMappings.java
// @AllArgsConstructor
// public enum TypeMappings {
//
// COLLECTION(Collection.class, d -> StreamEx.of((Collection<?>) d)),
// MAP(Map.class, d -> EntryStream.of((Map<?, ?>) d).mapKeyValue(AbstractMap.SimpleEntry::new)),
// ENTRY(Map.Entry.class, d -> StreamEx.of(((Map.Entry) d).getKey(), ((Map.Entry) d).getValue())),
// OBJECT_ARRAY(Object[].class, d -> StreamEx.of((Object[]) d)),
// DOUBLE_ARRAY(double[].class, d -> DoubleStreamEx.of((double[]) d).boxed()),
// INT_ARRAY(int[].class, d -> IntStreamEx.of((int[]) d).boxed()),
// LONG_ARRAY(long[].class, d -> LongStreamEx.of((long[]) d).boxed()),
// STREAM(Stream.class, d -> StreamEx.of((Stream<?>) d)),
// TUPLE(Tuple.class, d -> StreamEx.of(((Tuple) d).toSeq().toJavaArray()));
//
// private final Class<?> typeClass;
// private final Function<Object, StreamEx<?>> mapper;
//
// public boolean isInstanceOf(final Object ob) {
// return ob != null && typeClass.isAssignableFrom(ob.getClass());
// }
//
// @SuppressWarnings("unchecked")
// public <T> StreamEx<T> streamOf(final T ob) {
// return (StreamEx<T>) mapper.apply(ob);
// }
// }
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.FieldName;
import io.github.sskorol.data.Source;
import io.github.sskorol.model.TypeMappings;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.control.Try;
import lombok.experimental.UtilityClass;
import one.util.streamex.StreamEx;
import org.reflections.Reflections;
import org.testng.ITestNGMethod;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.testng.internal.annotations.IDataProvidable;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import static java.lang.ClassLoader.getSystemResource;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static java.util.Optional.ofNullable;
import static org.joor.Reflect.onClass;
public static <T> Class<T[]> castToArray(final Class<T> entityClass) {
return (Class<T[]>) (entityClass.isArray() ? entityClass : Array.newInstance(entityClass, 1).getClass());
}
@SuppressWarnings("unchecked")
public static <T> Class<T> castToObject(final Class<T> entityClass) {
return (Class<T>) (entityClass.isArray() ? entityClass.getComponentType() : entityClass);
}
public static String getFieldName(final Field field) {
var fieldAnnotation = field.getDeclaredAnnotation(FieldName.class);
return isNull(fieldAnnotation) ? field.getName() : fieldAnnotation.value();
}
public static <T> URL getSourcePath(final Class<T> entity) throws IOException {
return getSourcePath(ofNullable(entity.getDeclaredAnnotation(Source.class))
.map(Source::path)
.orElse(""));
}
public static URL getSourcePath(final String path) throws IOException {
return ofNullable(Try.of(() -> new URL(path)).getOrElseGet(ex -> getSystemResource(path)))
.orElseThrow(() -> new IOException("Unable to access resource specified by " + path + " path"));
}
public static <T> StreamEx<T> streamOf(final T data) {
if (isNull(data)) {
throw new IllegalArgumentException("Nothing to return from data supplier. Test will be skipped.");
}
| return StreamEx.of(TypeMappings.values()) |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/NullObjectsDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test;
import java.util.List;
import java.util.stream.Stream; | package io.github.sskorol.testcases;
public class NullObjectsDataSupplierTests {
@DataSupplier(transpose = true)
public String extractNullObjectData() {
return null;
}
@DataSupplier | // Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/NullObjectsDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test;
import java.util.List;
import java.util.stream.Stream;
package io.github.sskorol.testcases;
public class NullObjectsDataSupplierTests {
@DataSupplier(transpose = true)
public String extractNullObjectData() {
return null;
}
@DataSupplier | public User getNullObjectData() { |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/data/DataReader.java | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static <T> URL getSourcePath(final Class<T> entity) throws IOException {
// return getSourcePath(ofNullable(entity.getDeclaredAnnotation(Source.class))
// .map(Source::path)
// .orElse(""));
// }
| import one.util.streamex.StreamEx;
import java.io.IOException;
import java.net.URL;
import static io.github.sskorol.utils.ReflectionUtils.getSourcePath; | package io.github.sskorol.data;
public interface DataReader<T> {
StreamEx<T> read();
Class<T> getEntityClass();
String getPath();
default URL getUrl() throws IOException { | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static <T> URL getSourcePath(final Class<T> entity) throws IOException {
// return getSourcePath(ofNullable(entity.getDeclaredAnnotation(Source.class))
// .map(Source::path)
// .orElse(""));
// }
// Path: src/main/java/io/github/sskorol/data/DataReader.java
import one.util.streamex.StreamEx;
import java.io.IOException;
import java.net.URL;
import static io.github.sskorol.utils.ReflectionUtils.getSourcePath;
package io.github.sskorol.data;
public interface DataReader<T> {
StreamEx<T> read();
Class<T> getEntityClass();
String getPath();
default URL getUrl() throws IOException { | return getPath().isEmpty() ? getSourcePath(getEntityClass()) : getSourcePath(getPath()); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier | public StreamEx<User> getUsers() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() { | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() { | return use(CsvReader.class) |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() { | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() { | return use(CsvReader.class) |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() {
return use(CsvReader.class)
.withTarget(User.class)
.withSource("users.csv")
.read();
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() {
return use(CsvReader.class)
.withTarget(User.class)
.withSource("users.csv")
.read();
}
@DataSupplier | public StreamEx<CrimeRecord> getCrimes() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() {
return use(CsvReader.class)
.withTarget(User.class)
.withSource("users.csv")
.read();
}
@DataSupplier
public StreamEx<CrimeRecord> getCrimes() {
return use(CsvReader.class)
.withTarget(CrimeRecord.class)
.read()
.limit(1);
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/CsvReader.java
// @AllArgsConstructor
// public class CsvReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public CsvReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @Override
// public StreamEx<T> read() {
// try (val csvParser = parse(getUrl(), StandardCharsets.UTF_8,
// CSVFormat.Builder.create().setHeader().setSkipHeaderRecord(true).setIgnoreHeaderCase(true).setTrim(true).build())) {
// val entityFields = StreamEx.of(entityClass.getDeclaredFields()).map(ReflectionUtils::getFieldName).toList();
// return StreamEx.of(csvParser.getRecords())
// .map(csvRecord -> StreamEx.of(entityFields).map(csvRecord::get).toArray())
// .map(args -> onClass(entityClass).create(args).get());
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read CSV data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/CrimeRecord.java
// @Source(path = "https://raw.githubusercontent.com/JuliaData/CSV.jl/main/test/testfiles/SacramentocrimeJanuary2006.csv")
// @Data
// public class CrimeRecord {
//
// private final String address;
// @FieldName("crimedescr")
// private final String description;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/CsvDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.CsvReader;
import io.github.sskorol.entities.CrimeRecord;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.User;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class CsvDataSupplierTests {
@DataSupplier
public StreamEx<User> getUsers() {
return use(CsvReader.class)
.withTarget(User.class)
.withSource("users.csv")
.read();
}
@DataSupplier
public StreamEx<CrimeRecord> getCrimes() {
return use(CsvReader.class)
.withTarget(CrimeRecord.class)
.read()
.limit(1);
}
@DataSupplier | public StreamEx<MissingClient> getMissingClient() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/DataSupplierWithCustomNamesTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test; | package io.github.sskorol.testcases;
public class DataSupplierWithCustomNamesTests extends BaseDataSupplier {
@DataSupplier(name = "User supplier") | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/DataSupplierWithCustomNamesTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test;
package io.github.sskorol.testcases;
public class DataSupplierWithCustomNamesTests extends BaseDataSupplier {
@DataSupplier(name = "User supplier") | public User getDataWithCustomName() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/DataSupplierWithCustomNamesTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test; | package io.github.sskorol.testcases;
public class DataSupplierWithCustomNamesTests extends BaseDataSupplier {
@DataSupplier(name = "User supplier")
public User getDataWithCustomName() {
return new User("userFromNamedDataSupplier", "password");
}
@Test(dataProvider = "User supplier")
public void supplyUserFromNamedDataSupplier(final User user) {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/DataSupplierWithCustomNamesTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test;
package io.github.sskorol.testcases;
public class DataSupplierWithCustomNamesTests extends BaseDataSupplier {
@DataSupplier(name = "User supplier")
public User getDataWithCustomName() {
return new User("userFromNamedDataSupplier", "password");
}
@Test(dataProvider = "User supplier")
public void supplyUserFromNamedDataSupplier(final User user) {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "Password supplier") |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/SingleObjectsDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test; | package io.github.sskorol.testcases;
public class SingleObjectsDataSupplierTests {
@DataSupplier
public String getCommonObjectData() {
return "data1";
}
@DataSupplier | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/SingleObjectsDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test;
package io.github.sskorol.testcases;
public class SingleObjectsDataSupplierTests {
@DataSupplier
public String getCommonObjectData() {
return "data1";
}
@DataSupplier | public User getCustomObjectData() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/SingleObjectsDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test; | package io.github.sskorol.testcases;
public class SingleObjectsDataSupplierTests {
@DataSupplier
public String getCommonObjectData() {
return "data1";
}
@DataSupplier
public User getCustomObjectData() {
return new User("username", "password");
}
@DataSupplier
public long getPrimitiveData() {
return 5L;
}
@Test(dataProvider = "getCommonObjectData")
public void supplyCommonObject(final String ob) {
// not implemented
}
@Test(dataProvider = "getPrimitiveData")
public void supplyPrimitiveData(final long ob) {
// not implemented
}
@Test(dataProvider = "getCustomObjectData")
public void supplyCustomObjectData(final User user) {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/SingleObjectsDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import org.testng.annotations.Test;
package io.github.sskorol.testcases;
public class SingleObjectsDataSupplierTests {
@DataSupplier
public String getCommonObjectData() {
return "data1";
}
@DataSupplier
public User getCustomObjectData() {
return new User("username", "password");
}
@DataSupplier
public long getPrimitiveData() {
return 5L;
}
@Test(dataProvider = "getCommonObjectData")
public void supplyCommonObject(final String ob) {
// not implemented
}
@Test(dataProvider = "getPrimitiveData")
public void supplyPrimitiveData(final long ob) {
// not implemented
}
@Test(dataProvider = "getCustomObjectData")
public void supplyCustomObjectData(final User user) {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "getExternalObjectData") |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/core/DataProviderTransformer.java | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static DataSupplier getDataSupplierAnnotation(final Class<?> targetClass, final String targetMethodName) {
// return Try.of(() -> getDataSupplierMethod(targetClass, targetMethodName))
// .map(method -> method.getDeclaredAnnotation(DataSupplier.class))
// .filter(Objects::nonNull)
// .getOrElse((DataSupplier) null);
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> getDataSupplierClass(final IDataProvidable annotation, final Class<T> testClass,
// final Method testMethod) {
// return ofNullable(annotation.getDataProviderClass())
// .map(Class.class::cast)
// .orElseGet(() -> findParentDataSupplierClass(testMethod, testClass));
// }
| import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.internal.annotations.IDataProvidable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Iterator;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierAnnotation;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierClass;
import static java.util.Objects.nonNull; | package io.github.sskorol.core;
/**
* Core listener which transforms custom DataSupplier format to common TestNG DataProvider.
*/
public class DataProviderTransformer implements IAnnotationTransformer {
@DataProvider
public Iterator<Object[]> supplySeqData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@DataProvider(parallel = true)
public Iterator<Object[]> supplyParallelData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@Override
public void transform(final ITestAnnotation annotation, final Class testClass,
final Constructor testConstructor, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, testClass);
}
@Override
public void transform(final IFactoryAnnotation annotation, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, null);
}
| // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static DataSupplier getDataSupplierAnnotation(final Class<?> targetClass, final String targetMethodName) {
// return Try.of(() -> getDataSupplierMethod(targetClass, targetMethodName))
// .map(method -> method.getDeclaredAnnotation(DataSupplier.class))
// .filter(Objects::nonNull)
// .getOrElse((DataSupplier) null);
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> getDataSupplierClass(final IDataProvidable annotation, final Class<T> testClass,
// final Method testMethod) {
// return ofNullable(annotation.getDataProviderClass())
// .map(Class.class::cast)
// .orElseGet(() -> findParentDataSupplierClass(testMethod, testClass));
// }
// Path: src/main/java/io/github/sskorol/core/DataProviderTransformer.java
import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.internal.annotations.IDataProvidable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Iterator;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierAnnotation;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierClass;
import static java.util.Objects.nonNull;
package io.github.sskorol.core;
/**
* Core listener which transforms custom DataSupplier format to common TestNG DataProvider.
*/
public class DataProviderTransformer implements IAnnotationTransformer {
@DataProvider
public Iterator<Object[]> supplySeqData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@DataProvider(parallel = true)
public Iterator<Object[]> supplyParallelData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@Override
public void transform(final ITestAnnotation annotation, final Class testClass,
final Constructor testConstructor, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, testClass);
}
@Override
public void transform(final IFactoryAnnotation annotation, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, null);
}
| private DataSupplierMetaData getMetaData(final ITestContext context, final ITestNGMethod testMethod) { |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/core/DataProviderTransformer.java | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static DataSupplier getDataSupplierAnnotation(final Class<?> targetClass, final String targetMethodName) {
// return Try.of(() -> getDataSupplierMethod(targetClass, targetMethodName))
// .map(method -> method.getDeclaredAnnotation(DataSupplier.class))
// .filter(Objects::nonNull)
// .getOrElse((DataSupplier) null);
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> getDataSupplierClass(final IDataProvidable annotation, final Class<T> testClass,
// final Method testMethod) {
// return ofNullable(annotation.getDataProviderClass())
// .map(Class.class::cast)
// .orElseGet(() -> findParentDataSupplierClass(testMethod, testClass));
// }
| import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.internal.annotations.IDataProvidable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Iterator;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierAnnotation;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierClass;
import static java.util.Objects.nonNull; | package io.github.sskorol.core;
/**
* Core listener which transforms custom DataSupplier format to common TestNG DataProvider.
*/
public class DataProviderTransformer implements IAnnotationTransformer {
@DataProvider
public Iterator<Object[]> supplySeqData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@DataProvider(parallel = true)
public Iterator<Object[]> supplyParallelData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@Override
public void transform(final ITestAnnotation annotation, final Class testClass,
final Constructor testConstructor, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, testClass);
}
@Override
public void transform(final IFactoryAnnotation annotation, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, null);
}
private DataSupplierMetaData getMetaData(final ITestContext context, final ITestNGMethod testMethod) {
return new DataSupplierMetaData(context, testMethod);
}
@SuppressWarnings("FinalLocalVariable")
private <T> void assignCustomDataSupplier(final IDataProvidable annotation, final Method testMethod,
final Class<T> testClass) { | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static DataSupplier getDataSupplierAnnotation(final Class<?> targetClass, final String targetMethodName) {
// return Try.of(() -> getDataSupplierMethod(targetClass, targetMethodName))
// .map(method -> method.getDeclaredAnnotation(DataSupplier.class))
// .filter(Objects::nonNull)
// .getOrElse((DataSupplier) null);
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> getDataSupplierClass(final IDataProvidable annotation, final Class<T> testClass,
// final Method testMethod) {
// return ofNullable(annotation.getDataProviderClass())
// .map(Class.class::cast)
// .orElseGet(() -> findParentDataSupplierClass(testMethod, testClass));
// }
// Path: src/main/java/io/github/sskorol/core/DataProviderTransformer.java
import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.internal.annotations.IDataProvidable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Iterator;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierAnnotation;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierClass;
import static java.util.Objects.nonNull;
package io.github.sskorol.core;
/**
* Core listener which transforms custom DataSupplier format to common TestNG DataProvider.
*/
public class DataProviderTransformer implements IAnnotationTransformer {
@DataProvider
public Iterator<Object[]> supplySeqData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@DataProvider(parallel = true)
public Iterator<Object[]> supplyParallelData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@Override
public void transform(final ITestAnnotation annotation, final Class testClass,
final Constructor testConstructor, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, testClass);
}
@Override
public void transform(final IFactoryAnnotation annotation, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, null);
}
private DataSupplierMetaData getMetaData(final ITestContext context, final ITestNGMethod testMethod) {
return new DataSupplierMetaData(context, testMethod);
}
@SuppressWarnings("FinalLocalVariable")
private <T> void assignCustomDataSupplier(final IDataProvidable annotation, final Method testMethod,
final Class<T> testClass) { | var dataSupplierClass = getDataSupplierClass(annotation, testClass, testMethod); |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/core/DataProviderTransformer.java | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static DataSupplier getDataSupplierAnnotation(final Class<?> targetClass, final String targetMethodName) {
// return Try.of(() -> getDataSupplierMethod(targetClass, targetMethodName))
// .map(method -> method.getDeclaredAnnotation(DataSupplier.class))
// .filter(Objects::nonNull)
// .getOrElse((DataSupplier) null);
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> getDataSupplierClass(final IDataProvidable annotation, final Class<T> testClass,
// final Method testMethod) {
// return ofNullable(annotation.getDataProviderClass())
// .map(Class.class::cast)
// .orElseGet(() -> findParentDataSupplierClass(testMethod, testClass));
// }
| import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.internal.annotations.IDataProvidable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Iterator;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierAnnotation;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierClass;
import static java.util.Objects.nonNull; | package io.github.sskorol.core;
/**
* Core listener which transforms custom DataSupplier format to common TestNG DataProvider.
*/
public class DataProviderTransformer implements IAnnotationTransformer {
@DataProvider
public Iterator<Object[]> supplySeqData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@DataProvider(parallel = true)
public Iterator<Object[]> supplyParallelData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@Override
public void transform(final ITestAnnotation annotation, final Class testClass,
final Constructor testConstructor, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, testClass);
}
@Override
public void transform(final IFactoryAnnotation annotation, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, null);
}
private DataSupplierMetaData getMetaData(final ITestContext context, final ITestNGMethod testMethod) {
return new DataSupplierMetaData(context, testMethod);
}
@SuppressWarnings("FinalLocalVariable")
private <T> void assignCustomDataSupplier(final IDataProvidable annotation, final Method testMethod,
final Class<T> testClass) {
var dataSupplierClass = getDataSupplierClass(annotation, testClass, testMethod); | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// public static DataSupplier getDataSupplierAnnotation(final Class<?> targetClass, final String targetMethodName) {
// return Try.of(() -> getDataSupplierMethod(targetClass, targetMethodName))
// .map(method -> method.getDeclaredAnnotation(DataSupplier.class))
// .filter(Objects::nonNull)
// .getOrElse((DataSupplier) null);
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> getDataSupplierClass(final IDataProvidable annotation, final Class<T> testClass,
// final Method testMethod) {
// return ofNullable(annotation.getDataProviderClass())
// .map(Class.class::cast)
// .orElseGet(() -> findParentDataSupplierClass(testMethod, testClass));
// }
// Path: src/main/java/io/github/sskorol/core/DataProviderTransformer.java
import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.*;
import org.testng.annotations.*;
import org.testng.internal.annotations.IDataProvidable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Iterator;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierAnnotation;
import static io.github.sskorol.utils.ReflectionUtils.getDataSupplierClass;
import static java.util.Objects.nonNull;
package io.github.sskorol.core;
/**
* Core listener which transforms custom DataSupplier format to common TestNG DataProvider.
*/
public class DataProviderTransformer implements IAnnotationTransformer {
@DataProvider
public Iterator<Object[]> supplySeqData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@DataProvider(parallel = true)
public Iterator<Object[]> supplyParallelData(final ITestContext context, final ITestNGMethod testMethod) {
return getMetaData(context, testMethod).getTestData().iterator();
}
@Override
public void transform(final ITestAnnotation annotation, final Class testClass,
final Constructor testConstructor, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, testClass);
}
@Override
public void transform(final IFactoryAnnotation annotation, final Method testMethod) {
assignCustomDataSupplier(annotation, testMethod, null);
}
private DataSupplierMetaData getMetaData(final ITestContext context, final ITestNGMethod testMethod) {
return new DataSupplierMetaData(context, testMethod);
}
@SuppressWarnings("FinalLocalVariable")
private <T> void assignCustomDataSupplier(final IDataProvidable annotation, final Method testMethod,
final Class<T> testClass) {
var dataSupplierClass = getDataSupplierClass(annotation, testClass, testMethod); | var dataSupplierAnnotation = getDataSupplierAnnotation(dataSupplierClass, annotation.getDataProvider()); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/XlsxDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/XlsxReader.java
// @AllArgsConstructor
// public class XlsxReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public XlsxReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// val builder = Reader.of(entityClass).from(new File(getUrl().getFile()));
// return StreamEx.of(ofNullable(entityClass.getDeclaredAnnotation(Sheet.class))
// .map(Sheet::name)
// .map(builder::sheet)
// .orElse(builder)
// .skipEmptyRows(true)
// .list());
// } catch (Exception ex) {
// throw new IllegalArgumentException(
// format("Unable to read XLSX data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.XlsxReader;
import io.github.sskorol.entities.*;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class XlsxDataSupplierTests {
@DataSupplier
public StreamEx<PersonWithoutSheet> getPersonsWithoutSheet() { | // Path: src/main/java/io/github/sskorol/data/XlsxReader.java
// @AllArgsConstructor
// public class XlsxReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public XlsxReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// val builder = Reader.of(entityClass).from(new File(getUrl().getFile()));
// return StreamEx.of(ofNullable(entityClass.getDeclaredAnnotation(Sheet.class))
// .map(Sheet::name)
// .map(builder::sheet)
// .orElse(builder)
// .skipEmptyRows(true)
// .list());
// } catch (Exception ex) {
// throw new IllegalArgumentException(
// format("Unable to read XLSX data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/XlsxDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.XlsxReader;
import io.github.sskorol.entities.*;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class XlsxDataSupplierTests {
@DataSupplier
public StreamEx<PersonWithoutSheet> getPersonsWithoutSheet() { | return use(XlsxReader.class).withTarget(PersonWithoutSheet.class).read(); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/XlsxDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/XlsxReader.java
// @AllArgsConstructor
// public class XlsxReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public XlsxReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// val builder = Reader.of(entityClass).from(new File(getUrl().getFile()));
// return StreamEx.of(ofNullable(entityClass.getDeclaredAnnotation(Sheet.class))
// .map(Sheet::name)
// .map(builder::sheet)
// .orElse(builder)
// .skipEmptyRows(true)
// .list());
// } catch (Exception ex) {
// throw new IllegalArgumentException(
// format("Unable to read XLSX data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.XlsxReader;
import io.github.sskorol.entities.*;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class XlsxDataSupplierTests {
@DataSupplier
public StreamEx<PersonWithoutSheet> getPersonsWithoutSheet() { | // Path: src/main/java/io/github/sskorol/data/XlsxReader.java
// @AllArgsConstructor
// public class XlsxReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public XlsxReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// val builder = Reader.of(entityClass).from(new File(getUrl().getFile()));
// return StreamEx.of(ofNullable(entityClass.getDeclaredAnnotation(Sheet.class))
// .map(Sheet::name)
// .map(builder::sheet)
// .orElse(builder)
// .skipEmptyRows(true)
// .list());
// } catch (Exception ex) {
// throw new IllegalArgumentException(
// format("Unable to read XLSX data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/XlsxDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.XlsxReader;
import io.github.sskorol.entities.*;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class XlsxDataSupplierTests {
@DataSupplier
public StreamEx<PersonWithoutSheet> getPersonsWithoutSheet() { | return use(XlsxReader.class).withTarget(PersonWithoutSheet.class).read(); |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/data/JsonReader.java | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T[]> castToArray(final Class<T> entityClass) {
// return (Class<T[]>) (entityClass.isArray() ? entityClass : Array.newInstance(entityClass, 1).getClass());
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> castToObject(final Class<T> entityClass) {
// return (Class<T>) (entityClass.isArray() ? entityClass.getComponentType() : entityClass);
// }
| import com.google.gson.Gson;
import com.google.gson.JsonElement;
import lombok.AllArgsConstructor;
import lombok.Getter;
import one.util.streamex.StreamEx;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import static com.google.gson.JsonParser.parseReader;
import static io.github.sskorol.utils.ReflectionUtils.castToArray;
import static io.github.sskorol.utils.ReflectionUtils.castToObject;
import static io.vavr.API.*;
import static java.lang.String.format; | package io.github.sskorol.data;
@AllArgsConstructor
public class JsonReader<T> implements DataReader<T> {
@Getter
private final Class<T> entityClass;
@Getter
private final String path;
public JsonReader(final Class<T> entityClass) {
this(entityClass, "");
}
@SuppressWarnings("unchecked")
public StreamEx<T> read() {
var gson = new Gson();
try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
return StreamEx.of((T[]) Match(parseReader(jsonReader)).of( | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T[]> castToArray(final Class<T> entityClass) {
// return (Class<T[]>) (entityClass.isArray() ? entityClass : Array.newInstance(entityClass, 1).getClass());
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> castToObject(final Class<T> entityClass) {
// return (Class<T>) (entityClass.isArray() ? entityClass.getComponentType() : entityClass);
// }
// Path: src/main/java/io/github/sskorol/data/JsonReader.java
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import lombok.AllArgsConstructor;
import lombok.Getter;
import one.util.streamex.StreamEx;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import static com.google.gson.JsonParser.parseReader;
import static io.github.sskorol.utils.ReflectionUtils.castToArray;
import static io.github.sskorol.utils.ReflectionUtils.castToObject;
import static io.vavr.API.*;
import static java.lang.String.format;
package io.github.sskorol.data;
@AllArgsConstructor
public class JsonReader<T> implements DataReader<T> {
@Getter
private final Class<T> entityClass;
@Getter
private final String path;
public JsonReader(final Class<T> entityClass) {
this(entityClass, "");
}
@SuppressWarnings("unchecked")
public StreamEx<T> read() {
var gson = new Gson();
try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
return StreamEx.of((T[]) Match(parseReader(jsonReader)).of( | Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))), |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/data/JsonReader.java | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T[]> castToArray(final Class<T> entityClass) {
// return (Class<T[]>) (entityClass.isArray() ? entityClass : Array.newInstance(entityClass, 1).getClass());
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> castToObject(final Class<T> entityClass) {
// return (Class<T>) (entityClass.isArray() ? entityClass.getComponentType() : entityClass);
// }
| import com.google.gson.Gson;
import com.google.gson.JsonElement;
import lombok.AllArgsConstructor;
import lombok.Getter;
import one.util.streamex.StreamEx;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import static com.google.gson.JsonParser.parseReader;
import static io.github.sskorol.utils.ReflectionUtils.castToArray;
import static io.github.sskorol.utils.ReflectionUtils.castToObject;
import static io.vavr.API.*;
import static java.lang.String.format; | package io.github.sskorol.data;
@AllArgsConstructor
public class JsonReader<T> implements DataReader<T> {
@Getter
private final Class<T> entityClass;
@Getter
private final String path;
public JsonReader(final Class<T> entityClass) {
this(entityClass, "");
}
@SuppressWarnings("unchecked")
public StreamEx<T> read() {
var gson = new Gson();
try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))), | // Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T[]> castToArray(final Class<T> entityClass) {
// return (Class<T[]>) (entityClass.isArray() ? entityClass : Array.newInstance(entityClass, 1).getClass());
// }
//
// Path: src/main/java/io/github/sskorol/utils/ReflectionUtils.java
// @SuppressWarnings("unchecked")
// public static <T> Class<T> castToObject(final Class<T> entityClass) {
// return (Class<T>) (entityClass.isArray() ? entityClass.getComponentType() : entityClass);
// }
// Path: src/main/java/io/github/sskorol/data/JsonReader.java
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import lombok.AllArgsConstructor;
import lombok.Getter;
import one.util.streamex.StreamEx;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import static com.google.gson.JsonParser.parseReader;
import static io.github.sskorol.utils.ReflectionUtils.castToArray;
import static io.github.sskorol.utils.ReflectionUtils.castToObject;
import static io.vavr.API.*;
import static java.lang.String.format;
package io.github.sskorol.data;
@AllArgsConstructor
public class JsonReader<T> implements DataReader<T> {
@Getter
private final Class<T> entityClass;
@Getter
private final String path;
public JsonReader(final Class<T> entityClass) {
this(entityClass, "");
}
@SuppressWarnings("unchecked")
public StreamEx<T> read() {
var gson = new Gson();
try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))), | Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))}) |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier | public StreamEx<JsonUser> getUsers() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() { | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() { | return use(JsonReader.class).withTarget(JsonUser.class).read(); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() { | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() { | return use(JsonReader.class).withTarget(JsonUser.class).read(); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() {
return use(JsonReader.class).withTarget(JsonUser.class).read();
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() {
return use(JsonReader.class).withTarget(JsonUser.class).read();
}
@DataSupplier | public StreamEx<Client> getClient() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() {
return use(JsonReader.class).withTarget(JsonUser.class).read();
}
@DataSupplier
public StreamEx<Client> getClient() {
return use(JsonReader.class).withTarget(Client.class).read();
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() {
return use(JsonReader.class).withTarget(JsonUser.class).read();
}
@DataSupplier
public StreamEx<Client> getClient() {
return use(JsonReader.class).withTarget(Client.class).read();
}
@DataSupplier | public StreamEx<Animal> getAnimals() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() {
return use(JsonReader.class).withTarget(JsonUser.class).read();
}
@DataSupplier
public StreamEx<Client> getClient() {
return use(JsonReader.class).withTarget(Client.class).read();
}
@DataSupplier
public StreamEx<Animal> getAnimals() {
return use(JsonReader.class)
.withTarget(Animal.class)
.withSource("https://raw.githubusercontent.com/LearnWebCode/json-example/master/animals-1.json")
.read();
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/JsonReader.java
// @AllArgsConstructor
// public class JsonReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public JsonReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// @SuppressWarnings("unchecked")
// public StreamEx<T> read() {
// var gson = new Gson();
// try (var streamReader = new InputStreamReader(getUrl().openStream(), StandardCharsets.UTF_8);
// var jsonReader = new com.google.gson.stream.JsonReader(streamReader)) {
// return StreamEx.of((T[]) Match(parseReader(jsonReader)).of(
// Case($(JsonElement::isJsonArray), j -> gson.fromJson(j, castToArray(entityClass))),
// Case($(), j -> (T[]) new Object[] {gson.fromJson(j, castToObject(entityClass))})
// ));
// } catch (IOException ex) {
// throw new IllegalArgumentException(
// format("Unable to read JSON data to %s. Check provided path.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/Animal.java
// @Data
// public class Animal {
//
// private final String name;
// private final String species;
// private final Food foods;
// }
//
// Path: src/test/java/io/github/sskorol/entities/Client.java
// @Source(path = "client.json")
// @Data
// public class Client {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/JsonUser.java
// @Source(path = "users.json")
// @Data
// public class JsonUser {
//
// @SerializedName("username")
// private final String name;
// private final String password;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/JsonDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.JsonReader;
import io.github.sskorol.entities.Animal;
import io.github.sskorol.entities.Client;
import io.github.sskorol.entities.JsonUser;
import io.github.sskorol.entities.MissingClient;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class JsonDataSupplierTests {
@DataSupplier
public StreamEx<JsonUser> getUsers() {
return use(JsonReader.class).withTarget(JsonUser.class).read();
}
@DataSupplier
public StreamEx<Client> getClient() {
return use(JsonReader.class).withTarget(Client.class).read();
}
@DataSupplier
public StreamEx<Animal> getAnimals() {
return use(JsonReader.class)
.withTarget(Animal.class)
.withSource("https://raw.githubusercontent.com/LearnWebCode/json-example/master/animals-1.json")
.read();
}
@DataSupplier | public StreamEx<MissingClient> getMissingClient() { |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/core/DataSupplierInterceptor.java | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
| import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import java.util.Collection;
import java.util.Collections; | package io.github.sskorol.core;
/**
* A listener which allows retrieving useful meta-data. Should be implemented on client side, and linked via SPI.
*/
public interface DataSupplierInterceptor {
default void beforeDataPreparation(final ITestContext context, final ITestNGMethod method) {
// not implemented
}
default void afterDataPreparation(final ITestContext context, final ITestNGMethod method) {
// not implemented
}
| // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
// Path: src/main/java/io/github/sskorol/core/DataSupplierInterceptor.java
import io.github.sskorol.model.DataSupplierMetaData;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import java.util.Collection;
import java.util.Collections;
package io.github.sskorol.core;
/**
* A listener which allows retrieving useful meta-data. Should be implemented on client side, and linked via SPI.
*/
public interface DataSupplierInterceptor {
default void beforeDataPreparation(final ITestContext context, final ITestNGMethod method) {
// not implemented
}
default void afterDataPreparation(final ITestContext context, final ITestNGMethod method) {
// not implemented
}
| default void onDataPreparation(final DataSupplierMetaData metaData) { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CollectionsDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.Arrays.asList; | package io.github.sskorol.testcases;
public class CollectionsDataSupplierTests {
@DataSupplier
public List<String> getCommonListData() {
return asList("data1", "data2");
}
@DataSupplier
public Map<Integer, String> getCommonMapData() {
return EntryStream.of(asList("user1", "user2")).toMap();
}
@DataSupplier(flatMap = true)
public Map<Integer, String> getInternallyExtractedMapData() {
return EntryStream.of(asList("user3", "user4")).toMap();
}
@DataSupplier(transpose = true)
public Map<Integer, String> getTransposedMapData() {
return EntryStream.of(asList("user5", "user6")).toMap();
}
@DataSupplier(transpose = true, flatMap = true)
public Map<Integer, String> getTransposedInternallyExtractedMapData() {
return EntryStream.of(asList("user7", "user8")).toMap();
}
@DataSupplier(transpose = true) | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/CollectionsDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.Arrays.asList;
package io.github.sskorol.testcases;
public class CollectionsDataSupplierTests {
@DataSupplier
public List<String> getCommonListData() {
return asList("data1", "data2");
}
@DataSupplier
public Map<Integer, String> getCommonMapData() {
return EntryStream.of(asList("user1", "user2")).toMap();
}
@DataSupplier(flatMap = true)
public Map<Integer, String> getInternallyExtractedMapData() {
return EntryStream.of(asList("user3", "user4")).toMap();
}
@DataSupplier(transpose = true)
public Map<Integer, String> getTransposedMapData() {
return EntryStream.of(asList("user5", "user6")).toMap();
}
@DataSupplier(transpose = true, flatMap = true)
public Map<Integer, String> getTransposedInternallyExtractedMapData() {
return EntryStream.of(asList("user7", "user8")).toMap();
}
@DataSupplier(transpose = true) | public Set<User> extractCustomListData() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/CollectionsDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.Arrays.asList; |
@DataSupplier(transpose = true)
public Map<Integer, String> getTransposedMapData() {
return EntryStream.of(asList("user5", "user6")).toMap();
}
@DataSupplier(transpose = true, flatMap = true)
public Map<Integer, String> getTransposedInternallyExtractedMapData() {
return EntryStream.of(asList("user7", "user8")).toMap();
}
@DataSupplier(transpose = true)
public Set<User> extractCustomListData() {
return StreamEx.of(
new User("username", "password"),
new User("username", "password"),
null,
null).toSet();
}
@Test(dataProvider = "getCommonListData")
public void supplyCommonListData(final String ob) {
// not implemented
}
@Test(dataProvider = "extractCustomListData")
public void supplyCustomListData(final User... users) {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/CollectionsDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.Arrays.asList;
@DataSupplier(transpose = true)
public Map<Integer, String> getTransposedMapData() {
return EntryStream.of(asList("user5", "user6")).toMap();
}
@DataSupplier(transpose = true, flatMap = true)
public Map<Integer, String> getTransposedInternallyExtractedMapData() {
return EntryStream.of(asList("user7", "user8")).toMap();
}
@DataSupplier(transpose = true)
public Set<User> extractCustomListData() {
return StreamEx.of(
new User("username", "password"),
new User("username", "password"),
null,
null).toSet();
}
@Test(dataProvider = "getCommonListData")
public void supplyCommonListData(final String ob) {
// not implemented
}
@Test(dataProvider = "extractCustomListData")
public void supplyCustomListData(final User... users) {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "getExternalCollectionData") |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/TupleDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import io.vavr.Tuple;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static java.util.Arrays.asList; | package io.github.sskorol.testcases;
public class TupleDataSupplierTests {
@DataSupplier
public Tuple getCommonTupleData() {
return Tuple.of("data1", "data2");
}
@DataSupplier(transpose = true)
public Tuple extractCommonTupleData() { | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/TupleDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import io.vavr.Tuple;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static java.util.Arrays.asList;
package io.github.sskorol.testcases;
public class TupleDataSupplierTests {
@DataSupplier
public Tuple getCommonTupleData() {
return Tuple.of("data1", "data2");
}
@DataSupplier(transpose = true)
public Tuple extractCommonTupleData() { | return Tuple.of(1, new User("name", "password")); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/TupleDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import io.vavr.Tuple;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static java.util.Arrays.asList; | package io.github.sskorol.testcases;
public class TupleDataSupplierTests {
@DataSupplier
public Tuple getCommonTupleData() {
return Tuple.of("data1", "data2");
}
@DataSupplier(transpose = true)
public Tuple extractCommonTupleData() {
return Tuple.of(1, new User("name", "password"));
}
@DataSupplier(flatMap = true)
public StreamEx getInternallyExtractedTupleData() {
var list1 = asList("data1", "data2");
var list2 = asList("data3", "data4", "data5");
var minSize = Math.min(list1.size(), list2.size());
return EntryStream.of(list1)
.limit(minSize)
.mapKeyValue((i, val) -> Tuple.of(val, list2.get(i)));
}
@Test(dataProvider = "getCommonTupleData")
public void supplyCommonTupleData(final String ob) {
// not implemented
}
@Test(dataProvider = "extractCommonTupleData")
public void supplyExtractedTupleData(final int ob, final User user) {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/TupleDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import io.vavr.Tuple;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static java.util.Arrays.asList;
package io.github.sskorol.testcases;
public class TupleDataSupplierTests {
@DataSupplier
public Tuple getCommonTupleData() {
return Tuple.of("data1", "data2");
}
@DataSupplier(transpose = true)
public Tuple extractCommonTupleData() {
return Tuple.of(1, new User("name", "password"));
}
@DataSupplier(flatMap = true)
public StreamEx getInternallyExtractedTupleData() {
var list1 = asList("data1", "data2");
var list2 = asList("data3", "data4", "data5");
var minSize = Math.min(list1.size(), list2.size());
return EntryStream.of(list1)
.limit(minSize)
.mapKeyValue((i, val) -> Tuple.of(val, list2.get(i)));
}
@Test(dataProvider = "getCommonTupleData")
public void supplyCommonTupleData(final String ob) {
// not implemented
}
@Test(dataProvider = "extractCommonTupleData")
public void supplyExtractedTupleData(final int ob, final User user) {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "getExternalTupleData") |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/StreamsDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing; | package io.github.sskorol.testcases;
public class StreamsDataSupplierTests {
@DataSupplier
public Stream<Integer> getPrimitiveStreamData() {
return IntStream.range(0, 10)
.filter(d -> d % 2 == 0)
.boxed();
}
@DataSupplier(transpose = true) | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/StreamsDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
package io.github.sskorol.testcases;
public class StreamsDataSupplierTests {
@DataSupplier
public Stream<Integer> getPrimitiveStreamData() {
return IntStream.range(0, 10)
.filter(d -> d % 2 == 0)
.boxed();
}
@DataSupplier(transpose = true) | public Stream<User> extractCustomStreamData() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/StreamsDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing; | .map(User::getName)
.sorted()
.skip(1);
}
@DataSupplier(flatMap = true)
public StreamEx getInternallyExtractedStreamData() {
return StreamEx.of(asList("name1", "password1"), asList("name2", "password2"));
}
@DataSupplier(indices = {-1, 0, 2, 4, 6, 8, 10})
public StreamEx getFilteredByIndicesData() {
return IntStreamEx.range(0, 10).boxed();
}
@Test(dataProvider = "getPrimitiveStreamData")
public void supplyPrimitiveStreamData(final int ob) {
// not implemented
}
@Test(dataProvider = "extractCustomStreamData")
public void supplyExtractedCustomStreamData(final User user1, final User user2) {
// not implemented
}
@Test(dataProvider = "getCustomStreamData")
public void supplyCustomStreamData(final String ob) {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/User.java
// @Data
// public class User {
//
// @FieldName("username")
// private final String name;
// private final String password;
// }
// Path: src/test/java/io/github/sskorol/testcases/StreamsDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import io.github.sskorol.entities.User;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
.map(User::getName)
.sorted()
.skip(1);
}
@DataSupplier(flatMap = true)
public StreamEx getInternallyExtractedStreamData() {
return StreamEx.of(asList("name1", "password1"), asList("name2", "password2"));
}
@DataSupplier(indices = {-1, 0, 2, 4, 6, 8, 10})
public StreamEx getFilteredByIndicesData() {
return IntStreamEx.range(0, 10).boxed();
}
@Test(dataProvider = "getPrimitiveStreamData")
public void supplyPrimitiveStreamData(final int ob) {
// not implemented
}
@Test(dataProvider = "extractCustomStreamData")
public void supplyExtractedCustomStreamData(final User user1, final User user2) {
// not implemented
}
@Test(dataProvider = "getCustomStreamData")
public void supplyCustomStreamData(final String ob) {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "getExternalStreamData") |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/MissingDataSupplierTests.java | // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
| import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import org.testng.annotations.Test; | package io.github.sskorol.testcases;
public class MissingDataSupplierTests {
@Test(dataProvider = "missingDataSupplier")
public void failOnDataSupplying() {
// not implemented
}
| // Path: src/test/java/io/github/sskorol/datasuppliers/ExternalDataSuppliers.java
// public class ExternalDataSuppliers {
//
// @DataSupplier(transpose = true)
// public User[] getExternalArrayData() {
// return new User[]{
// new User("user1", "password1"),
// new User("user2", "password2")
// };
// }
//
// @DataSupplier
// public List<String> getExternalCollectionData() {
// return asList("data1", "data2");
// }
//
// @DataSupplier
// public Stream<Long> getExternalStreamData() {
// return LongStream.range(0, 10)
// .filter(i -> i % 2 != 0)
// .boxed();
// }
//
// @DataSupplier
// public double getExternalObjectData() {
// return 0.1;
// }
//
// @DataSupplier(name = "Password supplier")
// public String getPasswordFromNamedDataSupplier() {
// return "qwerty";
// }
//
// @DataSupplier(transpose = true)
// public Tuple getExternalTupleData() {
// return Tuple.of("1", 2, 3.0);
// }
//
// @DataProvider
// public static Iterator<Object[]> getCommonData() {
// return Stream.of("data").map(d -> new Object[]{d}).iterator();
// }
//
// @DataSupplier
// public String getClassLevelGlobalData() {
// return "data1";
// }
//
// @DataSupplier
// public String getClassLevelLocalData() {
// return "data2";
// }
//
// @DataSupplier(flatMap = true)
// public StreamEx externalHashes() {
// return StreamEx.of(Tuple.of("hash1", "password1"), Tuple.of("hash2", "password2"));
// }
// }
// Path: src/test/java/io/github/sskorol/testcases/MissingDataSupplierTests.java
import io.github.sskorol.datasuppliers.ExternalDataSuppliers;
import org.testng.annotations.Test;
package io.github.sskorol.testcases;
public class MissingDataSupplierTests {
@Test(dataProvider = "missingDataSupplier")
public void failOnDataSupplying() {
// not implemented
}
| @Test(dataProviderClass = ExternalDataSuppliers.class, dataProvider = "missingExternalDataSupplier") |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier | public StreamEx<DockerConfiguration> getDockerConfiguration() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() { | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() { | return use(YamlReader.class).withTarget(DockerConfiguration.class).read(); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() { | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() { | return use(YamlReader.class).withTarget(DockerConfiguration.class).read(); |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() {
return use(YamlReader.class).withTarget(DockerConfiguration.class).read();
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() {
return use(YamlReader.class).withTarget(DockerConfiguration.class).read();
}
@DataSupplier | public StreamEx<YamlUser> getUsers() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() {
return use(YamlReader.class).withTarget(DockerConfiguration.class).read();
}
@DataSupplier
public StreamEx<YamlUser> getUsers() {
return use(YamlReader.class).withTarget(YamlUser.class).read();
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() {
return use(YamlReader.class).withTarget(DockerConfiguration.class).read();
}
@DataSupplier
public StreamEx<YamlUser> getUsers() {
return use(YamlReader.class).withTarget(YamlUser.class).read();
}
@DataSupplier | public StreamEx<TravisConfiguration> getTravisConfiguration() { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
| import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use; | package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() {
return use(YamlReader.class).withTarget(DockerConfiguration.class).read();
}
@DataSupplier
public StreamEx<YamlUser> getUsers() {
return use(YamlReader.class).withTarget(YamlUser.class).read();
}
@DataSupplier
public StreamEx<TravisConfiguration> getTravisConfiguration() {
return use(YamlReader.class).withTarget(TravisConfiguration.class).read();
}
@DataSupplier | // Path: src/main/java/io/github/sskorol/data/YamlReader.java
// @AllArgsConstructor
// public class YamlReader<T> implements DataReader<T> {
//
// @Getter
// private final Class<T> entityClass;
// @Getter
// private final String path;
//
// public YamlReader(final Class<T> entityClass) {
// this(entityClass, "");
// }
//
// public StreamEx<T> read() {
// try {
// var yamlFactory = new YAMLFactory();
// return StreamEx.of(new ObjectMapper(yamlFactory)
// .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
// .readValues(yamlFactory.createParser(getUrl()), entityClass)
// .readAll());
// } catch (Exception ex) {
// throw new IllegalArgumentException(format("Unable to read YAML data to %s.", entityClass), ex);
// }
// }
// }
//
// Path: src/test/java/io/github/sskorol/entities/DockerConfiguration.java
// @Source(path = "docker-compose.yml")
// @Data
// @NoArgsConstructor
// public class DockerConfiguration {
//
// private String version;
// private Map<String, ServiceConfiguration> services;
// }
//
// Path: src/test/java/io/github/sskorol/entities/MissingClient.java
// @Source(path = "unknown")
// @Data
// public class MissingClient {
//
// private final String firstName;
// private final String lastName;
// }
//
// Path: src/test/java/io/github/sskorol/entities/TravisConfiguration.java
// @Source(path = "https://raw.githubusercontent.com/sskorol/test-data-supplier/master/.travis.yml")
// @Data
// @NoArgsConstructor
// public class TravisConfiguration {
//
// private String language;
// private boolean sudo;
// private boolean install;
// private Map<String, Addon> addons;
// private List<String> jdk;
// private List<String> script;
// private Map<String, List<String>> cache;
// private Map<String, Email> notifications;
// }
//
// Path: src/test/java/io/github/sskorol/entities/YamlUser.java
// @Source(path = "users.yml")
// @Data
// @NoArgsConstructor
// public class YamlUser {
//
// @JsonProperty("username")
// private String name;
// private String password;
// }
//
// Path: src/main/java/io/github/sskorol/data/TestDataReader.java
// public static <T extends DataReader<?>> TestDataReader<T> use(final Class<T> dataReaderClass) {
// return new TestDataReader<>(dataReaderClass);
// }
// Path: src/test/java/io/github/sskorol/testcases/YamlDataSupplierTests.java
import io.github.sskorol.core.DataSupplier;
import io.github.sskorol.data.YamlReader;
import io.github.sskorol.entities.DockerConfiguration;
import io.github.sskorol.entities.MissingClient;
import io.github.sskorol.entities.TravisConfiguration;
import io.github.sskorol.entities.YamlUser;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import static io.github.sskorol.data.TestDataReader.use;
package io.github.sskorol.testcases;
public class YamlDataSupplierTests {
@DataSupplier
public StreamEx<DockerConfiguration> getDockerConfiguration() {
return use(YamlReader.class).withTarget(DockerConfiguration.class).read();
}
@DataSupplier
public StreamEx<YamlUser> getUsers() {
return use(YamlReader.class).withTarget(YamlUser.class).read();
}
@DataSupplier
public StreamEx<TravisConfiguration> getTravisConfiguration() {
return use(YamlReader.class).withTarget(TravisConfiguration.class).read();
}
@DataSupplier | public StreamEx<MissingClient> getMissingClient() { |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/core/DataSupplierAspect.java | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ServiceLoaderUtils.java
// public static <T> List<T> load(final Class<T> type, final ClassLoader classLoader) {
// return Try.of(() -> StreamEx.of(ServiceLoader.load(type, classLoader).iterator()).toList())
// .getOrElseGet(ex -> emptyList());
// }
| import io.github.sskorol.model.DataSupplierMetaData;
import one.util.streamex.StreamEx;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.annotations.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Consumer;
import static io.github.sskorol.utils.ServiceLoaderUtils.load;
import static io.vavr.API.*; | package io.github.sskorol.core;
/**
* Key aspect for DataSupplier interception.
*/
@Aspect
public class DataSupplierAspect {
private static final List<DataSupplierInterceptor> DATA_SUPPLIERS = | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ServiceLoaderUtils.java
// public static <T> List<T> load(final Class<T> type, final ClassLoader classLoader) {
// return Try.of(() -> StreamEx.of(ServiceLoader.load(type, classLoader).iterator()).toList())
// .getOrElseGet(ex -> emptyList());
// }
// Path: src/main/java/io/github/sskorol/core/DataSupplierAspect.java
import io.github.sskorol.model.DataSupplierMetaData;
import one.util.streamex.StreamEx;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.annotations.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Consumer;
import static io.github.sskorol.utils.ServiceLoaderUtils.load;
import static io.vavr.API.*;
package io.github.sskorol.core;
/**
* Key aspect for DataSupplier interception.
*/
@Aspect
public class DataSupplierAspect {
private static final List<DataSupplierInterceptor> DATA_SUPPLIERS = | load(DataSupplierInterceptor.class, DataSupplierAspect.class.getClassLoader()); |
sskorol/test-data-supplier | src/main/java/io/github/sskorol/core/DataSupplierAspect.java | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ServiceLoaderUtils.java
// public static <T> List<T> load(final Class<T> type, final ClassLoader classLoader) {
// return Try.of(() -> StreamEx.of(ServiceLoader.load(type, classLoader).iterator()).toList())
// .getOrElseGet(ex -> emptyList());
// }
| import io.github.sskorol.model.DataSupplierMetaData;
import one.util.streamex.StreamEx;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.annotations.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Consumer;
import static io.github.sskorol.utils.ServiceLoaderUtils.load;
import static io.vavr.API.*; | package io.github.sskorol.core;
/**
* Key aspect for DataSupplier interception.
*/
@Aspect
public class DataSupplierAspect {
private static final List<DataSupplierInterceptor> DATA_SUPPLIERS =
load(DataSupplierInterceptor.class, DataSupplierAspect.class.getClassLoader());
private static final List<IAnnotationTransformerInterceptor> ANNOTATION_TRANSFORMERS =
load(IAnnotationTransformerInterceptor.class, DataSupplierAspect.class.getClassLoader());
@Before("execution(@org.testng.annotations.DataProvider * io.github.sskorol.core.DataProviderTransformer.*(..))")
public void beforeDataProviderCall(final JoinPoint joinPoint) {
DATA_SUPPLIERS.forEach(ds -> ds.beforeDataPreparation((ITestContext) joinPoint.getArgs()[0],
(ITestNGMethod) joinPoint.getArgs()[1]));
}
@After("execution(@org.testng.annotations.DataProvider * io.github.sskorol.core.DataProviderTransformer.*(..))")
public void afterDataProviderCall(final JoinPoint joinPoint) {
DATA_SUPPLIERS.forEach(ds -> ds.afterDataPreparation((ITestContext) joinPoint.getArgs()[0],
(ITestNGMethod) joinPoint.getArgs()[1]));
}
@Around("execution(* io.github.sskorol.core.DataProviderTransformer.getMetaData(..))") | // Path: src/main/java/io/github/sskorol/model/DataSupplierMetaData.java
// public class DataSupplierMetaData {
//
// @Getter
// private final List<Object[]> testData;
// private final boolean transpose;
// private final boolean flatMap;
// private final int[] indices;
// @Getter
// private final TestNGMethod testNGMethod;
//
// public DataSupplierMetaData(final ITestContext context, final ITestNGMethod testMethod) {
// this.testNGMethod = new TestNGMethod(context, testMethod);
// this.transpose = testNGMethod.getDataSupplierArg(DataSupplier::transpose, false);
// this.flatMap = testNGMethod.getDataSupplierArg(DataSupplier::flatMap, false);
// this.indices = testNGMethod.getDataSupplierArg(DataSupplier::indices, new int[0]);
// this.testData = transform();
// }
//
// private List<Object[]> transform() {
// var data = streamOf(obtainReturnValue()).toList();
// var indicesList = indicesList(data.size());
// var wrappedReturnValue = EntryStream.of(data).filterKeys(indicesList::contains).values();
//
// if (transpose) {
// return singletonList(flatMap
// ? wrappedReturnValue.flatMap(ReflectionUtils::streamOf).toArray()
// : wrappedReturnValue.toArray());
// }
//
// return wrappedReturnValue.map(ob -> flatMap ? streamOf(ob).toArray() : new Object[]{ob}).toList();
// }
//
// private Object obtainReturnValue() {
// return invokeDataSupplier(testNGMethod.getDataSupplierMetaData());
// }
//
// private List<Integer> indicesList(final int collectionSize) {
// return ofNullable(indices)
// .filter(indicesArray -> indicesArray.length > 0)
// .map(IntStreamEx::of)
// .orElseGet(() -> IntStreamEx.range(0, collectionSize))
// .boxed()
// .toList();
// }
// }
//
// Path: src/main/java/io/github/sskorol/utils/ServiceLoaderUtils.java
// public static <T> List<T> load(final Class<T> type, final ClassLoader classLoader) {
// return Try.of(() -> StreamEx.of(ServiceLoader.load(type, classLoader).iterator()).toList())
// .getOrElseGet(ex -> emptyList());
// }
// Path: src/main/java/io/github/sskorol/core/DataSupplierAspect.java
import io.github.sskorol.model.DataSupplierMetaData;
import one.util.streamex.StreamEx;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.annotations.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Consumer;
import static io.github.sskorol.utils.ServiceLoaderUtils.load;
import static io.vavr.API.*;
package io.github.sskorol.core;
/**
* Key aspect for DataSupplier interception.
*/
@Aspect
public class DataSupplierAspect {
private static final List<DataSupplierInterceptor> DATA_SUPPLIERS =
load(DataSupplierInterceptor.class, DataSupplierAspect.class.getClassLoader());
private static final List<IAnnotationTransformerInterceptor> ANNOTATION_TRANSFORMERS =
load(IAnnotationTransformerInterceptor.class, DataSupplierAspect.class.getClassLoader());
@Before("execution(@org.testng.annotations.DataProvider * io.github.sskorol.core.DataProviderTransformer.*(..))")
public void beforeDataProviderCall(final JoinPoint joinPoint) {
DATA_SUPPLIERS.forEach(ds -> ds.beforeDataPreparation((ITestContext) joinPoint.getArgs()[0],
(ITestNGMethod) joinPoint.getArgs()[1]));
}
@After("execution(@org.testng.annotations.DataProvider * io.github.sskorol.core.DataProviderTransformer.*(..))")
public void afterDataProviderCall(final JoinPoint joinPoint) {
DATA_SUPPLIERS.forEach(ds -> ds.afterDataPreparation((ITestContext) joinPoint.getArgs()[0],
(ITestNGMethod) joinPoint.getArgs()[1]));
}
@Around("execution(* io.github.sskorol.core.DataProviderTransformer.getMetaData(..))") | public DataSupplierMetaData onDataPreparation(final ProceedingJoinPoint joinPoint) throws Throwable { |
sskorol/test-data-supplier | src/test/java/io/github/sskorol/testcases/TypeMappingsTests.java | // Path: src/main/java/io/github/sskorol/model/TypeMappings.java
// @AllArgsConstructor
// public enum TypeMappings {
//
// COLLECTION(Collection.class, d -> StreamEx.of((Collection<?>) d)),
// MAP(Map.class, d -> EntryStream.of((Map<?, ?>) d).mapKeyValue(AbstractMap.SimpleEntry::new)),
// ENTRY(Map.Entry.class, d -> StreamEx.of(((Map.Entry) d).getKey(), ((Map.Entry) d).getValue())),
// OBJECT_ARRAY(Object[].class, d -> StreamEx.of((Object[]) d)),
// DOUBLE_ARRAY(double[].class, d -> DoubleStreamEx.of((double[]) d).boxed()),
// INT_ARRAY(int[].class, d -> IntStreamEx.of((int[]) d).boxed()),
// LONG_ARRAY(long[].class, d -> LongStreamEx.of((long[]) d).boxed()),
// STREAM(Stream.class, d -> StreamEx.of((Stream<?>) d)),
// TUPLE(Tuple.class, d -> StreamEx.of(((Tuple) d).toSeq().toJavaArray()));
//
// private final Class<?> typeClass;
// private final Function<Object, StreamEx<?>> mapper;
//
// public boolean isInstanceOf(final Object ob) {
// return ob != null && typeClass.isAssignableFrom(ob.getClass());
// }
//
// @SuppressWarnings("unchecked")
// public <T> StreamEx<T> streamOf(final T ob) {
// return (StreamEx<T>) mapper.apply(ob);
// }
// }
| import io.github.sskorol.model.TypeMappings;
import io.vavr.Tuple;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; | package io.github.sskorol.testcases;
public class TypeMappingsTests {
@Test
public void providedObjectsShouldMatchMappedInstances() { | // Path: src/main/java/io/github/sskorol/model/TypeMappings.java
// @AllArgsConstructor
// public enum TypeMappings {
//
// COLLECTION(Collection.class, d -> StreamEx.of((Collection<?>) d)),
// MAP(Map.class, d -> EntryStream.of((Map<?, ?>) d).mapKeyValue(AbstractMap.SimpleEntry::new)),
// ENTRY(Map.Entry.class, d -> StreamEx.of(((Map.Entry) d).getKey(), ((Map.Entry) d).getValue())),
// OBJECT_ARRAY(Object[].class, d -> StreamEx.of((Object[]) d)),
// DOUBLE_ARRAY(double[].class, d -> DoubleStreamEx.of((double[]) d).boxed()),
// INT_ARRAY(int[].class, d -> IntStreamEx.of((int[]) d).boxed()),
// LONG_ARRAY(long[].class, d -> LongStreamEx.of((long[]) d).boxed()),
// STREAM(Stream.class, d -> StreamEx.of((Stream<?>) d)),
// TUPLE(Tuple.class, d -> StreamEx.of(((Tuple) d).toSeq().toJavaArray()));
//
// private final Class<?> typeClass;
// private final Function<Object, StreamEx<?>> mapper;
//
// public boolean isInstanceOf(final Object ob) {
// return ob != null && typeClass.isAssignableFrom(ob.getClass());
// }
//
// @SuppressWarnings("unchecked")
// public <T> StreamEx<T> streamOf(final T ob) {
// return (StreamEx<T>) mapper.apply(ob);
// }
// }
// Path: src/test/java/io/github/sskorol/testcases/TypeMappingsTests.java
import io.github.sskorol.model.TypeMappings;
import io.vavr.Tuple;
import one.util.streamex.StreamEx;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
package io.github.sskorol.testcases;
public class TypeMappingsTests {
@Test
public void providedObjectsShouldMatchMappedInstances() { | assertThat(TypeMappings.COLLECTION.isInstanceOf(List.of("data1", "data2"))).as("Collection").isTrue(); |
orientechnologies/orientdb-gremlin | driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/traversal/step/sideeffect/OrientGraphStep.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OGremlinResult.java
// public class OGremlinResult {
//
// private OrientGraph graph;
// OResult inner;
//
// public OGremlinResult(OrientGraph graph, OResult inner) {
// this.graph = graph;
// this.inner = inner;
// }
//
// public <T> T getProperty(String name) {
// Object value = inner.getProperty(name);
// if (value instanceof Iterable) {
// Spliterator spliterator = ((Iterable) value).spliterator();
// value =
// StreamSupport.stream(spliterator, false)
// .map(
// (e) -> {
// if (e instanceof OResult) {
// return new OGremlinResult(this.graph, (OResult) e);
// } else {
// return e;
// }
// })
// .collect(Collectors.toList());
// }
// return (T) value;
// }
//
// public Optional<OrientVertex> getVertex() {
// return inner.getVertex().map((v) -> graph.elementFactory().wrapVertex(v));
// }
//
// public Optional<OrientEdge> getEdge() {
// return inner.getEdge().map((v) -> graph.elementFactory().wrapEdge(v));
// }
//
// public boolean isElement() {
// return inner.isElement();
// }
//
// public boolean isVertex() {
// return inner.isVertex();
// }
//
// public boolean isEdge() {
// return inner.isEdge();
// }
//
// public boolean isBlob() {
// return inner.isBlob();
// }
//
// public OResult getRawResult() {
// return inner;
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexManager;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Stream;
import org.apache.tinkerpop.gremlin.orientdb.*;
import org.apache.tinkerpop.gremlin.orientdb.executor.OGremlinResult;
import org.apache.tinkerpop.gremlin.process.traversal.Compare;
import org.apache.tinkerpop.gremlin.process.traversal.Contains;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.step.HasContainerHolder;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.DefaultCloseableIterator;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.util.function.TriFunction;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils; | package org.apache.tinkerpop.gremlin.orientdb.traversal.step.sideeffect;
public class OrientGraphStep<S, E extends Element> extends GraphStep<S, E>
implements HasContainerHolder {
private static final long serialVersionUID = 8141248670294067626L;
private final List<HasContainer> hasContainers = new ArrayList<>();
public OrientGraphStep(final GraphStep<S, E> originalGraphStep) {
super(
originalGraphStep.getTraversal(),
originalGraphStep.getReturnClass(),
originalGraphStep.isStartStep(),
originalGraphStep.getIds());
originalGraphStep.getLabels().forEach(this::addLabel);
this.setIteratorSupplier(() -> (Iterator<E>) (isVertexStep() ? this.vertices() : this.edges()));
}
public boolean isVertexStep() {
return Vertex.class.isAssignableFrom(this.returnClass);
}
private Iterator<? extends Vertex> vertices() {
return elements(
OGraph::vertices, OGraph::getIndexedVertices, OGraph::vertices, v -> v.getVertex().get());
}
private Iterator<? extends Edge> edges() {
return elements(
OGraph::edges, OGraph::getIndexedEdges, OGraph::edges, (e) -> e.getEdge().get());
}
/**
* Gets an iterator over those vertices/edges that have the specific IDs wanted, or those that
* have indexed properties with the wanted values, or failing that by just getting all of the
* vertices or edges.
*
* @param getElementsByIds Function that will return an iterator over all the vertices/edges in
* the graph that have the specific IDs
* @param getElementsByIndex Function that returns a stream of all the vertices/edges in the graph
* that have an indexed property with a specific value
* @param getAllElements Function that returns an iterator of all the vertices or all the edges
* (i.e. full scan)
* @return An iterator for all the vertices/edges for this step
*/
private <ElementType extends Element> Iterator<? extends ElementType> elements(
BiFunction<OGraph, Object[], Iterator<ElementType>> getElementsByIds,
TriFunction<OGraph, OIndex, Iterator<Object>, Stream<? extends ElementType>>
getElementsByIndex,
Function<OGraph, Iterator<ElementType>> getAllElements, | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OGremlinResult.java
// public class OGremlinResult {
//
// private OrientGraph graph;
// OResult inner;
//
// public OGremlinResult(OrientGraph graph, OResult inner) {
// this.graph = graph;
// this.inner = inner;
// }
//
// public <T> T getProperty(String name) {
// Object value = inner.getProperty(name);
// if (value instanceof Iterable) {
// Spliterator spliterator = ((Iterable) value).spliterator();
// value =
// StreamSupport.stream(spliterator, false)
// .map(
// (e) -> {
// if (e instanceof OResult) {
// return new OGremlinResult(this.graph, (OResult) e);
// } else {
// return e;
// }
// })
// .collect(Collectors.toList());
// }
// return (T) value;
// }
//
// public Optional<OrientVertex> getVertex() {
// return inner.getVertex().map((v) -> graph.elementFactory().wrapVertex(v));
// }
//
// public Optional<OrientEdge> getEdge() {
// return inner.getEdge().map((v) -> graph.elementFactory().wrapEdge(v));
// }
//
// public boolean isElement() {
// return inner.isElement();
// }
//
// public boolean isVertex() {
// return inner.isVertex();
// }
//
// public boolean isEdge() {
// return inner.isEdge();
// }
//
// public boolean isBlob() {
// return inner.isBlob();
// }
//
// public OResult getRawResult() {
// return inner;
// }
// }
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/traversal/step/sideeffect/OrientGraphStep.java
import com.google.common.annotations.VisibleForTesting;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexManager;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Stream;
import org.apache.tinkerpop.gremlin.orientdb.*;
import org.apache.tinkerpop.gremlin.orientdb.executor.OGremlinResult;
import org.apache.tinkerpop.gremlin.process.traversal.Compare;
import org.apache.tinkerpop.gremlin.process.traversal.Contains;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.step.HasContainerHolder;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.DefaultCloseableIterator;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.util.function.TriFunction;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
package org.apache.tinkerpop.gremlin.orientdb.traversal.step.sideeffect;
public class OrientGraphStep<S, E extends Element> extends GraphStep<S, E>
implements HasContainerHolder {
private static final long serialVersionUID = 8141248670294067626L;
private final List<HasContainer> hasContainers = new ArrayList<>();
public OrientGraphStep(final GraphStep<S, E> originalGraphStep) {
super(
originalGraphStep.getTraversal(),
originalGraphStep.getReturnClass(),
originalGraphStep.isStartStep(),
originalGraphStep.getIds());
originalGraphStep.getLabels().forEach(this::addLabel);
this.setIteratorSupplier(() -> (Iterator<E>) (isVertexStep() ? this.vertices() : this.edges()));
}
public boolean isVertexStep() {
return Vertex.class.isAssignableFrom(this.returnClass);
}
private Iterator<? extends Vertex> vertices() {
return elements(
OGraph::vertices, OGraph::getIndexedVertices, OGraph::vertices, v -> v.getVertex().get());
}
private Iterator<? extends Edge> edges() {
return elements(
OGraph::edges, OGraph::getIndexedEdges, OGraph::edges, (e) -> e.getEdge().get());
}
/**
* Gets an iterator over those vertices/edges that have the specific IDs wanted, or those that
* have indexed properties with the wanted values, or failing that by just getting all of the
* vertices or edges.
*
* @param getElementsByIds Function that will return an iterator over all the vertices/edges in
* the graph that have the specific IDs
* @param getElementsByIndex Function that returns a stream of all the vertices/edges in the graph
* that have an indexed property with a specific value
* @param getAllElements Function that returns an iterator of all the vertices or all the edges
* (i.e. full scan)
* @return An iterator for all the vertices/edges for this step
*/
private <ElementType extends Element> Iterator<? extends ElementType> elements(
BiFunction<OGraph, Object[], Iterator<ElementType>> getElementsByIds,
TriFunction<OGraph, OIndex, Iterator<Object>, Stream<? extends ElementType>>
getElementsByIndex,
Function<OGraph, Iterator<ElementType>> getAllElements, | Function<OGremlinResult, ElementType> getElement) { |
orientechnologies/orientdb-gremlin | driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientVertex.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/StreamUtils.java
// public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
// return asStream(sourceIterator, false);
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.apache.tinkerpop.gremlin.orientdb.StreamUtils.asStream;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory; | package org.apache.tinkerpop.gremlin.orientdb;
public final class OrientVertex extends OrientElement implements Vertex {
private static final List<String> INTERNAL_FIELDS = Arrays.asList("@rid", "@class");
public OrientVertex(final OGraph graph, final OVertex rawElement) {
super(graph, rawElement);
}
public OrientVertex(OGraph graph, OIdentifiable identifiable) {
this(
graph,
new ODocument(identifiable.getIdentity())
.asVertex()
.orElseThrow(
() ->
new IllegalArgumentException(
String.format("Cannot get a Vertex for identity %s", identifiable))));
}
public OrientVertex(OGraph graph, String label) {
this(graph, createRawElement(graph, label));
}
protected static OVertex createRawElement(OGraph graph, String label) {
graph.createVertexClass(label);
return graph.getRawDatabase().newVertex(label);
}
public Iterator<Vertex> vertices(final Direction direction, final String... labels) {
this.graph.tx().readWrite();
Stream<Vertex> vertexStream = | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/StreamUtils.java
// public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
// return asStream(sourceIterator, false);
// }
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientVertex.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.apache.tinkerpop.gremlin.orientdb.StreamUtils.asStream;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.record.impl.ODocument;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
package org.apache.tinkerpop.gremlin.orientdb;
public final class OrientVertex extends OrientElement implements Vertex {
private static final List<String> INTERNAL_FIELDS = Arrays.asList("@rid", "@class");
public OrientVertex(final OGraph graph, final OVertex rawElement) {
super(graph, rawElement);
}
public OrientVertex(OGraph graph, OIdentifiable identifiable) {
this(
graph,
new ODocument(identifiable.getIdentity())
.asVertex()
.orElseThrow(
() ->
new IllegalArgumentException(
String.format("Cannot get a Vertex for identity %s", identifiable))));
}
public OrientVertex(OGraph graph, String label) {
this(graph, createRawElement(graph, label));
}
protected static OVertex createRawElement(OGraph graph, String label) {
graph.createVertexClass(label);
return graph.getRawDatabase().newVertex(label);
}
public Iterator<Vertex> vertices(final Direction direction, final String... labels) {
this.graph.tx().readWrite();
Stream<Vertex> vertexStream = | asStream( |
orientechnologies/orientdb-gremlin | driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientFactory.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_PASS = "orient-pass";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_URL = "orient-url";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_USER = "orient-user";
| import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_PASS;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_URL;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_USER;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration; | package org.apache.tinkerpop.gremlin.orientdb;
/** OrientFactory is used to open a new OrientStandardGraph */
public class OrientFactory {
/**
* Opens a {@link OGraph} in-memory database
*
* @return OGraph database
*/
public static OrientStandardGraph open() {
return open("memory:orientdb-" + Math.random(), "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @return OGraph database
*/
public static OrientStandardGraph open(String url) {
return open(url, "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @param user username of a database user or a server user allowed to open the database
* @param password related to the specified username
* @return OGraph database
*/
public static OrientStandardGraph open(String url, String user, String password) {
BaseConfiguration configuration = new BaseConfiguration(); | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_PASS = "orient-pass";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_URL = "orient-url";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_USER = "orient-user";
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientFactory.java
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_PASS;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_URL;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_USER;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
package org.apache.tinkerpop.gremlin.orientdb;
/** OrientFactory is used to open a new OrientStandardGraph */
public class OrientFactory {
/**
* Opens a {@link OGraph} in-memory database
*
* @return OGraph database
*/
public static OrientStandardGraph open() {
return open("memory:orientdb-" + Math.random(), "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @return OGraph database
*/
public static OrientStandardGraph open(String url) {
return open(url, "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @param user username of a database user or a server user allowed to open the database
* @param password related to the specified username
* @return OGraph database
*/
public static OrientStandardGraph open(String url, String user, String password) {
BaseConfiguration configuration = new BaseConfiguration(); | configuration.setProperty(CONFIG_URL, url); |
orientechnologies/orientdb-gremlin | driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientFactory.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_PASS = "orient-pass";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_URL = "orient-url";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_USER = "orient-user";
| import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_PASS;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_URL;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_USER;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration; | package org.apache.tinkerpop.gremlin.orientdb;
/** OrientFactory is used to open a new OrientStandardGraph */
public class OrientFactory {
/**
* Opens a {@link OGraph} in-memory database
*
* @return OGraph database
*/
public static OrientStandardGraph open() {
return open("memory:orientdb-" + Math.random(), "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @return OGraph database
*/
public static OrientStandardGraph open(String url) {
return open(url, "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @param user username of a database user or a server user allowed to open the database
* @param password related to the specified username
* @return OGraph database
*/
public static OrientStandardGraph open(String url, String user, String password) {
BaseConfiguration configuration = new BaseConfiguration();
configuration.setProperty(CONFIG_URL, url); | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_PASS = "orient-pass";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_URL = "orient-url";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_USER = "orient-user";
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientFactory.java
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_PASS;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_URL;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_USER;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
package org.apache.tinkerpop.gremlin.orientdb;
/** OrientFactory is used to open a new OrientStandardGraph */
public class OrientFactory {
/**
* Opens a {@link OGraph} in-memory database
*
* @return OGraph database
*/
public static OrientStandardGraph open() {
return open("memory:orientdb-" + Math.random(), "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @return OGraph database
*/
public static OrientStandardGraph open(String url) {
return open(url, "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @param user username of a database user or a server user allowed to open the database
* @param password related to the specified username
* @return OGraph database
*/
public static OrientStandardGraph open(String url, String user, String password) {
BaseConfiguration configuration = new BaseConfiguration();
configuration.setProperty(CONFIG_URL, url); | configuration.setProperty(CONFIG_USER, user); |
orientechnologies/orientdb-gremlin | driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientFactory.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_PASS = "orient-pass";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_URL = "orient-url";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_USER = "orient-user";
| import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_PASS;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_URL;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_USER;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration; | package org.apache.tinkerpop.gremlin.orientdb;
/** OrientFactory is used to open a new OrientStandardGraph */
public class OrientFactory {
/**
* Opens a {@link OGraph} in-memory database
*
* @return OGraph database
*/
public static OrientStandardGraph open() {
return open("memory:orientdb-" + Math.random(), "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @return OGraph database
*/
public static OrientStandardGraph open(String url) {
return open(url, "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @param user username of a database user or a server user allowed to open the database
* @param password related to the specified username
* @return OGraph database
*/
public static OrientStandardGraph open(String url, String user, String password) {
BaseConfiguration configuration = new BaseConfiguration();
configuration.setProperty(CONFIG_URL, url);
configuration.setProperty(CONFIG_USER, user); | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_PASS = "orient-pass";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_URL = "orient-url";
//
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_USER = "orient-user";
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientFactory.java
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_PASS;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_URL;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_USER;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
package org.apache.tinkerpop.gremlin.orientdb;
/** OrientFactory is used to open a new OrientStandardGraph */
public class OrientFactory {
/**
* Opens a {@link OGraph} in-memory database
*
* @return OGraph database
*/
public static OrientStandardGraph open() {
return open("memory:orientdb-" + Math.random(), "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @return OGraph database
*/
public static OrientStandardGraph open(String url) {
return open(url, "admin", "admin");
}
/**
* Opens a {@link OGraph}
*
* @param url URL for the specific database
* @param user username of a database user or a server user allowed to open the database
* @param password related to the specified username
* @return OGraph database
*/
public static OrientStandardGraph open(String url, String user, String password) {
BaseConfiguration configuration = new BaseConfiguration();
configuration.setProperty(CONFIG_URL, url);
configuration.setProperty(CONFIG_USER, user); | configuration.setProperty(CONFIG_PASS, password); |
orientechnologies/orientdb-gremlin | driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/OrientIoRegistryTest.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/io/OrientIoRegistry.java
// @SuppressWarnings("serial")
// public class OrientIoRegistry extends AbstractIoRegistry {
//
// public static final String CLUSTER_ID = "clusterId";
// public static final String CLUSTER_POSITION = "clusterPosition";
//
// private static final OrientIoRegistry INSTANCE = new OrientIoRegistry();
//
// private OrientIoRegistry() {
// register(GryoIo.class, ORecordId.class, new ORecordIdGyroSerializer());
// register(GryoIo.class, ORidBag.class, new ORidBagGyroSerializer());
// register(GryoIo.class, OTrackedMap.class, new OrientMapSerializer());
//
// register(GraphSONIo.class, ORecordId.class, OrientGraphSONV3.INSTANCE);
// }
//
// public static OrientIoRegistry instance() {
// return INSTANCE;
// }
//
// public static OrientIoRegistry getInstance() {
// return INSTANCE;
// }
//
// public static ORecordId newORecordId(final Object obj) {
// if (obj == null) {
// return null;
// }
//
// if (obj instanceof ORecordId) {
// return (ORecordId) obj;
// }
//
// if (obj instanceof Map) {
// @SuppressWarnings({"unchecked", "rawtypes"})
// final Map<String, Number> map = (Map) obj;
// return new ORecordId(map.get(CLUSTER_ID).intValue(), map.get(CLUSTER_POSITION).longValue());
// }
// throw new IllegalArgumentException(
// "Unable to convert unknow type to ORecordId " + obj.getClass());
// }
//
// public static boolean isORecord(final Object result) {
// if (!(result instanceof Map)) {
// return false;
// }
//
// @SuppressWarnings("unchecked")
// final Map<String, Number> map = (Map<String, Number>) result;
// return map.containsKey(CLUSTER_ID) && map.containsKey(CLUSTER_POSITION);
// }
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import java.io.StringWriter;
import java.util.List;
import org.apache.tinkerpop.gremlin.orientdb.io.OrientIoRegistry;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONIo;
import org.apache.tinkerpop.shaded.jackson.databind.Module;
import org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper;
import org.javatuples.Pair;
import org.junit.Before;
import org.junit.Test; | package org.apache.tinkerpop.gremlin.orientdb;
public class OrientIoRegistryTest {
private ObjectMapper objectMapper;
@Before
public void setup() {
@SuppressWarnings("rawtypes") | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/io/OrientIoRegistry.java
// @SuppressWarnings("serial")
// public class OrientIoRegistry extends AbstractIoRegistry {
//
// public static final String CLUSTER_ID = "clusterId";
// public static final String CLUSTER_POSITION = "clusterPosition";
//
// private static final OrientIoRegistry INSTANCE = new OrientIoRegistry();
//
// private OrientIoRegistry() {
// register(GryoIo.class, ORecordId.class, new ORecordIdGyroSerializer());
// register(GryoIo.class, ORidBag.class, new ORidBagGyroSerializer());
// register(GryoIo.class, OTrackedMap.class, new OrientMapSerializer());
//
// register(GraphSONIo.class, ORecordId.class, OrientGraphSONV3.INSTANCE);
// }
//
// public static OrientIoRegistry instance() {
// return INSTANCE;
// }
//
// public static OrientIoRegistry getInstance() {
// return INSTANCE;
// }
//
// public static ORecordId newORecordId(final Object obj) {
// if (obj == null) {
// return null;
// }
//
// if (obj instanceof ORecordId) {
// return (ORecordId) obj;
// }
//
// if (obj instanceof Map) {
// @SuppressWarnings({"unchecked", "rawtypes"})
// final Map<String, Number> map = (Map) obj;
// return new ORecordId(map.get(CLUSTER_ID).intValue(), map.get(CLUSTER_POSITION).longValue());
// }
// throw new IllegalArgumentException(
// "Unable to convert unknow type to ORecordId " + obj.getClass());
// }
//
// public static boolean isORecord(final Object result) {
// if (!(result instanceof Map)) {
// return false;
// }
//
// @SuppressWarnings("unchecked")
// final Map<String, Number> map = (Map<String, Number>) result;
// return map.containsKey(CLUSTER_ID) && map.containsKey(CLUSTER_POSITION);
// }
// }
// Path: driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/OrientIoRegistryTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import java.io.StringWriter;
import java.util.List;
import org.apache.tinkerpop.gremlin.orientdb.io.OrientIoRegistry;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONIo;
import org.apache.tinkerpop.shaded.jackson.databind.Module;
import org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper;
import org.javatuples.Pair;
import org.junit.Before;
import org.junit.Test;
package org.apache.tinkerpop.gremlin.orientdb;
public class OrientIoRegistryTest {
private ObjectMapper objectMapper;
@Before
public void setup() {
@SuppressWarnings("rawtypes") | List<Pair<Class, Object>> modules = OrientIoRegistry.getInstance().find(GraphSONIo.class); |
orientechnologies/orientdb-gremlin | driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraphCountStrategyTest.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/traversal/step/map/OrientClassCountStep.java
// public class OrientClassCountStep<S> extends AbstractStep<S, Long> {
//
// private final boolean vertexStep;
// private List<String> klasses;
//
// protected boolean done = false;
//
// public OrientClassCountStep(Traversal.Admin traversal, List<String> klasses, boolean vertexStep) {
// super(traversal);
// this.klasses = klasses;
// this.vertexStep = vertexStep;
// }
//
// @Override
// protected Traverser.Admin<Long> processNextStart() throws NoSuchElementException {
// if (!done) {
// done = true;
// ODatabaseDocument db = getDatabase();
// Long v =
// klasses.stream()
// .filter(this::filterClass)
// .mapToLong((klass) -> db.countClass(klass))
// .reduce(0, (a, b) -> a + b);
// return this.traversal.getTraverserGenerator().generate(v, (Step) this, 1L);
// } else {
// throw FastNoSuchElementException.instance();
// }
// }
//
// private ODatabaseDocument getDatabase() {
// OGraph graph = (OGraph) this.traversal.getGraph().get();
// return graph.getRawDatabase();
// }
//
// private boolean filterClass(String klass) {
//
// ODatabaseDocument database = getDatabase();
// OSchema schema = database.getMetadata().getSchema();
// OClass schemaClass = schema.getClass(klass);
//
// if (vertexStep) {
// return schemaClass.isSubClassOf("V");
// } else {
// return schemaClass.isSubClassOf("E");
// }
// }
//
// public List<String> getKlasses() {
// return klasses;
// }
// }
| import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.apache.tinkerpop.gremlin.orientdb.traversal.step.map.OrientClassCountStep;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Assert;
import org.junit.Test; | package org.apache.tinkerpop.gremlin.orientdb;
public class OrientGraphCountStrategyTest {
@Test
public void shouldUseGlobalCountStepWithV() {
OrientGraph graph = OrientGraph.open();
try {
GraphTraversalSource traversal = graph.traversal();
GraphTraversal.Admin<Vertex, Long> admin = traversal.V().count().asAdmin();
admin.applyStrategies();
Step<Vertex, ?> startStep = admin.getStartStep(); | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/traversal/step/map/OrientClassCountStep.java
// public class OrientClassCountStep<S> extends AbstractStep<S, Long> {
//
// private final boolean vertexStep;
// private List<String> klasses;
//
// protected boolean done = false;
//
// public OrientClassCountStep(Traversal.Admin traversal, List<String> klasses, boolean vertexStep) {
// super(traversal);
// this.klasses = klasses;
// this.vertexStep = vertexStep;
// }
//
// @Override
// protected Traverser.Admin<Long> processNextStart() throws NoSuchElementException {
// if (!done) {
// done = true;
// ODatabaseDocument db = getDatabase();
// Long v =
// klasses.stream()
// .filter(this::filterClass)
// .mapToLong((klass) -> db.countClass(klass))
// .reduce(0, (a, b) -> a + b);
// return this.traversal.getTraverserGenerator().generate(v, (Step) this, 1L);
// } else {
// throw FastNoSuchElementException.instance();
// }
// }
//
// private ODatabaseDocument getDatabase() {
// OGraph graph = (OGraph) this.traversal.getGraph().get();
// return graph.getRawDatabase();
// }
//
// private boolean filterClass(String klass) {
//
// ODatabaseDocument database = getDatabase();
// OSchema schema = database.getMetadata().getSchema();
// OClass schemaClass = schema.getClass(klass);
//
// if (vertexStep) {
// return schemaClass.isSubClassOf("V");
// } else {
// return schemaClass.isSubClassOf("E");
// }
// }
//
// public List<String> getKlasses() {
// return klasses;
// }
// }
// Path: driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraphCountStrategyTest.java
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.apache.tinkerpop.gremlin.orientdb.traversal.step.map.OrientClassCountStep;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Assert;
import org.junit.Test;
package org.apache.tinkerpop.gremlin.orientdb;
public class OrientGraphCountStrategyTest {
@Test
public void shouldUseGlobalCountStepWithV() {
OrientGraph graph = OrientGraph.open();
try {
GraphTraversalSource traversal = graph.traversal();
GraphTraversal.Admin<Vertex, Long> admin = traversal.V().count().asAdmin();
admin.applyStrategies();
Step<Vertex, ?> startStep = admin.getStartStep(); | assertEquals(OrientClassCountStep.class, startStep.getClass()); |
orientechnologies/orientdb-gremlin | driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/gremlintest/OrientGraphTxProvider.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_TRANSACTIONAL = "orient-transactional";
| import static java.util.Arrays.asList;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_TRANSACTIONAL;
import java.util.Map;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.structure.GraphTest;
import org.apache.tinkerpop.gremlin.structure.TransactionTest;
import org.apache.tinkerpop.gremlin.structure.VertexTest; | package org.apache.tinkerpop.gremlin.orientdb.gremlintest;
public class OrientGraphTxProvider extends OrientGraphProvider {
static {
IGNORED_TESTS.put(
TransactionTest.class,
asList(
"shouldExecuteWithCompetingThreads",
"shouldAllowReferenceOfEdgeIdOutsideOfOriginalThreadManual",
"shouldAllowReferenceOfVertexIdOutsideOfOriginalThreadManual",
"shouldSupportTransactionIsolationCommitCheck",
"shouldNotShareTransactionReadWriteConsumersAcrossThreads",
"shouldNotShareTransactionCloseConsumersAcrossThreads",
"shouldNotifyTransactionListenersInSameThreadOnlyOnCommitSuccess",
"shouldNotifyTransactionListenersInSameThreadOnlyOnRollbackSuccess"));
IGNORED_TESTS.put(GraphTest.class, asList("shouldRemoveVertices"));
IGNORED_TESTS.put(
VertexTest.BasicVertexTest.class, asList("shouldNotGetConcurrentModificationException"));
}
@Override
public Map<String, Object> getBaseConfiguration(
String graphName,
Class<?> test,
String testMethodName,
LoadGraphWith.GraphData loadGraphWith) {
Map<String, Object> baseConfiguration =
super.getBaseConfiguration(graphName, test, testMethodName, loadGraphWith); | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java
// public static final String CONFIG_TRANSACTIONAL = "orient-transactional";
// Path: driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/gremlintest/OrientGraphTxProvider.java
import static java.util.Arrays.asList;
import static org.apache.tinkerpop.gremlin.orientdb.OrientGraph.CONFIG_TRANSACTIONAL;
import java.util.Map;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.structure.GraphTest;
import org.apache.tinkerpop.gremlin.structure.TransactionTest;
import org.apache.tinkerpop.gremlin.structure.VertexTest;
package org.apache.tinkerpop.gremlin.orientdb.gremlintest;
public class OrientGraphTxProvider extends OrientGraphProvider {
static {
IGNORED_TESTS.put(
TransactionTest.class,
asList(
"shouldExecuteWithCompetingThreads",
"shouldAllowReferenceOfEdgeIdOutsideOfOriginalThreadManual",
"shouldAllowReferenceOfVertexIdOutsideOfOriginalThreadManual",
"shouldSupportTransactionIsolationCommitCheck",
"shouldNotShareTransactionReadWriteConsumersAcrossThreads",
"shouldNotShareTransactionCloseConsumersAcrossThreads",
"shouldNotifyTransactionListenersInSameThreadOnlyOnCommitSuccess",
"shouldNotifyTransactionListenersInSameThreadOnlyOnRollbackSuccess"));
IGNORED_TESTS.put(GraphTest.class, asList("shouldRemoveVertices"));
IGNORED_TESTS.put(
VertexTest.BasicVertexTest.class, asList("shouldNotGetConcurrentModificationException"));
}
@Override
public Map<String, Object> getBaseConfiguration(
String graphName,
Class<?> test,
String testMethodName,
LoadGraphWith.GraphData loadGraphWith) {
Map<String, Object> baseConfiguration =
super.getBaseConfiguration(graphName, test, testMethodName, loadGraphWith); | baseConfiguration.put(CONFIG_TRANSACTIONAL, true); |
orientechnologies/orientdb-gremlin | driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraphQuery.java | // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OGremlinResultSet.java
// public class OGremlinResultSet implements Iterable<OGremlinResult>, AutoCloseable {
//
// private OrientGraph graph;
// private OResultSet inner;
//
// public OGremlinResultSet(OrientGraph graph, OResultSet inner) {
// this.graph = graph;
// this.inner = inner;
// }
//
// @Override
// public void close() {
// inner.close();
// }
//
// @Override
// public Iterator<OGremlinResult> iterator() {
// return new Iterator<OGremlinResult>() {
// @Override
// public boolean hasNext() {
// return inner.hasNext();
// }
//
// @Override
// public OGremlinResult next() {
// OResult next = inner.next();
// return new OGremlinResult(graph, next);
// }
// };
// }
//
// public Stream<OGremlinResult> stream() {
// return inner.stream().map((result) -> new OGremlinResult(graph, result));
// }
//
// public OResultSet getRawResultSet() {
// return inner;
// }
// }
| import com.orientechnologies.orient.core.sql.executor.FetchFromIndexStep;
import com.orientechnologies.orient.core.sql.executor.GlobalLetQueryStep;
import com.orientechnologies.orient.core.sql.executor.OExecutionPlan;
import java.util.Map;
import java.util.Optional;
import org.apache.tinkerpop.gremlin.orientdb.executor.OGremlinResultSet; | package org.apache.tinkerpop.gremlin.orientdb;
public class OrientGraphQuery implements OrientGraphBaseQuery {
protected final Map<String, Object> params;
protected final String query;
private final Integer target;
public OrientGraphQuery(String query, Map<String, Object> params, Integer target) {
this.query = query;
this.params = params;
this.target = target;
}
public String getQuery() {
return query;
}
public Map<String, Object> getParams() {
return params;
}
| // Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OGremlinResultSet.java
// public class OGremlinResultSet implements Iterable<OGremlinResult>, AutoCloseable {
//
// private OrientGraph graph;
// private OResultSet inner;
//
// public OGremlinResultSet(OrientGraph graph, OResultSet inner) {
// this.graph = graph;
// this.inner = inner;
// }
//
// @Override
// public void close() {
// inner.close();
// }
//
// @Override
// public Iterator<OGremlinResult> iterator() {
// return new Iterator<OGremlinResult>() {
// @Override
// public boolean hasNext() {
// return inner.hasNext();
// }
//
// @Override
// public OGremlinResult next() {
// OResult next = inner.next();
// return new OGremlinResult(graph, next);
// }
// };
// }
//
// public Stream<OGremlinResult> stream() {
// return inner.stream().map((result) -> new OGremlinResult(graph, result));
// }
//
// public OResultSet getRawResultSet() {
// return inner;
// }
// }
// Path: driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraphQuery.java
import com.orientechnologies.orient.core.sql.executor.FetchFromIndexStep;
import com.orientechnologies.orient.core.sql.executor.GlobalLetQueryStep;
import com.orientechnologies.orient.core.sql.executor.OExecutionPlan;
import java.util.Map;
import java.util.Optional;
import org.apache.tinkerpop.gremlin.orientdb.executor.OGremlinResultSet;
package org.apache.tinkerpop.gremlin.orientdb;
public class OrientGraphQuery implements OrientGraphBaseQuery {
protected final Map<String, Object> params;
protected final String query;
private final Integer target;
public OrientGraphQuery(String query, Map<String, Object> params, Integer target) {
this.query = query;
this.params = params;
this.target = target;
}
public String getQuery() {
return query;
}
public Map<String, Object> getParams() {
return params;
}
| public OGremlinResultSet execute(OGraph graph) { |
pkaq/smart-framework | src/main/java/org/smart4j/framework/mvc/impl/DefaultHandlerExceptionResolver.java | // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthcException.java
// public class AuthcException extends RuntimeException {
//
// public AuthcException() {
// super();
// }
//
// public AuthcException(String message) {
// super(message);
// }
//
// public AuthcException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthcException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthzException.java
// public class AuthzException extends RuntimeException {
//
// public AuthzException() {
// super();
// }
//
// public AuthzException(String message) {
// super(message);
// }
//
// public AuthzException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthzException(Throwable cause) {
// super(cause);
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.mvc.HandlerExceptionResolver;
import org.smart4j.framework.mvc.fault.AuthcException;
import org.smart4j.framework.mvc.fault.AuthzException;
import org.smart4j.framework.util.WebUtil; | package org.smart4j.framework.mvc.impl;
/**
* 默认 Handler 异常解析器
*
* @author huangyong
* @since 2.3
*/
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerExceptionResolver.class);
@Override
public void resolveHandlerException(HttpServletRequest request, HttpServletResponse response, Exception e) {
// 判断异常原因
Throwable cause = e.getCause();
if (cause == null) {
logger.error(e.getMessage(), e);
return;
} | // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthcException.java
// public class AuthcException extends RuntimeException {
//
// public AuthcException() {
// super();
// }
//
// public AuthcException(String message) {
// super(message);
// }
//
// public AuthcException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthcException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthzException.java
// public class AuthzException extends RuntimeException {
//
// public AuthzException() {
// super();
// }
//
// public AuthzException(String message) {
// super(message);
// }
//
// public AuthzException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthzException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/org/smart4j/framework/mvc/impl/DefaultHandlerExceptionResolver.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.mvc.HandlerExceptionResolver;
import org.smart4j.framework.mvc.fault.AuthcException;
import org.smart4j.framework.mvc.fault.AuthzException;
import org.smart4j.framework.util.WebUtil;
package org.smart4j.framework.mvc.impl;
/**
* 默认 Handler 异常解析器
*
* @author huangyong
* @since 2.3
*/
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerExceptionResolver.class);
@Override
public void resolveHandlerException(HttpServletRequest request, HttpServletResponse response, Exception e) {
// 判断异常原因
Throwable cause = e.getCause();
if (cause == null) {
logger.error(e.getMessage(), e);
return;
} | if (cause instanceof AuthcException) { |
pkaq/smart-framework | src/main/java/org/smart4j/framework/mvc/impl/DefaultHandlerExceptionResolver.java | // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthcException.java
// public class AuthcException extends RuntimeException {
//
// public AuthcException() {
// super();
// }
//
// public AuthcException(String message) {
// super(message);
// }
//
// public AuthcException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthcException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthzException.java
// public class AuthzException extends RuntimeException {
//
// public AuthzException() {
// super();
// }
//
// public AuthzException(String message) {
// super(message);
// }
//
// public AuthzException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthzException(Throwable cause) {
// super(cause);
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.mvc.HandlerExceptionResolver;
import org.smart4j.framework.mvc.fault.AuthcException;
import org.smart4j.framework.mvc.fault.AuthzException;
import org.smart4j.framework.util.WebUtil; | package org.smart4j.framework.mvc.impl;
/**
* 默认 Handler 异常解析器
*
* @author huangyong
* @since 2.3
*/
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerExceptionResolver.class);
@Override
public void resolveHandlerException(HttpServletRequest request, HttpServletResponse response, Exception e) {
// 判断异常原因
Throwable cause = e.getCause();
if (cause == null) {
logger.error(e.getMessage(), e);
return;
}
if (cause instanceof AuthcException) {
// 分两种情况进行处理
if (WebUtil.isAJAX(request)) {
// 跳转到 403 页面
WebUtil.sendError(HttpServletResponse.SC_FORBIDDEN, "", response);
} else {
// 重定向到首页 | // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthcException.java
// public class AuthcException extends RuntimeException {
//
// public AuthcException() {
// super();
// }
//
// public AuthcException(String message) {
// super(message);
// }
//
// public AuthcException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthcException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthzException.java
// public class AuthzException extends RuntimeException {
//
// public AuthzException() {
// super();
// }
//
// public AuthzException(String message) {
// super(message);
// }
//
// public AuthzException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthzException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/org/smart4j/framework/mvc/impl/DefaultHandlerExceptionResolver.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.mvc.HandlerExceptionResolver;
import org.smart4j.framework.mvc.fault.AuthcException;
import org.smart4j.framework.mvc.fault.AuthzException;
import org.smart4j.framework.util.WebUtil;
package org.smart4j.framework.mvc.impl;
/**
* 默认 Handler 异常解析器
*
* @author huangyong
* @since 2.3
*/
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerExceptionResolver.class);
@Override
public void resolveHandlerException(HttpServletRequest request, HttpServletResponse response, Exception e) {
// 判断异常原因
Throwable cause = e.getCause();
if (cause == null) {
logger.error(e.getMessage(), e);
return;
}
if (cause instanceof AuthcException) {
// 分两种情况进行处理
if (WebUtil.isAJAX(request)) {
// 跳转到 403 页面
WebUtil.sendError(HttpServletResponse.SC_FORBIDDEN, "", response);
} else {
// 重定向到首页 | WebUtil.redirectRequest(FrameworkConstant.HOME_PAGE, request, response); |
pkaq/smart-framework | src/main/java/org/smart4j/framework/mvc/impl/DefaultHandlerExceptionResolver.java | // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthcException.java
// public class AuthcException extends RuntimeException {
//
// public AuthcException() {
// super();
// }
//
// public AuthcException(String message) {
// super(message);
// }
//
// public AuthcException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthcException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthzException.java
// public class AuthzException extends RuntimeException {
//
// public AuthzException() {
// super();
// }
//
// public AuthzException(String message) {
// super(message);
// }
//
// public AuthzException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthzException(Throwable cause) {
// super(cause);
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.mvc.HandlerExceptionResolver;
import org.smart4j.framework.mvc.fault.AuthcException;
import org.smart4j.framework.mvc.fault.AuthzException;
import org.smart4j.framework.util.WebUtil; | package org.smart4j.framework.mvc.impl;
/**
* 默认 Handler 异常解析器
*
* @author huangyong
* @since 2.3
*/
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerExceptionResolver.class);
@Override
public void resolveHandlerException(HttpServletRequest request, HttpServletResponse response, Exception e) {
// 判断异常原因
Throwable cause = e.getCause();
if (cause == null) {
logger.error(e.getMessage(), e);
return;
}
if (cause instanceof AuthcException) {
// 分两种情况进行处理
if (WebUtil.isAJAX(request)) {
// 跳转到 403 页面
WebUtil.sendError(HttpServletResponse.SC_FORBIDDEN, "", response);
} else {
// 重定向到首页
WebUtil.redirectRequest(FrameworkConstant.HOME_PAGE, request, response);
} | // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthcException.java
// public class AuthcException extends RuntimeException {
//
// public AuthcException() {
// super();
// }
//
// public AuthcException(String message) {
// super(message);
// }
//
// public AuthcException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthcException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/smart4j/framework/mvc/fault/AuthzException.java
// public class AuthzException extends RuntimeException {
//
// public AuthzException() {
// super();
// }
//
// public AuthzException(String message) {
// super(message);
// }
//
// public AuthzException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AuthzException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/org/smart4j/framework/mvc/impl/DefaultHandlerExceptionResolver.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.mvc.HandlerExceptionResolver;
import org.smart4j.framework.mvc.fault.AuthcException;
import org.smart4j.framework.mvc.fault.AuthzException;
import org.smart4j.framework.util.WebUtil;
package org.smart4j.framework.mvc.impl;
/**
* 默认 Handler 异常解析器
*
* @author huangyong
* @since 2.3
*/
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerExceptionResolver.class);
@Override
public void resolveHandlerException(HttpServletRequest request, HttpServletResponse response, Exception e) {
// 判断异常原因
Throwable cause = e.getCause();
if (cause == null) {
logger.error(e.getMessage(), e);
return;
}
if (cause instanceof AuthcException) {
// 分两种情况进行处理
if (WebUtil.isAJAX(request)) {
// 跳转到 403 页面
WebUtil.sendError(HttpServletResponse.SC_FORBIDDEN, "", response);
} else {
// 重定向到首页
WebUtil.redirectRequest(FrameworkConstant.HOME_PAGE, request, response);
} | } else if (cause instanceof AuthzException) { |
pkaq/smart-framework | src/main/java/org/smart4j/framework/ioc/BeanHelper.java | // Path: src/main/java/org/smart4j/framework/core/fault/InitializationError.java
// public class InitializationError extends Error {
//
// public InitializationError() {
// super();
// }
//
// public InitializationError(String message) {
// super(message);
// }
//
// public InitializationError(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InitializationError(Throwable cause) {
// super(cause);
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.smart4j.framework.aop.annotation.Aspect;
import org.smart4j.framework.core.ClassHelper;
import org.smart4j.framework.core.fault.InitializationError;
import org.smart4j.framework.ioc.annotation.Bean;
import org.smart4j.framework.mvc.annotation.Action;
import org.smart4j.framework.tx.annotation.Service; | package org.smart4j.framework.ioc;
/**
* 初始化相关 Bean 类
*
* @author huangyong
* @since 1.0
*/
public class BeanHelper {
/**
* Bean Map(Bean 类 => Bean 实例)
*/
private static final Map<Class<?>, Object> beanMap = new HashMap<Class<?>, Object>();
static {
try {
// 获取应用包路径下所有的类
List<Class<?>> classList = ClassHelper.getClassList();
for (Class<?> cls : classList) {
// 处理带有 Bean/Service/Action/Aspect 注解的类
if (cls.isAnnotationPresent(Bean.class) ||
cls.isAnnotationPresent(Service.class) ||
cls.isAnnotationPresent(Action.class) ||
cls.isAnnotationPresent(Aspect.class)) {
// 创建 Bean 实例
Object beanInstance = cls.newInstance();
// 将 Bean 实例放入 Bean Map 中(键为 Bean 类,值为 Bean 实例)
beanMap.put(cls, beanInstance);
}
}
} catch (Exception e) { | // Path: src/main/java/org/smart4j/framework/core/fault/InitializationError.java
// public class InitializationError extends Error {
//
// public InitializationError() {
// super();
// }
//
// public InitializationError(String message) {
// super(message);
// }
//
// public InitializationError(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InitializationError(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/org/smart4j/framework/ioc/BeanHelper.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.smart4j.framework.aop.annotation.Aspect;
import org.smart4j.framework.core.ClassHelper;
import org.smart4j.framework.core.fault.InitializationError;
import org.smart4j.framework.ioc.annotation.Bean;
import org.smart4j.framework.mvc.annotation.Action;
import org.smart4j.framework.tx.annotation.Service;
package org.smart4j.framework.ioc;
/**
* 初始化相关 Bean 类
*
* @author huangyong
* @since 1.0
*/
public class BeanHelper {
/**
* Bean Map(Bean 类 => Bean 实例)
*/
private static final Map<Class<?>, Object> beanMap = new HashMap<Class<?>, Object>();
static {
try {
// 获取应用包路径下所有的类
List<Class<?>> classList = ClassHelper.getClassList();
for (Class<?> cls : classList) {
// 处理带有 Bean/Service/Action/Aspect 注解的类
if (cls.isAnnotationPresent(Bean.class) ||
cls.isAnnotationPresent(Service.class) ||
cls.isAnnotationPresent(Action.class) ||
cls.isAnnotationPresent(Aspect.class)) {
// 创建 Bean 实例
Object beanInstance = cls.newInstance();
// 将 Bean 实例放入 Bean Map 中(键为 Bean 类,值为 Bean 实例)
beanMap.put(cls, beanInstance);
}
}
} catch (Exception e) { | throw new InitializationError("初始化 BeanHelper 出错!", e); |
pkaq/smart-framework | src/main/java/org/smart4j/framework/mvc/DispatcherServlet.java | // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/InstanceFactory.java
// public class InstanceFactory {
//
// /**
// * 用于缓存对应的实例
// */
// private static final Map<String, Object> cache = new ConcurrentHashMap<String, Object>();
//
// /**
// * ClassScanner
// */
// private static final String CLASS_SCANNER = "smart.framework.custom.class_scanner";
//
// /**
// * DataSourceFactory
// */
// private static final String DS_FACTORY = "smart.framework.custom.ds_factory";
//
// /**
// * DataAccessor
// */
// private static final String DATA_ACCESSOR = "smart.framework.custom.data_accessor";
//
// /**
// * HandlerMapping
// */
// private static final String HANDLER_MAPPING = "smart.framework.custom.handler_mapping";
//
// /**
// * HandlerInvoker
// */
// private static final String HANDLER_INVOKER = "smart.framework.custom.handler_invoker";
//
// /**
// * HandlerExceptionResolver
// */
// private static final String HANDLER_EXCEPTION_RESOLVER = "smart.framework.custom.handler_exception_resolver";
//
// /**
// * ViewResolver
// */
// private static final String VIEW_RESOLVER = "smart.framework.custom.view_resolver";
//
// /**
// * 获取 ClassScanner
// */
// public static ClassScanner getClassScanner() {
// return getInstance(CLASS_SCANNER, DefaultClassScanner.class);
// }
//
// /**
// * 获取 DataSourceFactory
// */
// public static DataSourceFactory getDataSourceFactory() {
// return getInstance(DS_FACTORY, DefaultDataSourceFactory.class);
// }
//
// /**
// * 获取 DataAccessor
// */
// public static DataAccessor getDataAccessor() {
// return getInstance(DATA_ACCESSOR, DefaultDataAccessor.class);
// }
//
// /**
// * 获取 HandlerMapping
// */
// public static HandlerMapping getHandlerMapping() {
// return getInstance(HANDLER_MAPPING, DefaultHandlerMapping.class);
// }
//
// /**
// * 获取 HandlerInvoker
// */
// public static HandlerInvoker getHandlerInvoker() {
// return getInstance(HANDLER_INVOKER, DefaultHandlerInvoker.class);
// }
//
// /**
// * 获取 HandlerExceptionResolver
// */
// public static HandlerExceptionResolver getHandlerExceptionResolver() {
// return getInstance(HANDLER_EXCEPTION_RESOLVER, DefaultHandlerExceptionResolver.class);
// }
//
// /**
// * 获取 ViewResolver
// */
// public static ViewResolver getViewResolver() {
// return getInstance(VIEW_RESOLVER, DefaultViewResolver.class);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getInstance(String cacheKey, Class<T> defaultImplClass) {
// // 若缓存中存在对应的实例,则返回该实例
// if (cache.containsKey(cacheKey)) {
// return (T) cache.get(cacheKey);
// }
// // 从配置文件中获取相应的接口实现类配置
// String implClassName = ConfigHelper.getString(cacheKey);
// // 若实现类配置不存在,则使用默认实现类
// if (StringUtil.isEmpty(implClassName)) {
// implClassName = defaultImplClass.getName();
// }
// // 通过反射创建该实现类对应的实例
// T instance = ObjectUtil.newInstance(implClassName);
// // 若该实例不为空,则将其放入缓存
// if (instance != null) {
// cache.put(cacheKey, instance);
// }
// // 返回该实例
// return instance;
// }
// }
| import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.InstanceFactory;
import org.smart4j.framework.util.WebUtil; | package org.smart4j.framework.mvc;
/**
* 前端控制器
*
* @author huangyong
* @since 1.0
*/
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(DispatcherServlet.class);
| // Path: src/main/java/org/smart4j/framework/FrameworkConstant.java
// public interface FrameworkConstant {
//
// String UTF_8 = "UTF-8";
//
// String CONFIG_PROPS = "smart.properties";
// String SQL_PROPS = "smart-sql.properties";
//
// String PLUGIN_PACKAGE = "org.smart4j.plugin";
//
// String JSP_PATH = ConfigHelper.getString("smart.framework.app.jsp_path", "/WEB-INF/jsp/");
// String WWW_PATH = ConfigHelper.getString("smart.framework.app.www_path", "/www/");
// String HOME_PAGE = ConfigHelper.getString("smart.framework.app.home_page", "/index.html");
// int UPLOAD_LIMIT = ConfigHelper.getInt("smart.framework.app.upload_limit", 10);
//
// String PK_NAME = "id";
// }
//
// Path: src/main/java/org/smart4j/framework/InstanceFactory.java
// public class InstanceFactory {
//
// /**
// * 用于缓存对应的实例
// */
// private static final Map<String, Object> cache = new ConcurrentHashMap<String, Object>();
//
// /**
// * ClassScanner
// */
// private static final String CLASS_SCANNER = "smart.framework.custom.class_scanner";
//
// /**
// * DataSourceFactory
// */
// private static final String DS_FACTORY = "smart.framework.custom.ds_factory";
//
// /**
// * DataAccessor
// */
// private static final String DATA_ACCESSOR = "smart.framework.custom.data_accessor";
//
// /**
// * HandlerMapping
// */
// private static final String HANDLER_MAPPING = "smart.framework.custom.handler_mapping";
//
// /**
// * HandlerInvoker
// */
// private static final String HANDLER_INVOKER = "smart.framework.custom.handler_invoker";
//
// /**
// * HandlerExceptionResolver
// */
// private static final String HANDLER_EXCEPTION_RESOLVER = "smart.framework.custom.handler_exception_resolver";
//
// /**
// * ViewResolver
// */
// private static final String VIEW_RESOLVER = "smart.framework.custom.view_resolver";
//
// /**
// * 获取 ClassScanner
// */
// public static ClassScanner getClassScanner() {
// return getInstance(CLASS_SCANNER, DefaultClassScanner.class);
// }
//
// /**
// * 获取 DataSourceFactory
// */
// public static DataSourceFactory getDataSourceFactory() {
// return getInstance(DS_FACTORY, DefaultDataSourceFactory.class);
// }
//
// /**
// * 获取 DataAccessor
// */
// public static DataAccessor getDataAccessor() {
// return getInstance(DATA_ACCESSOR, DefaultDataAccessor.class);
// }
//
// /**
// * 获取 HandlerMapping
// */
// public static HandlerMapping getHandlerMapping() {
// return getInstance(HANDLER_MAPPING, DefaultHandlerMapping.class);
// }
//
// /**
// * 获取 HandlerInvoker
// */
// public static HandlerInvoker getHandlerInvoker() {
// return getInstance(HANDLER_INVOKER, DefaultHandlerInvoker.class);
// }
//
// /**
// * 获取 HandlerExceptionResolver
// */
// public static HandlerExceptionResolver getHandlerExceptionResolver() {
// return getInstance(HANDLER_EXCEPTION_RESOLVER, DefaultHandlerExceptionResolver.class);
// }
//
// /**
// * 获取 ViewResolver
// */
// public static ViewResolver getViewResolver() {
// return getInstance(VIEW_RESOLVER, DefaultViewResolver.class);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getInstance(String cacheKey, Class<T> defaultImplClass) {
// // 若缓存中存在对应的实例,则返回该实例
// if (cache.containsKey(cacheKey)) {
// return (T) cache.get(cacheKey);
// }
// // 从配置文件中获取相应的接口实现类配置
// String implClassName = ConfigHelper.getString(cacheKey);
// // 若实现类配置不存在,则使用默认实现类
// if (StringUtil.isEmpty(implClassName)) {
// implClassName = defaultImplClass.getName();
// }
// // 通过反射创建该实现类对应的实例
// T instance = ObjectUtil.newInstance(implClassName);
// // 若该实例不为空,则将其放入缓存
// if (instance != null) {
// cache.put(cacheKey, instance);
// }
// // 返回该实例
// return instance;
// }
// }
// Path: src/main/java/org/smart4j/framework/mvc/DispatcherServlet.java
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.FrameworkConstant;
import org.smart4j.framework.InstanceFactory;
import org.smart4j.framework.util.WebUtil;
package org.smart4j.framework.mvc;
/**
* 前端控制器
*
* @author huangyong
* @since 1.0
*/
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(DispatcherServlet.class);
| private HandlerMapping handlerMapping = InstanceFactory.getHandlerMapping(); |
Azure/azure-documentdb-java | bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java | // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
| import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | return numberOfDocumentsImported.get();
}
public double getTotalRequestUnitsConsumed() {
return totalRequestUnitsConsumed.get();
}
public Iterator<Callable<InsertMetrics>> miniBatchInsertExecutionCallableIterator() {
Stream<Callable<InsertMetrics>> stream = batchesToInsert.stream().map(miniBatch -> {
return new Callable<InsertMetrics>() {
@Override
public InsertMetrics call() throws Exception {
try {
logger.debug("pki {} importing mini batch started", partitionKeyRangeId);
Stopwatch stopwatch = Stopwatch.createStarted();
double requestUnitsCounsumed = 0;
int numberOfThrottles = 0;
StoredProcedureResponse response;
boolean timedOut = false;
int currentDocumentIndex = 0;
while (currentDocumentIndex < miniBatch.size() && !cancel) {
logger.debug("pki {} inside for loop, currentDocumentIndex", partitionKeyRangeId, currentDocumentIndex);
String[] docBatch = miniBatch.subList(currentDocumentIndex, miniBatch.size()).toArray(new String[0]);
| // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
return numberOfDocumentsImported.get();
}
public double getTotalRequestUnitsConsumed() {
return totalRequestUnitsConsumed.get();
}
public Iterator<Callable<InsertMetrics>> miniBatchInsertExecutionCallableIterator() {
Stream<Callable<InsertMetrics>> stream = batchesToInsert.stream().map(miniBatch -> {
return new Callable<InsertMetrics>() {
@Override
public InsertMetrics call() throws Exception {
try {
logger.debug("pki {} importing mini batch started", partitionKeyRangeId);
Stopwatch stopwatch = Stopwatch.createStarted();
double requestUnitsCounsumed = 0;
int numberOfThrottles = 0;
StoredProcedureResponse response;
boolean timedOut = false;
int currentDocumentIndex = 0;
while (currentDocumentIndex < miniBatch.size() && !cancel) {
logger.debug("pki {} inside for loop, currentDocumentIndex", partitionKeyRangeId, currentDocumentIndex);
String[] docBatch = miniBatch.subList(currentDocumentIndex, miniBatch.size()).toArray(new String[0]);
| boolean isThrottled = false; |
Azure/azure-documentdb-java | bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java | // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
| import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | if (bulkImportResponse != null) {
if (bulkImportResponse.errorCode != 0) {
logger.warn("pki {} Received response error code {}", partitionKeyRangeId, bulkImportResponse.errorCode);
if (bulkImportResponse.count == 0) {
throw new RuntimeException(
String.format("Stored proc returned failure %s", bulkImportResponse.errorCode));
}
}
double requestCharge = response.getRequestCharge();
currentDocumentIndex += bulkImportResponse.count;
numberOfDocumentsImported.addAndGet(bulkImportResponse.count);
requestUnitsCounsumed += requestCharge;
totalRequestUnitsConsumed.addAndGet(requestCharge);
}
else {
logger.warn("pki {} Failed to receive response", partitionKeyRangeId);
}
} catch (DocumentClientException e) {
logger.debug("pki {} Importing minibatch failed", partitionKeyRangeId, e);
if (isThrottled(e)) {
logger.debug("pki {} Throttled on partition range id", partitionKeyRangeId);
numberOfThrottles++;
isThrottled = true;
retryAfter = Duration.ofMillis(e.getRetryAfterInMilliseconds());
// will retry again
| // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
if (bulkImportResponse != null) {
if (bulkImportResponse.errorCode != 0) {
logger.warn("pki {} Received response error code {}", partitionKeyRangeId, bulkImportResponse.errorCode);
if (bulkImportResponse.count == 0) {
throw new RuntimeException(
String.format("Stored proc returned failure %s", bulkImportResponse.errorCode));
}
}
double requestCharge = response.getRequestCharge();
currentDocumentIndex += bulkImportResponse.count;
numberOfDocumentsImported.addAndGet(bulkImportResponse.count);
requestUnitsCounsumed += requestCharge;
totalRequestUnitsConsumed.addAndGet(requestCharge);
}
else {
logger.warn("pki {} Failed to receive response", partitionKeyRangeId);
}
} catch (DocumentClientException e) {
logger.debug("pki {} Importing minibatch failed", partitionKeyRangeId, e);
if (isThrottled(e)) {
logger.debug("pki {} Throttled on partition range id", partitionKeyRangeId);
numberOfThrottles++;
isThrottled = true;
retryAfter = Duration.ofMillis(e.getRetryAfterInMilliseconds());
// will retry again
| } else if (isTimedOut(e)) { |
Azure/azure-documentdb-java | bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java | // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
| import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | String.format("Stored proc returned failure %s", bulkImportResponse.errorCode));
}
}
double requestCharge = response.getRequestCharge();
currentDocumentIndex += bulkImportResponse.count;
numberOfDocumentsImported.addAndGet(bulkImportResponse.count);
requestUnitsCounsumed += requestCharge;
totalRequestUnitsConsumed.addAndGet(requestCharge);
}
else {
logger.warn("pki {} Failed to receive response", partitionKeyRangeId);
}
} catch (DocumentClientException e) {
logger.debug("pki {} Importing minibatch failed", partitionKeyRangeId, e);
if (isThrottled(e)) {
logger.debug("pki {} Throttled on partition range id", partitionKeyRangeId);
numberOfThrottles++;
isThrottled = true;
retryAfter = Duration.ofMillis(e.getRetryAfterInMilliseconds());
// will retry again
} else if (isTimedOut(e)) {
logger.debug("pki {} Request timed out", partitionKeyRangeId);
timedOut = true;
// will retry again
| // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
String.format("Stored proc returned failure %s", bulkImportResponse.errorCode));
}
}
double requestCharge = response.getRequestCharge();
currentDocumentIndex += bulkImportResponse.count;
numberOfDocumentsImported.addAndGet(bulkImportResponse.count);
requestUnitsCounsumed += requestCharge;
totalRequestUnitsConsumed.addAndGet(requestCharge);
}
else {
logger.warn("pki {} Failed to receive response", partitionKeyRangeId);
}
} catch (DocumentClientException e) {
logger.debug("pki {} Importing minibatch failed", partitionKeyRangeId, e);
if (isThrottled(e)) {
logger.debug("pki {} Throttled on partition range id", partitionKeyRangeId);
numberOfThrottles++;
isThrottled = true;
retryAfter = Duration.ofMillis(e.getRetryAfterInMilliseconds());
// will retry again
} else if (isTimedOut(e)) {
logger.debug("pki {} Request timed out", partitionKeyRangeId);
timedOut = true;
// will retry again
| } else if (isGone(e)) { |
Azure/azure-documentdb-java | bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java | // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
| import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | }
double requestCharge = response.getRequestCharge();
currentDocumentIndex += bulkImportResponse.count;
numberOfDocumentsImported.addAndGet(bulkImportResponse.count);
requestUnitsCounsumed += requestCharge;
totalRequestUnitsConsumed.addAndGet(requestCharge);
}
else {
logger.warn("pki {} Failed to receive response", partitionKeyRangeId);
}
} catch (DocumentClientException e) {
logger.debug("pki {} Importing minibatch failed", partitionKeyRangeId, e);
if (isThrottled(e)) {
logger.debug("pki {} Throttled on partition range id", partitionKeyRangeId);
numberOfThrottles++;
isThrottled = true;
retryAfter = Duration.ofMillis(e.getRetryAfterInMilliseconds());
// will retry again
} else if (isTimedOut(e)) {
logger.debug("pki {} Request timed out", partitionKeyRangeId);
timedOut = true;
// will retry again
} else if (isGone(e)) {
// there is no value in retrying | // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isGone(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isSplit(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.GONE
// && HttpConstants.SubStatusCodes.SPLITTING == e.getSubStatusCode();
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isThrottled(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TOO_MANY_REQUESTS;
// }
//
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/ExceptionUtils.java
// public static boolean isTimedOut(DocumentClientException e) {
// return e.getStatusCode() == HttpConstants.StatusCodes.TIMEOUT;
// }
// Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/BatchInserter.java
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isGone;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isSplit;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isThrottled;
import static com.microsoft.azure.documentdb.bulkimport.ExceptionUtils.isTimedOut;
import java.io.IOException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.AtomicDouble;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
}
double requestCharge = response.getRequestCharge();
currentDocumentIndex += bulkImportResponse.count;
numberOfDocumentsImported.addAndGet(bulkImportResponse.count);
requestUnitsCounsumed += requestCharge;
totalRequestUnitsConsumed.addAndGet(requestCharge);
}
else {
logger.warn("pki {} Failed to receive response", partitionKeyRangeId);
}
} catch (DocumentClientException e) {
logger.debug("pki {} Importing minibatch failed", partitionKeyRangeId, e);
if (isThrottled(e)) {
logger.debug("pki {} Throttled on partition range id", partitionKeyRangeId);
numberOfThrottles++;
isThrottled = true;
retryAfter = Duration.ofMillis(e.getRetryAfterInMilliseconds());
// will retry again
} else if (isTimedOut(e)) {
logger.debug("pki {} Request timed out", partitionKeyRangeId);
timedOut = true;
// will retry again
} else if (isGone(e)) {
// there is no value in retrying | if (isSplit(e)) { |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/EndToEndTestBase.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String HOST = System.getProperty("ACCOUNT_HOST");
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String MASTER_KEY = System.getProperty("ACCOUNT_KEY");
| import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.HOST;
import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.MASTER_KEY;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.documentdb.ConnectionMode;
import com.microsoft.azure.documentdb.ConnectionPolicy;
import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.Database;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.DocumentCollection;
import com.microsoft.azure.documentdb.FeedResponse;
import com.microsoft.azure.documentdb.Offer;
import com.microsoft.azure.documentdb.PartitionKeyDefinition;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.internal.directconnectivity.HttpClientFactory; | /**
* The MIT License (MIT)
* Copyright (c) 2017 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class EndToEndTestBase {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected String databaseId = "bulkImportTestDatabase";
protected String collectionId;
protected String collectionLink;
protected DocumentCollection pCollection;
protected static Set<String> SYSTEM_FIELD_NAMES;
static {
SYSTEM_FIELD_NAMES = new HashSet<>();
SYSTEM_FIELD_NAMES.addAll(Arrays.asList(new String[] { "_rid", "_attachments", "_self", "_etag" , "_ts"}));
}
public EndToEndTestBase() {
HttpClientFactory.DISABLE_HOST_NAME_VERIFICATION = true;
collectionId = UUID.randomUUID().toString();
collectionLink = "dbs/" + databaseId + "/colls/" + collectionId;
}
@Parameters
public static List<Object[]> configs() {
ConnectionPolicy directModePolicy = new ConnectionPolicy();
directModePolicy.setConnectionMode(ConnectionMode.DirectHttps);
ConnectionPolicy gatewayModePolicy = new ConnectionPolicy();
gatewayModePolicy.setConnectionMode(ConnectionMode.Gateway);
return Arrays.asList(new Object[][] { | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String HOST = System.getProperty("ACCOUNT_HOST");
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String MASTER_KEY = System.getProperty("ACCOUNT_KEY");
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/EndToEndTestBase.java
import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.HOST;
import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.MASTER_KEY;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.documentdb.ConnectionMode;
import com.microsoft.azure.documentdb.ConnectionPolicy;
import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.Database;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.DocumentCollection;
import com.microsoft.azure.documentdb.FeedResponse;
import com.microsoft.azure.documentdb.Offer;
import com.microsoft.azure.documentdb.PartitionKeyDefinition;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.internal.directconnectivity.HttpClientFactory;
/**
* The MIT License (MIT)
* Copyright (c) 2017 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class EndToEndTestBase {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected String databaseId = "bulkImportTestDatabase";
protected String collectionId;
protected String collectionLink;
protected DocumentCollection pCollection;
protected static Set<String> SYSTEM_FIELD_NAMES;
static {
SYSTEM_FIELD_NAMES = new HashSet<>();
SYSTEM_FIELD_NAMES.addAll(Arrays.asList(new String[] { "_rid", "_attachments", "_self", "_etag" , "_ts"}));
}
public EndToEndTestBase() {
HttpClientFactory.DISABLE_HOST_NAME_VERIFICATION = true;
collectionId = UUID.randomUUID().toString();
collectionLink = "dbs/" + databaseId + "/colls/" + collectionId;
}
@Parameters
public static List<Object[]> configs() {
ConnectionPolicy directModePolicy = new ConnectionPolicy();
directModePolicy.setConnectionMode(ConnectionMode.DirectHttps);
ConnectionPolicy gatewayModePolicy = new ConnectionPolicy();
gatewayModePolicy.setConnectionMode(ConnectionMode.Gateway);
return Arrays.asList(new Object[][] { | { new DocumentClientConfiguration(HOST, MASTER_KEY, gatewayModePolicy, ConsistencyLevel.Eventual) }, |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/EndToEndTestBase.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String HOST = System.getProperty("ACCOUNT_HOST");
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String MASTER_KEY = System.getProperty("ACCOUNT_KEY");
| import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.HOST;
import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.MASTER_KEY;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.documentdb.ConnectionMode;
import com.microsoft.azure.documentdb.ConnectionPolicy;
import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.Database;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.DocumentCollection;
import com.microsoft.azure.documentdb.FeedResponse;
import com.microsoft.azure.documentdb.Offer;
import com.microsoft.azure.documentdb.PartitionKeyDefinition;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.internal.directconnectivity.HttpClientFactory; | /**
* The MIT License (MIT)
* Copyright (c) 2017 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class EndToEndTestBase {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected String databaseId = "bulkImportTestDatabase";
protected String collectionId;
protected String collectionLink;
protected DocumentCollection pCollection;
protected static Set<String> SYSTEM_FIELD_NAMES;
static {
SYSTEM_FIELD_NAMES = new HashSet<>();
SYSTEM_FIELD_NAMES.addAll(Arrays.asList(new String[] { "_rid", "_attachments", "_self", "_etag" , "_ts"}));
}
public EndToEndTestBase() {
HttpClientFactory.DISABLE_HOST_NAME_VERIFICATION = true;
collectionId = UUID.randomUUID().toString();
collectionLink = "dbs/" + databaseId + "/colls/" + collectionId;
}
@Parameters
public static List<Object[]> configs() {
ConnectionPolicy directModePolicy = new ConnectionPolicy();
directModePolicy.setConnectionMode(ConnectionMode.DirectHttps);
ConnectionPolicy gatewayModePolicy = new ConnectionPolicy();
gatewayModePolicy.setConnectionMode(ConnectionMode.Gateway);
return Arrays.asList(new Object[][] { | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String HOST = System.getProperty("ACCOUNT_HOST");
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestConfigurations.java
// public static String MASTER_KEY = System.getProperty("ACCOUNT_KEY");
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/EndToEndTestBase.java
import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.HOST;
import static com.microsoft.azure.documentdb.bulkimport.TestConfigurations.MASTER_KEY;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microsoft.azure.documentdb.ConnectionMode;
import com.microsoft.azure.documentdb.ConnectionPolicy;
import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.Database;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.DocumentCollection;
import com.microsoft.azure.documentdb.FeedResponse;
import com.microsoft.azure.documentdb.Offer;
import com.microsoft.azure.documentdb.PartitionKeyDefinition;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.internal.directconnectivity.HttpClientFactory;
/**
* The MIT License (MIT)
* Copyright (c) 2017 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class EndToEndTestBase {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected String databaseId = "bulkImportTestDatabase";
protected String collectionId;
protected String collectionLink;
protected DocumentCollection pCollection;
protected static Set<String> SYSTEM_FIELD_NAMES;
static {
SYSTEM_FIELD_NAMES = new HashSet<>();
SYSTEM_FIELD_NAMES.addAll(Arrays.asList(new String[] { "_rid", "_attachments", "_self", "_etag" , "_ts"}));
}
public EndToEndTestBase() {
HttpClientFactory.DISABLE_HOST_NAME_VERIFICATION = true;
collectionId = UUID.randomUUID().toString();
collectionLink = "dbs/" + databaseId + "/colls/" + collectionId;
}
@Parameters
public static List<Object[]> configs() {
ConnectionPolicy directModePolicy = new ConnectionPolicy();
directModePolicy.setConnectionMode(ConnectionMode.DirectHttps);
ConnectionPolicy gatewayModePolicy = new ConnectionPolicy();
gatewayModePolicy.setConnectionMode(ConnectionMode.Gateway);
return Arrays.asList(new Object[][] { | { new DocumentClientConfiguration(HOST, MASTER_KEY, gatewayModePolicy, ConsistencyLevel.Eventual) }, |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/CongestionControllerTests.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
| import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | /**
* The MIT License (MIT)
* Copyright (c) 2016 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class CongestionControllerTests {
private ListeningExecutorService listeningExecutorService;
private static final int TIMEOUT = 5000;
@Before
public void setUp() {
listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}
@After
public void shutDown() {
listeningExecutorService.shutdown();
}
@Test(timeout = TIMEOUT)
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String paritionKeyRangeId = "0";
BatchInserter bi = new BatchInserter(paritionKeyRangeId, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
| // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/CongestionControllerTests.java
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
/**
* The MIT License (MIT)
* Copyright (c) 2016 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class CongestionControllerTests {
private ListeningExecutorService listeningExecutorService;
private static final int TIMEOUT = 5000;
@Before
public void setUp() {
listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}
@After
public void shutDown() {
listeningExecutorService.shutdown();
}
@Test(timeout = TIMEOUT)
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String paritionKeyRangeId = "0";
BatchInserter bi = new BatchInserter(paritionKeyRangeId, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
| Map<String, String> headers = withRequestCharge(null, 5.5); |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/CongestionControllerTests.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
| import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | /**
* The MIT License (MIT)
* Copyright (c) 2016 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class CongestionControllerTests {
private ListeningExecutorService listeningExecutorService;
private static final int TIMEOUT = 5000;
@Before
public void setUp() {
listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}
@After
public void shutDown() {
listeningExecutorService.shutdown();
}
@Test(timeout = TIMEOUT)
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String paritionKeyRangeId = "0";
BatchInserter bi = new BatchInserter(paritionKeyRangeId, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Map<String, String> headers = withRequestCharge(null, 5.5);
| // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/CongestionControllerTests.java
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
/**
* The MIT License (MIT)
* Copyright (c) 2016 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class CongestionControllerTests {
private ListeningExecutorService listeningExecutorService;
private static final int TIMEOUT = 5000;
@Before
public void setUp() {
listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}
@After
public void shutDown() {
listeningExecutorService.shutdown();
}
@Test(timeout = TIMEOUT)
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String paritionKeyRangeId = "0";
BatchInserter bi = new BatchInserter(paritionKeyRangeId, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Map<String, String> headers = withRequestCharge(null, 5.5);
| StoredProcedureResponse bulkImportResponse = getStoredProcedureResponse(getBulkImportStoredProcedureResponse(numberOfDocuments, 0), headers); |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/CongestionControllerTests.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
| import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | /**
* The MIT License (MIT)
* Copyright (c) 2016 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class CongestionControllerTests {
private ListeningExecutorService listeningExecutorService;
private static final int TIMEOUT = 5000;
@Before
public void setUp() {
listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}
@After
public void shutDown() {
listeningExecutorService.shutdown();
}
@Test(timeout = TIMEOUT)
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String paritionKeyRangeId = "0";
BatchInserter bi = new BatchInserter(paritionKeyRangeId, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Map<String, String> headers = withRequestCharge(null, 5.5);
| // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/CongestionControllerTests.java
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
/**
* The MIT License (MIT)
* Copyright (c) 2016 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
public class CongestionControllerTests {
private ListeningExecutorService listeningExecutorService;
private static final int TIMEOUT = 5000;
@Before
public void setUp() {
listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}
@After
public void shutDown() {
listeningExecutorService.shutdown();
}
@Test(timeout = TIMEOUT)
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String paritionKeyRangeId = "0";
BatchInserter bi = new BatchInserter(paritionKeyRangeId, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Map<String, String> headers = withRequestCharge(null, 5.5);
| StoredProcedureResponse bulkImportResponse = getStoredProcedureResponse(getBulkImportStoredProcedureResponse(numberOfDocuments, 0), headers); |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
| import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; |
assertThat(list.size(), equalTo(3));
}
@Test
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
| // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
assertThat(list.size(), equalTo(3));
}
@Test
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
| Map<String, String> headers = withRequestCharge(null, 5.5); |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
| import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | }
@Test
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
Map<String, String> headers = withRequestCharge(null, 5.5);
| // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
}
@Test
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
Map<String, String> headers = withRequestCharge(null, 5.5);
| StoredProcedureResponse bulkImportResponse = getStoredProcedureResponse(getBulkImportStoredProcedureResponse(numberOfDocuments, 0), headers); |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
| import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | }
@Test
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
Map<String, String> headers = withRequestCharge(null, 5.5);
| // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
}
@Test
public void simple() throws Exception {
BulkImportStoredProcedureOptions options = null;
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
Map<String, String> headers = withRequestCharge(null, 5.5);
| StoredProcedureResponse bulkImportResponse = getStoredProcedureResponse(getBulkImportStoredProcedureResponse(numberOfDocuments, 0), headers); |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java | // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
| import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse; | public void throttle() throws Exception {
BulkImportStoredProcedureOptions options = new BulkImportStoredProcedureOptions(true, true, "fakeCollectionId", true);
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
Map<String, String> headers = withRequestCharge(null, 5.5);
StoredProcedureResponse bulkImportResponse = getStoredProcedureResponse(getBulkImportStoredProcedureResponse(numberOfDocuments, 0), headers);
| // Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static BulkImportStoredProcedureResponse getBulkImportStoredProcedureResponse(int count, int error) {
// BulkImportStoredProcedureResponse bispr = new BulkImportStoredProcedureResponse();
// bispr.count = count;
// bispr.errorCode = error;
// return bispr;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static StoredProcedureResponse getStoredProcedureResponse(
// BulkImportStoredProcedureResponse bulkImportResponse, Map<String, String> headerResponse)
// throws JsonProcessingException, InstantiationException, IllegalAccessException, IllegalArgumentException,
// InvocationTargetException, NoSuchMethodException, SecurityException {
//
// DocumentServiceResponse documentServiceResponse = Mockito.mock(DocumentServiceResponse.class);
// when(documentServiceResponse.getReponseBodyAsString()).thenReturn(MAPPER.writeValueAsString(bulkImportResponse));
// when(documentServiceResponse.getResponseHeaders()).thenReturn(headerResponse);
//
// Constructor<StoredProcedureResponse> constructor = StoredProcedureResponse.class
// .getDeclaredConstructor(DocumentServiceResponse.class);
// constructor.setAccessible(true);
//
// StoredProcedureResponse storedProcedureResponse = constructor.newInstance(documentServiceResponse);
//
// return storedProcedureResponse;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static DocumentClientException getThrottleException() {
// DocumentClientException e = Mockito.mock(DocumentClientException.class);
// when(e.getStatusCode()).thenReturn(429);
// when(e.getRetryAfterInMilliseconds()).thenReturn(1l);
//
// return e;
// }
//
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/TestUtils.java
// public static Map<String, String> withRequestCharge(Map<String, String> headerResponse, double requestCharge) {
// if (headerResponse == null) {
// headerResponse = new HashMap<>();
// }
//
// headerResponse.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
// return headerResponse;
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/BatchInserterTests.java
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getBulkImportStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getStoredProcedureResponse;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.getThrottleException;
import static com.microsoft.azure.documentdb.bulkimport.TestUtils.withRequestCharge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Iterators;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.RequestOptions;
import com.microsoft.azure.documentdb.StoredProcedureResponse;
public void throttle() throws Exception {
BulkImportStoredProcedureOptions options = new BulkImportStoredProcedureOptions(true, true, "fakeCollectionId", true);
String bulkImportSproc = null;
DocumentClient client = Mockito.mock(DocumentClient.class);
List<List<String>> batchesToInsert = new ArrayList<>();
batchesToInsert.add(new ArrayList<>());
int numberOfDocuments = 10;
for (int i = 0; i < numberOfDocuments; i++) {
batchesToInsert.get(0).add("{}");
}
String partitionIndex = "0";
BatchInserter bi = new BatchInserter(partitionIndex, batchesToInsert, client, bulkImportSproc, options);
Iterator<Callable<InsertMetrics>> callbackIterator = bi.miniBatchInsertExecutionCallableIterator();
List<Callable<InsertMetrics>> list = new ArrayList<>();
Iterators.addAll(list, callbackIterator);
assertThat(list.size(), equalTo(1));
Callable<InsertMetrics> callable = list.get(0);
Map<String, String> headers = withRequestCharge(null, 5.5);
StoredProcedureResponse bulkImportResponse = getStoredProcedureResponse(getBulkImportStoredProcedureResponse(numberOfDocuments, 0), headers);
| DocumentClientException throttleException = getThrottleException(); |
Azure/azure-documentdb-java | bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/EndToEndBulkImportTests.java | // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/DocumentBulkImporter.java
// public static class Builder {
//
// private DocumentClient client;
// private String collectionLink;
// private int maxMiniBatchSize = (int) Math.floor(MAX_BULK_IMPORT_SCRIPT_INPUT_SIZE * FRACTION_OF_MAX_BULK_IMPORT_SCRIPT_INPUT_SIZE_ALLOWED);
// private final static int DEFAULT_RETRY_ATTEMPT_ON_THROTTLING_FOR_INIT = 200;
// private final static int DEFAULT_WAIT_TIME_ON_THROTTLING_FOR_INIT_IN_SECONDS = 60;
//
// private PartitionKeyDefinition partitionKeyDef;
// private int offerThroughput;
//
// private static RetryOptions DEFAULT_INIT_RETRY_OPTIONS;
//
// static {
// DEFAULT_INIT_RETRY_OPTIONS = new RetryOptions();
// DEFAULT_INIT_RETRY_OPTIONS.setMaxRetryAttemptsOnThrottledRequests(DEFAULT_RETRY_ATTEMPT_ON_THROTTLING_FOR_INIT);
// DEFAULT_INIT_RETRY_OPTIONS.setMaxRetryWaitTimeInSeconds(DEFAULT_WAIT_TIME_ON_THROTTLING_FOR_INIT_IN_SECONDS);
// }
//
// private RetryOptions retryOptions = DEFAULT_INIT_RETRY_OPTIONS;
//
// /**
// * Use the instance of {@link DocumentClient} to bulk import to the given instance of {@link DocumentCollection}
// * @param client an instance of {@link DocumentClient}
// * @param partitionKeyDef specifies the {@link PartitionKeyDefinition} of the collection
// * @param databaseName name of the database
// * @param collectionName name of the collection
// * @param offerThroughput specifies the collection throughput
// * @return an instance of {@link Builder}
// */
// public Builder from(DocumentClient client,
// String databaseName,
// String collectionName,
// PartitionKeyDefinition partitionKeyDef,
// int offerThroughput) {
//
// // TODO: validate the retry options for the client
// this.client = client;
// this.collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName);
// this.partitionKeyDef = partitionKeyDef;
// this.offerThroughput = offerThroughput;
// return this;
// }
//
// /**
// * use the given size to configure max mini batch size.
// *
// * If not specified will use the default.
// * @param size specifies the size of mini batch.
// * @return {@link Builder}
// */
// public Builder withMaxMiniBatchSize(int size) {
// Preconditions.checkArgument(size > 0, "maxMiniBatchSize cannot be negative");
// Preconditions.checkArgument(size <= MAX_BULK_IMPORT_SCRIPT_INPUT_SIZE, "maxMiniBatchSize cannot be negative");
//
// this.maxMiniBatchSize = size;
// return this;
// }
//
// /**
// * use the given retry option for initialization
// *
// * @param options an instance of {@link RetryOptions}
// * @return {@link Builder}
// */
// public Builder withInitializationRetryOptions(RetryOptions options) {
// this.retryOptions = options;
// return this;
// }
//
// /**
// * Instantiates {@link DocumentBulkImporter} given the configured {@link Builder}.
// *
// * @return the new builder
// * @throws Exception if there is any failure
// */
// public DocumentBulkImporter build() throws Exception {
// DocumentBulkImporter importer = new DocumentBulkImporter(client, collectionLink, partitionKeyDef, offerThroughput);
// try {
// importer.setInitializationRetryOptions(retryOptions);
// importer.setMaxMiniBatchSize(maxMiniBatchSize);
//
// importer.safeInit();
//
// } catch (Exception e) {
// importer.close();
// throw e;
// }
// return importer;
// }
//
// private Builder() {}
// }
| import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import com.microsoft.azure.documentdb.Document;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.Undefined;
import com.microsoft.azure.documentdb.bulkimport.DocumentBulkImporter.Builder;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors; | /**
* The MIT License (MIT)
* Copyright (c) 2017 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
@RunWith(Parameterized.class)
public class EndToEndBulkImportTests extends EndToEndTestBase {
private DocumentClient client;
public EndToEndBulkImportTests(DocumentClientConfiguration config) {
this.client = new DocumentClient(config.getEndpoint(), config.getMasterKey(), config.getConnectionPolicy(),
config.getConsistencyLevel());
}
@Before
public void setup() throws Exception {
super.setup(this.client);
Thread.sleep(1000);
}
@After
public void shutdown() throws DocumentClientException {
super.shutdown(this.client);
}
@Test
public void bulkImport() throws Exception { | // Path: bulkimport/src/main/java/com/microsoft/azure/documentdb/bulkimport/DocumentBulkImporter.java
// public static class Builder {
//
// private DocumentClient client;
// private String collectionLink;
// private int maxMiniBatchSize = (int) Math.floor(MAX_BULK_IMPORT_SCRIPT_INPUT_SIZE * FRACTION_OF_MAX_BULK_IMPORT_SCRIPT_INPUT_SIZE_ALLOWED);
// private final static int DEFAULT_RETRY_ATTEMPT_ON_THROTTLING_FOR_INIT = 200;
// private final static int DEFAULT_WAIT_TIME_ON_THROTTLING_FOR_INIT_IN_SECONDS = 60;
//
// private PartitionKeyDefinition partitionKeyDef;
// private int offerThroughput;
//
// private static RetryOptions DEFAULT_INIT_RETRY_OPTIONS;
//
// static {
// DEFAULT_INIT_RETRY_OPTIONS = new RetryOptions();
// DEFAULT_INIT_RETRY_OPTIONS.setMaxRetryAttemptsOnThrottledRequests(DEFAULT_RETRY_ATTEMPT_ON_THROTTLING_FOR_INIT);
// DEFAULT_INIT_RETRY_OPTIONS.setMaxRetryWaitTimeInSeconds(DEFAULT_WAIT_TIME_ON_THROTTLING_FOR_INIT_IN_SECONDS);
// }
//
// private RetryOptions retryOptions = DEFAULT_INIT_RETRY_OPTIONS;
//
// /**
// * Use the instance of {@link DocumentClient} to bulk import to the given instance of {@link DocumentCollection}
// * @param client an instance of {@link DocumentClient}
// * @param partitionKeyDef specifies the {@link PartitionKeyDefinition} of the collection
// * @param databaseName name of the database
// * @param collectionName name of the collection
// * @param offerThroughput specifies the collection throughput
// * @return an instance of {@link Builder}
// */
// public Builder from(DocumentClient client,
// String databaseName,
// String collectionName,
// PartitionKeyDefinition partitionKeyDef,
// int offerThroughput) {
//
// // TODO: validate the retry options for the client
// this.client = client;
// this.collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName);
// this.partitionKeyDef = partitionKeyDef;
// this.offerThroughput = offerThroughput;
// return this;
// }
//
// /**
// * use the given size to configure max mini batch size.
// *
// * If not specified will use the default.
// * @param size specifies the size of mini batch.
// * @return {@link Builder}
// */
// public Builder withMaxMiniBatchSize(int size) {
// Preconditions.checkArgument(size > 0, "maxMiniBatchSize cannot be negative");
// Preconditions.checkArgument(size <= MAX_BULK_IMPORT_SCRIPT_INPUT_SIZE, "maxMiniBatchSize cannot be negative");
//
// this.maxMiniBatchSize = size;
// return this;
// }
//
// /**
// * use the given retry option for initialization
// *
// * @param options an instance of {@link RetryOptions}
// * @return {@link Builder}
// */
// public Builder withInitializationRetryOptions(RetryOptions options) {
// this.retryOptions = options;
// return this;
// }
//
// /**
// * Instantiates {@link DocumentBulkImporter} given the configured {@link Builder}.
// *
// * @return the new builder
// * @throws Exception if there is any failure
// */
// public DocumentBulkImporter build() throws Exception {
// DocumentBulkImporter importer = new DocumentBulkImporter(client, collectionLink, partitionKeyDef, offerThroughput);
// try {
// importer.setInitializationRetryOptions(retryOptions);
// importer.setMaxMiniBatchSize(maxMiniBatchSize);
//
// importer.safeInit();
//
// } catch (Exception e) {
// importer.close();
// throw e;
// }
// return importer;
// }
//
// private Builder() {}
// }
// Path: bulkimport/src/test/java/com/microsoft/azure/documentdb/bulkimport/EndToEndBulkImportTests.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import com.microsoft.azure.documentdb.Document;
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.Undefined;
import com.microsoft.azure.documentdb.bulkimport.DocumentBulkImporter.Builder;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* The MIT License (MIT)
* Copyright (c) 2017 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.azure.documentdb.bulkimport;
@RunWith(Parameterized.class)
public class EndToEndBulkImportTests extends EndToEndTestBase {
private DocumentClient client;
public EndToEndBulkImportTests(DocumentClientConfiguration config) {
this.client = new DocumentClient(config.getEndpoint(), config.getMasterKey(), config.getConnectionPolicy(),
config.getConsistencyLevel());
}
@Before
public void setup() throws Exception {
super.setup(this.client);
Thread.sleep(1000);
}
@After
public void shutdown() throws DocumentClientException {
super.shutdown(this.client);
}
@Test
public void bulkImport() throws Exception { | Builder bulkImporterBuilder = DocumentBulkImporter.builder(). |
dbennett455/DetectHtml | test/DetectHtmlTest.java | // Path: src/org/github/DetectHtml.java
// public class DetectHtml
// {
// // adapted from post by Phil Haack and modified to match better
// public final static String tagStart=
// "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)\\>";
// public final static String tagEnd=
// "\\</\\w+\\>";
// public final static String tagSelfClosing=
// "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)/\\>";
// public final static String htmlEntity=
// "&[a-zA-Z][a-zA-Z0-9]+;";
// public final static Pattern htmlPattern=Pattern.compile(
// "("+tagStart+".*"+tagEnd+")|("+tagSelfClosing+")|("+htmlEntity+")",
// Pattern.DOTALL
// );
//
// /**
// * Will return true if s contains HTML markup tags or entities.
// *
// * @param s String to test
// * @return true if string contains HTML
// */
// public static boolean isHtml(String s) {
// boolean ret=false;
// if (s != null) {
// ret=htmlPattern.matcher(s).find();
// }
// return ret;
// }
//
// }
| import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.github.DetectHtml;
import org.junit.Test; |
public class DetectHtmlTest {
@Test
public void test() {
boolean reportToConsole=false;
boolean fileNotFound=false;
// iterate through HTML files
File[] htmlFiles = new File("testdata/html/").listFiles();
if (reportToConsole)
System.out.println("Testing HTML files\n-----");
for (File htmlFile : htmlFiles) {
fileNotFound=false;
try {
String htmlContent = new Scanner(htmlFile).useDelimiter("\\Z").next(); | // Path: src/org/github/DetectHtml.java
// public class DetectHtml
// {
// // adapted from post by Phil Haack and modified to match better
// public final static String tagStart=
// "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)\\>";
// public final static String tagEnd=
// "\\</\\w+\\>";
// public final static String tagSelfClosing=
// "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)/\\>";
// public final static String htmlEntity=
// "&[a-zA-Z][a-zA-Z0-9]+;";
// public final static Pattern htmlPattern=Pattern.compile(
// "("+tagStart+".*"+tagEnd+")|("+tagSelfClosing+")|("+htmlEntity+")",
// Pattern.DOTALL
// );
//
// /**
// * Will return true if s contains HTML markup tags or entities.
// *
// * @param s String to test
// * @return true if string contains HTML
// */
// public static boolean isHtml(String s) {
// boolean ret=false;
// if (s != null) {
// ret=htmlPattern.matcher(s).find();
// }
// return ret;
// }
//
// }
// Path: test/DetectHtmlTest.java
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.github.DetectHtml;
import org.junit.Test;
public class DetectHtmlTest {
@Test
public void test() {
boolean reportToConsole=false;
boolean fileNotFound=false;
// iterate through HTML files
File[] htmlFiles = new File("testdata/html/").listFiles();
if (reportToConsole)
System.out.println("Testing HTML files\n-----");
for (File htmlFile : htmlFiles) {
fileNotFound=false;
try {
String htmlContent = new Scanner(htmlFile).useDelimiter("\\Z").next(); | boolean isHtml=DetectHtml.isHtml(htmlContent); |
monoid-us/vertx-postgresql | src/main/java/us/monoid/psql/async/Type.java | // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/converter/Converters.java
// public class Converters {
//
// public static final StringConverter stringConverter = new StringConverter();
// public static final NumberConverter shortConverter = new NumberConverter(2);
// public static final NumberConverter intConverter = new NumberConverter(4);
// public static final NumberConverter longConverter = new NumberConverter(8);
// public static final JsonConverter jsonConverter = new JsonConverter();
//
// }
| import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.converter.Converters; | package us.monoid.psql.async;
/** Description of a data type.
* See Types for a list of known types.
* You can create your own user types as well. (later) TODO
* @author beders
*
*/
public class Type {
final String name;
final int oid; // internal identifier in the pg_type table and part of the RowDescription server message
final int size; | // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/converter/Converters.java
// public class Converters {
//
// public static final StringConverter stringConverter = new StringConverter();
// public static final NumberConverter shortConverter = new NumberConverter(2);
// public static final NumberConverter intConverter = new NumberConverter(4);
// public static final NumberConverter longConverter = new NumberConverter(8);
// public static final JsonConverter jsonConverter = new JsonConverter();
//
// }
// Path: src/main/java/us/monoid/psql/async/Type.java
import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.converter.Converters;
package us.monoid.psql.async;
/** Description of a data type.
* See Types for a list of known types.
* You can create your own user types as well. (later) TODO
* @author beders
*
*/
public class Type {
final String name;
final int oid; // internal identifier in the pg_type table and part of the RowDescription server message
final int size; | final Converter converter; |
monoid-us/vertx-postgresql | src/main/java/us/monoid/psql/async/Type.java | // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/converter/Converters.java
// public class Converters {
//
// public static final StringConverter stringConverter = new StringConverter();
// public static final NumberConverter shortConverter = new NumberConverter(2);
// public static final NumberConverter intConverter = new NumberConverter(4);
// public static final NumberConverter longConverter = new NumberConverter(8);
// public static final JsonConverter jsonConverter = new JsonConverter();
//
// }
| import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.converter.Converters; | package us.monoid.psql.async;
/** Description of a data type.
* See Types for a list of known types.
* You can create your own user types as well. (later) TODO
* @author beders
*
*/
public class Type {
final String name;
final int oid; // internal identifier in the pg_type table and part of the RowDescription server message
final int size;
final Converter converter;
public Type(String aName, int anOid, int aSize, Converter aConverter) {
name = aName;
oid = anOid;
size = aSize;
converter = aConverter;
Types.register(this);
}
public Type(String aName, int anOid, int aSize) { | // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/converter/Converters.java
// public class Converters {
//
// public static final StringConverter stringConverter = new StringConverter();
// public static final NumberConverter shortConverter = new NumberConverter(2);
// public static final NumberConverter intConverter = new NumberConverter(4);
// public static final NumberConverter longConverter = new NumberConverter(8);
// public static final JsonConverter jsonConverter = new JsonConverter();
//
// }
// Path: src/main/java/us/monoid/psql/async/Type.java
import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.converter.Converters;
package us.monoid.psql.async;
/** Description of a data type.
* See Types for a list of known types.
* You can create your own user types as well. (later) TODO
* @author beders
*
*/
public class Type {
final String name;
final int oid; // internal identifier in the pg_type table and part of the RowDescription server message
final int size;
final Converter converter;
public Type(String aName, int anOid, int aSize, Converter aConverter) {
name = aName;
oid = anOid;
size = aSize;
converter = aConverter;
Types.register(this);
}
public Type(String aName, int anOid, int aSize) { | this(aName, anOid, aSize, Converters.stringConverter); |
monoid-us/vertx-postgresql | src/test/java/us/monoid/psql/async/message/PasswordTest.java | // Path: src/main/java/us/monoid/psql/async/auth/MD5Digest.java
// public class MD5Digest {
// static final char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//
// private MD5Digest() {
// }
//
// /**
// * Encodes user/password/salt information in the following way: MD5(MD5(password + user) + salt)
// *
// * @param aUser The connecting user.
// *
// * @param aPassword The connecting user's password.
// *
// * @param salt A four-salt sent by the server.
// *
// * @return A 35-byte array, comprising the string "md5" and an MD5 digest.
// */
// public static byte[] encode(String aUser, char[] aPassword, byte salt[]) {
// MessageDigest md;
// byte[] temp_digest, pass_digest;
// byte[] hex_digest = new byte[35];
// byte[] user = toUTF8(aUser);
// byte[] password = toUTF8(new String(aPassword));
//
// try {
// md = MessageDigest.getInstance("MD5");
//
// md.update(password);
// md.update(user);
// temp_digest = md.digest();
//
// bytesToHex(temp_digest, hex_digest, 0);
// md.update(hex_digest, 0, 32);
// md.update(salt);
// pass_digest = md.digest();
//
// bytesToHex(pass_digest, hex_digest, 3);
// hex_digest[0] = (byte) 'm';
// hex_digest[1] = (byte) 'd';
// hex_digest[2] = (byte) '5';
// } catch (Exception e) {
// ; // "MessageDigest failure; " + e
// }
//
// return hex_digest;
// }
//
// private static byte[] toUTF8(String aString) {
// try {
// return aString.getBytes("UTF-8");
// } catch (UnsupportedEncodingException e) {
// }
// throw new IllegalArgumentException("UTF8 encoding not found");
// }
//
// /*
// * Turn 16-byte stream into a human-readable 32-byte hex string
// */
// private static void bytesToHex(byte[] bytes, byte[] hex, int offset) {
// int pos = offset;
//
// for (int i = 0; i < 16; i++) {
// int c = bytes[i] & 0xFF;
// int j = c >> 4;
// hex[pos++] = (byte) lookup[j];
// j = (c & 0xF);
// hex[pos++] = (byte) lookup[j];
// }
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.auth.MD5Digest; | package us.monoid.psql.async.message;
public class PasswordTest {
@Test
public void test() {
Buffer buffer = new Buffer();
Password p = new Password(buffer);
char[] pwd = { 't','e','s','t' };
Buffer b = p.write(pwd);
assertNotNull(b);
assertTrue(b.getByte(0) == 'p');
assertTrue(b.toString().contains("test"));
assertTrue(b.getByte(b.length() - 1) == 0);
assertTrue(b.length() > 0);
}
@Test
public void testMD5() {
Buffer buffer = new Buffer();
Password p = new Password(buffer);
char[] pwd = { 't','e','s','t' };
byte[] salt = { 1, 2, 3, 4 }; | // Path: src/main/java/us/monoid/psql/async/auth/MD5Digest.java
// public class MD5Digest {
// static final char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//
// private MD5Digest() {
// }
//
// /**
// * Encodes user/password/salt information in the following way: MD5(MD5(password + user) + salt)
// *
// * @param aUser The connecting user.
// *
// * @param aPassword The connecting user's password.
// *
// * @param salt A four-salt sent by the server.
// *
// * @return A 35-byte array, comprising the string "md5" and an MD5 digest.
// */
// public static byte[] encode(String aUser, char[] aPassword, byte salt[]) {
// MessageDigest md;
// byte[] temp_digest, pass_digest;
// byte[] hex_digest = new byte[35];
// byte[] user = toUTF8(aUser);
// byte[] password = toUTF8(new String(aPassword));
//
// try {
// md = MessageDigest.getInstance("MD5");
//
// md.update(password);
// md.update(user);
// temp_digest = md.digest();
//
// bytesToHex(temp_digest, hex_digest, 0);
// md.update(hex_digest, 0, 32);
// md.update(salt);
// pass_digest = md.digest();
//
// bytesToHex(pass_digest, hex_digest, 3);
// hex_digest[0] = (byte) 'm';
// hex_digest[1] = (byte) 'd';
// hex_digest[2] = (byte) '5';
// } catch (Exception e) {
// ; // "MessageDigest failure; " + e
// }
//
// return hex_digest;
// }
//
// private static byte[] toUTF8(String aString) {
// try {
// return aString.getBytes("UTF-8");
// } catch (UnsupportedEncodingException e) {
// }
// throw new IllegalArgumentException("UTF8 encoding not found");
// }
//
// /*
// * Turn 16-byte stream into a human-readable 32-byte hex string
// */
// private static void bytesToHex(byte[] bytes, byte[] hex, int offset) {
// int pos = offset;
//
// for (int i = 0; i < 16; i++) {
// int c = bytes[i] & 0xFF;
// int j = c >> 4;
// hex[pos++] = (byte) lookup[j];
// j = (c & 0xF);
// hex[pos++] = (byte) lookup[j];
// }
// }
// }
// Path: src/test/java/us/monoid/psql/async/message/PasswordTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.auth.MD5Digest;
package us.monoid.psql.async.message;
public class PasswordTest {
@Test
public void test() {
Buffer buffer = new Buffer();
Password p = new Password(buffer);
char[] pwd = { 't','e','s','t' };
Buffer b = p.write(pwd);
assertNotNull(b);
assertTrue(b.getByte(0) == 'p');
assertTrue(b.toString().contains("test"));
assertTrue(b.getByte(b.length() - 1) == 0);
assertTrue(b.length() > 0);
}
@Test
public void testMD5() {
Buffer buffer = new Buffer();
Password p = new Password(buffer);
char[] pwd = { 't','e','s','t' };
byte[] salt = { 1, 2, 3, 4 }; | Buffer b = p.write(MD5Digest.encode("test", pwd, salt)); |
monoid-us/vertx-postgresql | src/test/java/us/monoid/psql/async/RowTest.java | // Path: src/main/java/us/monoid/psql/async/message/DataRow.java
// public class DataRow extends BackendMessage {
// // this is possibly a micro-optimization, as finding the data for a column is summing up a few ints
// // we are sacrificing heap for ease-of-use and cpu
// int[] indexes; // for each column, records pointer in buffer where the content is. Makes it easier to read column data which will most likely be done
//
// @Override
// public void setBuffer(Buffer aBuffer) {
// super.setBuffer(aBuffer);
// short col = buffer.getShort(5);
// indexes = new int[col];
// for (int pos = 7,i = 0; i < col; i++) {
// indexes[i] = pos;
// int lenData = buffer.getInt(pos); // length is raw length of column data excluding the length information
// if (lenData == -1) { // NULL value
// pos += 4; // next column starts right away
// } else {
// pos += 4 + lenData;
// }
// }
// }
//
// /** Get a copy of the raw bytes making up the value of that column. Data will be copied for each call to this method.
// *
// * @param column the column index (0-based)
// * @return a buffer with the raw data
// */
// public Buffer getRawBytes(int column) {
// int lenData = buffer.getInt(indexes[column]);
// if (lenData == -1) return new Buffer(0); // NULL
// return buffer.getBuffer(indexes[column] + 4, indexes[column] + 4 + lenData);
// }
//
// public Buffer getBuffer() {
// return buffer;
// }
//
// /** Return the length of the data in the column. If -1, there is no data, return null */
// public int len(int col) {
// return buffer.getInt(indexes[col]);
// }
//
// /** Return the position in the buffer where the data starts. If length is -1, there is no data, return null */
// public int pos(int col) {
// return indexes[col] + 4;
// }
//
// }
| import static org.junit.Assert.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.junit.Test;
import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.message.DataRow; | package us.monoid.psql.async;
public class RowTest {
@Test
public void simpleTest() throws IOException {
Row r = createRow();
String asString = r.asString(0);
assertEquals(asString, "bubu");
int i = r.asInt(1);
assertEquals(42,i);
assertTrue(r.isNull(2));
assertEquals(0L, r.asLong(2));
Buffer t = new Buffer();
r.appendBytes(t, 0);
System.out.println(t.length());
assertEquals(t.getString(0, t.length()), "bubu");
System.out.println(r);
}
public static Row createRow() throws IOException {
Buffer b = createDataRowBuffer(); | // Path: src/main/java/us/monoid/psql/async/message/DataRow.java
// public class DataRow extends BackendMessage {
// // this is possibly a micro-optimization, as finding the data for a column is summing up a few ints
// // we are sacrificing heap for ease-of-use and cpu
// int[] indexes; // for each column, records pointer in buffer where the content is. Makes it easier to read column data which will most likely be done
//
// @Override
// public void setBuffer(Buffer aBuffer) {
// super.setBuffer(aBuffer);
// short col = buffer.getShort(5);
// indexes = new int[col];
// for (int pos = 7,i = 0; i < col; i++) {
// indexes[i] = pos;
// int lenData = buffer.getInt(pos); // length is raw length of column data excluding the length information
// if (lenData == -1) { // NULL value
// pos += 4; // next column starts right away
// } else {
// pos += 4 + lenData;
// }
// }
// }
//
// /** Get a copy of the raw bytes making up the value of that column. Data will be copied for each call to this method.
// *
// * @param column the column index (0-based)
// * @return a buffer with the raw data
// */
// public Buffer getRawBytes(int column) {
// int lenData = buffer.getInt(indexes[column]);
// if (lenData == -1) return new Buffer(0); // NULL
// return buffer.getBuffer(indexes[column] + 4, indexes[column] + 4 + lenData);
// }
//
// public Buffer getBuffer() {
// return buffer;
// }
//
// /** Return the length of the data in the column. If -1, there is no data, return null */
// public int len(int col) {
// return buffer.getInt(indexes[col]);
// }
//
// /** Return the position in the buffer where the data starts. If length is -1, there is no data, return null */
// public int pos(int col) {
// return indexes[col] + 4;
// }
//
// }
// Path: src/test/java/us/monoid/psql/async/RowTest.java
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.junit.Test;
import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.message.DataRow;
package us.monoid.psql.async;
public class RowTest {
@Test
public void simpleTest() throws IOException {
Row r = createRow();
String asString = r.asString(0);
assertEquals(asString, "bubu");
int i = r.asInt(1);
assertEquals(42,i);
assertTrue(r.isNull(2));
assertEquals(0L, r.asLong(2));
Buffer t = new Buffer();
r.appendBytes(t, 0);
System.out.println(t.length());
assertEquals(t.getString(0, t.length()), "bubu");
System.out.println(r);
}
public static Row createRow() throws IOException {
Buffer b = createDataRowBuffer(); | DataRow dr = new DataRow(); |
monoid-us/vertx-postgresql | src/main/java/us/monoid/psql/async/message/RowDescription.java | // Path: src/main/java/us/monoid/psql/async/Columns.java
// public class Columns {
// final Column[] columns;
//
// public Columns(short columnCount) {
// columns = new Column[columnCount];
// }
//
// /** Get a column by index. Note that this is a zero-based index, i.e. first column is getColumn(0) */
// public Column get(int col) {
// return columns[col];
// }
//
// /** Get a column by name. */
// public Column get(String name) {
// for (Column c : columns) {
// if (c.name.equals(name)) {
// return c;
// }
// }
// return null;
// }
//
// /** Get the index of the column by name. Returns -1 if column is not found.
// * You can use this method with the various Row methods to retrieve the value of a column
// * {@code row.asString(row.columns().index("name")); }
// **/
// public int index(String name) {
// for (int i = 0; i < columns.length; i++) {
// if (columns[i].name.equals(name)) {
// return i;
// }
// }
// return -1;
// }
//
// public static class Column {
// public final String name;
// public final Type type;
// int oid; // can be removed again once we have all types supported
// private final short formatCode;
//
// Column(String aName, Type aType, int anOid, short aFormatCode) {
// name = aName;
// type = aType;
// oid = anOid;
// formatCode = aFormatCode;
// }
//
// public boolean isBinary() {
// return formatCode == 1;
// }
//
// }
//
// /** Add column information. This method is used internally */
// public void setColumn(int i, String name, int type, short formatCode) {
// columns[i] = new Column(name, Types.lookup(type), type, formatCode);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for (Column c : columns) {
// sb.append(c.name).append(" | ").append(c.type.name).append(" | ").append(c.formatCode == 0 ? "text" : "binary").append('\n');
// }
// return sb.toString();
// }
//
// /** Return number of columns */
// public int count() {
// return columns.length;
// }
//
// // // thanks to Mauricio Linhares for putting this list together.
// // replaced by a more flexible type system
// // enum Type {
// // Bigserial(20), BigserialArray(1016), Char(18), CharArray(1002), Smallint(21), SmallintArray(1005), Integer(23), IntegerArray(1007), Numeric(
// // 1700),
// // NumericArray(1231), Real(700), RealArray(1021), Double(701), DoubleArray(1022), Serial(23), Bpchar(1042), BpcharArray(1014), Varchar(
// // 1043),
// // VarcharArray(1015), Text(25), TextArray(1009), Timestamp(1114), TimestampArray(1115), TimestampWithTimezone(1184), TimestampWithTimezoneArray(
// // 1185), Date(1082), DateArray(1182), Time(1083), TimeArray(1183), TimeWithTimezone(1266), TimeWithTimezoneArray(1270), Interval(1186), IntervalArray(
// // 1187), Boolean(16), BooleanArray(1000), OID(26), OIDArray(1028),
// //
// // ByteA(17), ByteA_Array(1001),
// //
// // MoneyArray(791), NameArray(1003), UUIDArray(2951), XMLArray(143), Unknown(0);
// //
// // int typeID; // use catalog pg_type to
// //
// // Type(int aTypeID) {
// // typeID = aTypeID;
// // }
// //
// // public static Type getType(int type) {
// // for (Type t : values()) { // yes, we could use a Map for that, but this isn't performance critical as it will be called only once for each type per query result
// // if (t.typeID == type) {
// // return t;
// // }
// // }
// // return Unknown;
// // }
// //
// // }
//
// }
| import us.monoid.psql.async.Columns; | package us.monoid.psql.async.message;
/** See Postgresl Manual 46.5 Message Formats.
*
* @author beders
*
*/
public class RowDescription extends BackendMessage {
public short columnCount() {
return buffer.getShort(5); // can be 0!
}
| // Path: src/main/java/us/monoid/psql/async/Columns.java
// public class Columns {
// final Column[] columns;
//
// public Columns(short columnCount) {
// columns = new Column[columnCount];
// }
//
// /** Get a column by index. Note that this is a zero-based index, i.e. first column is getColumn(0) */
// public Column get(int col) {
// return columns[col];
// }
//
// /** Get a column by name. */
// public Column get(String name) {
// for (Column c : columns) {
// if (c.name.equals(name)) {
// return c;
// }
// }
// return null;
// }
//
// /** Get the index of the column by name. Returns -1 if column is not found.
// * You can use this method with the various Row methods to retrieve the value of a column
// * {@code row.asString(row.columns().index("name")); }
// **/
// public int index(String name) {
// for (int i = 0; i < columns.length; i++) {
// if (columns[i].name.equals(name)) {
// return i;
// }
// }
// return -1;
// }
//
// public static class Column {
// public final String name;
// public final Type type;
// int oid; // can be removed again once we have all types supported
// private final short formatCode;
//
// Column(String aName, Type aType, int anOid, short aFormatCode) {
// name = aName;
// type = aType;
// oid = anOid;
// formatCode = aFormatCode;
// }
//
// public boolean isBinary() {
// return formatCode == 1;
// }
//
// }
//
// /** Add column information. This method is used internally */
// public void setColumn(int i, String name, int type, short formatCode) {
// columns[i] = new Column(name, Types.lookup(type), type, formatCode);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for (Column c : columns) {
// sb.append(c.name).append(" | ").append(c.type.name).append(" | ").append(c.formatCode == 0 ? "text" : "binary").append('\n');
// }
// return sb.toString();
// }
//
// /** Return number of columns */
// public int count() {
// return columns.length;
// }
//
// // // thanks to Mauricio Linhares for putting this list together.
// // replaced by a more flexible type system
// // enum Type {
// // Bigserial(20), BigserialArray(1016), Char(18), CharArray(1002), Smallint(21), SmallintArray(1005), Integer(23), IntegerArray(1007), Numeric(
// // 1700),
// // NumericArray(1231), Real(700), RealArray(1021), Double(701), DoubleArray(1022), Serial(23), Bpchar(1042), BpcharArray(1014), Varchar(
// // 1043),
// // VarcharArray(1015), Text(25), TextArray(1009), Timestamp(1114), TimestampArray(1115), TimestampWithTimezone(1184), TimestampWithTimezoneArray(
// // 1185), Date(1082), DateArray(1182), Time(1083), TimeArray(1183), TimeWithTimezone(1266), TimeWithTimezoneArray(1270), Interval(1186), IntervalArray(
// // 1187), Boolean(16), BooleanArray(1000), OID(26), OIDArray(1028),
// //
// // ByteA(17), ByteA_Array(1001),
// //
// // MoneyArray(791), NameArray(1003), UUIDArray(2951), XMLArray(143), Unknown(0);
// //
// // int typeID; // use catalog pg_type to
// //
// // Type(int aTypeID) {
// // typeID = aTypeID;
// // }
// //
// // public static Type getType(int type) {
// // for (Type t : values()) { // yes, we could use a Map for that, but this isn't performance critical as it will be called only once for each type per query result
// // if (t.typeID == type) {
// // return t;
// // }
// // }
// // return Unknown;
// // }
// //
// // }
//
// }
// Path: src/main/java/us/monoid/psql/async/message/RowDescription.java
import us.monoid.psql.async.Columns;
package us.monoid.psql.async.message;
/** See Postgresl Manual 46.5 Message Formats.
*
* @author beders
*
*/
public class RowDescription extends BackendMessage {
public short columnCount() {
return buffer.getShort(5); // can be 0!
}
| public Columns readColumns() { |
monoid-us/vertx-postgresql | src/main/java/us/monoid/psql/async/Types.java | // Path: src/main/java/us/monoid/psql/async/converter/Converters.java
// public class Converters {
//
// public static final StringConverter stringConverter = new StringConverter();
// public static final NumberConverter shortConverter = new NumberConverter(2);
// public static final NumberConverter intConverter = new NumberConverter(4);
// public static final NumberConverter longConverter = new NumberConverter(8);
// public static final JsonConverter jsonConverter = new JsonConverter();
//
// }
| import java.util.HashMap;
import java.util.Map;
import us.monoid.psql.async.converter.Converters; | package us.monoid.psql.async;
/**
* Built-in PostgresQL types.
*
* @author beders
*
*/
// Some types are commented out as they are used internally mostly
/* Created via the following SQL:
* SELECT n.nspname AS schema,
t.oid,
pg_catalog.format_type ( t.oid, NULL ) AS name,
t.typname AS internal_name,
CASE
WHEN t.typrelid != 0
THEN CAST ( 'tuple' AS pg_catalog.text )
WHEN t.typlen < 0
THEN CAST ( 'var' AS pg_catalog.text )
ELSE CAST ( t.typlen AS pg_catalog.text )
END AS size,
pg_catalog.array_to_string (
ARRAY( SELECT e.enumlabel
FROM pg_catalog.pg_enum e
WHERE e.enumtypid = t.oid
ORDER BY e.oid ), E'\n'
) AS elements,
pg_catalog.obj_description ( t.oid, 'pg_type' ) AS description
FROM pg_catalog.pg_type t
LEFT JOIN pg_catalog.pg_namespace n
ON n.oid = t.typnamespace
WHERE ( t.typrelid = 0
OR ( SELECT c.relkind = 'c'
FROM pg_catalog.pg_class c
WHERE c.oid = t.typrelid
)
)
AND NOT EXISTS
( SELECT 1
FROM pg_catalog.pg_type el
WHERE el.oid = t.typelem
AND el.typarray = t.oid
)
AND pg_catalog.pg_type_is_visible ( t.oid )
ORDER BY 1, 2;
*
*
*/
public class Types {
static Map<Integer,Type> types = new HashMap<>();
// public static final Type "Any" = new Type(""any"",2276,4); //
public static final Type Abstime = new Type("abstime", 702, 4); // absolute, limited-range date and time (Unix system time)
public static final Type AbstimeArray = new Type("abstime[]", 1023, -1); //
public static final Type Aclitem = new Type("aclitem", 1033, 12); // access control list
public static final Type AclitemArray = new Type("aclitem[]", 1034, -1); //
// public static final Type Anyarray = new Type("anyarray",2277,-1); //
// public static final Type Anyelement = new Type("anyelement",2283,4); //
// public static final Type Anyenum = new Type("anyenum",3500,4); //
// public static final Type Anynonarray = new Type("anynonarray",2776,4); //
// public static final Type Anyrange = new Type("anyrange",3831,-1); // | // Path: src/main/java/us/monoid/psql/async/converter/Converters.java
// public class Converters {
//
// public static final StringConverter stringConverter = new StringConverter();
// public static final NumberConverter shortConverter = new NumberConverter(2);
// public static final NumberConverter intConverter = new NumberConverter(4);
// public static final NumberConverter longConverter = new NumberConverter(8);
// public static final JsonConverter jsonConverter = new JsonConverter();
//
// }
// Path: src/main/java/us/monoid/psql/async/Types.java
import java.util.HashMap;
import java.util.Map;
import us.monoid.psql.async.converter.Converters;
package us.monoid.psql.async;
/**
* Built-in PostgresQL types.
*
* @author beders
*
*/
// Some types are commented out as they are used internally mostly
/* Created via the following SQL:
* SELECT n.nspname AS schema,
t.oid,
pg_catalog.format_type ( t.oid, NULL ) AS name,
t.typname AS internal_name,
CASE
WHEN t.typrelid != 0
THEN CAST ( 'tuple' AS pg_catalog.text )
WHEN t.typlen < 0
THEN CAST ( 'var' AS pg_catalog.text )
ELSE CAST ( t.typlen AS pg_catalog.text )
END AS size,
pg_catalog.array_to_string (
ARRAY( SELECT e.enumlabel
FROM pg_catalog.pg_enum e
WHERE e.enumtypid = t.oid
ORDER BY e.oid ), E'\n'
) AS elements,
pg_catalog.obj_description ( t.oid, 'pg_type' ) AS description
FROM pg_catalog.pg_type t
LEFT JOIN pg_catalog.pg_namespace n
ON n.oid = t.typnamespace
WHERE ( t.typrelid = 0
OR ( SELECT c.relkind = 'c'
FROM pg_catalog.pg_class c
WHERE c.oid = t.typrelid
)
)
AND NOT EXISTS
( SELECT 1
FROM pg_catalog.pg_type el
WHERE el.oid = t.typelem
AND el.typarray = t.oid
)
AND pg_catalog.pg_type_is_visible ( t.oid )
ORDER BY 1, 2;
*
*
*/
public class Types {
static Map<Integer,Type> types = new HashMap<>();
// public static final Type "Any" = new Type(""any"",2276,4); //
public static final Type Abstime = new Type("abstime", 702, 4); // absolute, limited-range date and time (Unix system time)
public static final Type AbstimeArray = new Type("abstime[]", 1023, -1); //
public static final Type Aclitem = new Type("aclitem", 1033, 12); // access control list
public static final Type AclitemArray = new Type("aclitem[]", 1034, -1); //
// public static final Type Anyarray = new Type("anyarray",2277,-1); //
// public static final Type Anyelement = new Type("anyelement",2283,4); //
// public static final Type Anyenum = new Type("anyenum",3500,4); //
// public static final Type Anynonarray = new Type("anynonarray",2776,4); //
// public static final Type Anyrange = new Type("anyrange",3831,-1); // | public static final Type Bigint = new Type("bigint", 20, 8, Converters.longConverter); // ~18 digit integer, 8-byte storage |
monoid-us/vertx-postgresql | src/main/java/us/monoid/psql/async/promise/Promises.java | // Path: src/main/java/us/monoid/psql/async/promise/Promise.java
// abstract class DoneCallback<V> {
// public abstract void onFulfilled(V value);
//
// public void onRejected(Throwable reason) {
// Promises.propagate(reason);
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import us.monoid.psql.async.promise.Promise.DoneCallback; | package us.monoid.psql.async.promise;
/** Composing promises etc.
*
* @author beders
* @author tbroyer
*/
public final class Promises {
/**
* This is the same as Guava's Throwables#propagate, but we don't want a
* mandatory dependency on Guava.
*/
static RuntimeException propagate(Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
throw new RuntimeException(t);
}
public static <V> Promise<V> fulfilled(final V value) {
return new Promise<V>() {
@Override
public <R> Promise<R> then(Callback<? super V, R> callback) {
try {
return callback.onFulfilled(value);
} catch (Throwable t) {
return rejected(t);
}
}
@Override
public <R> Promise<R> then(ImmediateCallback<? super V, R> callback) {
try {
return fulfilled(callback.onFulfilled(value));
} catch (Throwable t) {
return rejected(t);
}
}
@Override | // Path: src/main/java/us/monoid/psql/async/promise/Promise.java
// abstract class DoneCallback<V> {
// public abstract void onFulfilled(V value);
//
// public void onRejected(Throwable reason) {
// Promises.propagate(reason);
// }
// }
// Path: src/main/java/us/monoid/psql/async/promise/Promises.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import us.monoid.psql.async.promise.Promise.DoneCallback;
package us.monoid.psql.async.promise;
/** Composing promises etc.
*
* @author beders
* @author tbroyer
*/
public final class Promises {
/**
* This is the same as Guava's Throwables#propagate, but we don't want a
* mandatory dependency on Guava.
*/
static RuntimeException propagate(Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
throw new RuntimeException(t);
}
public static <V> Promise<V> fulfilled(final V value) {
return new Promise<V>() {
@Override
public <R> Promise<R> then(Callback<? super V, R> callback) {
try {
return callback.onFulfilled(value);
} catch (Throwable t) {
return rejected(t);
}
}
@Override
public <R> Promise<R> then(ImmediateCallback<? super V, R> callback) {
try {
return fulfilled(callback.onFulfilled(value));
} catch (Throwable t) {
return rejected(t);
}
}
@Override | public void done(DoneCallback<? super V> callback) { |
monoid-us/vertx-postgresql | src/main/java/us/monoid/psql/async/Row.java | // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/message/DataRow.java
// public class DataRow extends BackendMessage {
// // this is possibly a micro-optimization, as finding the data for a column is summing up a few ints
// // we are sacrificing heap for ease-of-use and cpu
// int[] indexes; // for each column, records pointer in buffer where the content is. Makes it easier to read column data which will most likely be done
//
// @Override
// public void setBuffer(Buffer aBuffer) {
// super.setBuffer(aBuffer);
// short col = buffer.getShort(5);
// indexes = new int[col];
// for (int pos = 7,i = 0; i < col; i++) {
// indexes[i] = pos;
// int lenData = buffer.getInt(pos); // length is raw length of column data excluding the length information
// if (lenData == -1) { // NULL value
// pos += 4; // next column starts right away
// } else {
// pos += 4 + lenData;
// }
// }
// }
//
// /** Get a copy of the raw bytes making up the value of that column. Data will be copied for each call to this method.
// *
// * @param column the column index (0-based)
// * @return a buffer with the raw data
// */
// public Buffer getRawBytes(int column) {
// int lenData = buffer.getInt(indexes[column]);
// if (lenData == -1) return new Buffer(0); // NULL
// return buffer.getBuffer(indexes[column] + 4, indexes[column] + 4 + lenData);
// }
//
// public Buffer getBuffer() {
// return buffer;
// }
//
// /** Return the length of the data in the column. If -1, there is no data, return null */
// public int len(int col) {
// return buffer.getInt(indexes[col]);
// }
//
// /** Return the position in the buffer where the data starts. If length is -1, there is no data, return null */
// public int pos(int col) {
// return indexes[col] + 4;
// }
//
// }
| import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.message.DataRow; | package us.monoid.psql.async;
/** Represents a row of data. Uses the fly-weight pattern, i.e. don't hold onto instances of this class. Just use the row instance passed into
* your ResultListener to copy the data.
*
* For each row, access the data for each column using one of the asXxxx methods. You can either use the zero-based column index or the column name.
*
* Row does some conversions for you. If you call asString(..) on a value that is a number, it will be converted to a String.
* However, trying to call asInt, asLong, asShort on a value that is not parseable will result in a NumberFormatException
*
* Also note the various implementations of ResultListener which makes retrieving data a bit easier in may cases
* @see us.monoid.psql.async.callback.ResultListener
* @see us.monoid.psql.async.callback.SingleResult
* @see us.monoid.psql.async.callback.JsonResult
**/
public class Row {
Columns columns; | // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/message/DataRow.java
// public class DataRow extends BackendMessage {
// // this is possibly a micro-optimization, as finding the data for a column is summing up a few ints
// // we are sacrificing heap for ease-of-use and cpu
// int[] indexes; // for each column, records pointer in buffer where the content is. Makes it easier to read column data which will most likely be done
//
// @Override
// public void setBuffer(Buffer aBuffer) {
// super.setBuffer(aBuffer);
// short col = buffer.getShort(5);
// indexes = new int[col];
// for (int pos = 7,i = 0; i < col; i++) {
// indexes[i] = pos;
// int lenData = buffer.getInt(pos); // length is raw length of column data excluding the length information
// if (lenData == -1) { // NULL value
// pos += 4; // next column starts right away
// } else {
// pos += 4 + lenData;
// }
// }
// }
//
// /** Get a copy of the raw bytes making up the value of that column. Data will be copied for each call to this method.
// *
// * @param column the column index (0-based)
// * @return a buffer with the raw data
// */
// public Buffer getRawBytes(int column) {
// int lenData = buffer.getInt(indexes[column]);
// if (lenData == -1) return new Buffer(0); // NULL
// return buffer.getBuffer(indexes[column] + 4, indexes[column] + 4 + lenData);
// }
//
// public Buffer getBuffer() {
// return buffer;
// }
//
// /** Return the length of the data in the column. If -1, there is no data, return null */
// public int len(int col) {
// return buffer.getInt(indexes[col]);
// }
//
// /** Return the position in the buffer where the data starts. If length is -1, there is no data, return null */
// public int pos(int col) {
// return indexes[col] + 4;
// }
//
// }
// Path: src/main/java/us/monoid/psql/async/Row.java
import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.message.DataRow;
package us.monoid.psql.async;
/** Represents a row of data. Uses the fly-weight pattern, i.e. don't hold onto instances of this class. Just use the row instance passed into
* your ResultListener to copy the data.
*
* For each row, access the data for each column using one of the asXxxx methods. You can either use the zero-based column index or the column name.
*
* Row does some conversions for you. If you call asString(..) on a value that is a number, it will be converted to a String.
* However, trying to call asInt, asLong, asShort on a value that is not parseable will result in a NumberFormatException
*
* Also note the various implementations of ResultListener which makes retrieving data a bit easier in may cases
* @see us.monoid.psql.async.callback.ResultListener
* @see us.monoid.psql.async.callback.SingleResult
* @see us.monoid.psql.async.callback.JsonResult
**/
public class Row {
Columns columns; | DataRow row; |
monoid-us/vertx-postgresql | src/main/java/us/monoid/psql/async/Row.java | // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/message/DataRow.java
// public class DataRow extends BackendMessage {
// // this is possibly a micro-optimization, as finding the data for a column is summing up a few ints
// // we are sacrificing heap for ease-of-use and cpu
// int[] indexes; // for each column, records pointer in buffer where the content is. Makes it easier to read column data which will most likely be done
//
// @Override
// public void setBuffer(Buffer aBuffer) {
// super.setBuffer(aBuffer);
// short col = buffer.getShort(5);
// indexes = new int[col];
// for (int pos = 7,i = 0; i < col; i++) {
// indexes[i] = pos;
// int lenData = buffer.getInt(pos); // length is raw length of column data excluding the length information
// if (lenData == -1) { // NULL value
// pos += 4; // next column starts right away
// } else {
// pos += 4 + lenData;
// }
// }
// }
//
// /** Get a copy of the raw bytes making up the value of that column. Data will be copied for each call to this method.
// *
// * @param column the column index (0-based)
// * @return a buffer with the raw data
// */
// public Buffer getRawBytes(int column) {
// int lenData = buffer.getInt(indexes[column]);
// if (lenData == -1) return new Buffer(0); // NULL
// return buffer.getBuffer(indexes[column] + 4, indexes[column] + 4 + lenData);
// }
//
// public Buffer getBuffer() {
// return buffer;
// }
//
// /** Return the length of the data in the column. If -1, there is no data, return null */
// public int len(int col) {
// return buffer.getInt(indexes[col]);
// }
//
// /** Return the position in the buffer where the data starts. If length is -1, there is no data, return null */
// public int pos(int col) {
// return indexes[col] + 4;
// }
//
// }
| import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.message.DataRow; | int col = columns().index(colName);
return asFloat(col);
}
public double asDouble(String colName) {
int col = columns().index(colName);
return asDouble(col);
}
/** Get a copy of the bytes for the requested column */
public Buffer asBuffer(String colName) {
int col = columns().index(colName);
return asBuffer(col);
}
/** Return the length of a column in bytes. Might return -1 in which case the value is NULL */
public int length(int col) {
return row.len(col);
}
/** Append bytes for column 'col' to target buffer. Return the number of bytes written.
* @return number of bytes copied
* This should work for Strings / varchar / character varying if both buffers use UTF8 as String encoding
*/
public int appendBytes(Buffer target, int col) {
target.appendBuffer(row.getRawBytes(col)); // can't get deep enough access to Netty to use buffer transfer, too bad
return row.len(col);
}
| // Path: src/main/java/us/monoid/psql/async/converter/Converter.java
// public abstract class Converter {
// public abstract String toString(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract boolean toBoolean(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract int toInt(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract long toLong(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract double toDouble(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract float toFloat(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract short toShort(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract char toChar(Buffer buffer, int pos, int len, boolean isBinary);
// public abstract Object toObject(Buffer buffer, int pos, int len, boolean isBinary);
// }
//
// Path: src/main/java/us/monoid/psql/async/message/DataRow.java
// public class DataRow extends BackendMessage {
// // this is possibly a micro-optimization, as finding the data for a column is summing up a few ints
// // we are sacrificing heap for ease-of-use and cpu
// int[] indexes; // for each column, records pointer in buffer where the content is. Makes it easier to read column data which will most likely be done
//
// @Override
// public void setBuffer(Buffer aBuffer) {
// super.setBuffer(aBuffer);
// short col = buffer.getShort(5);
// indexes = new int[col];
// for (int pos = 7,i = 0; i < col; i++) {
// indexes[i] = pos;
// int lenData = buffer.getInt(pos); // length is raw length of column data excluding the length information
// if (lenData == -1) { // NULL value
// pos += 4; // next column starts right away
// } else {
// pos += 4 + lenData;
// }
// }
// }
//
// /** Get a copy of the raw bytes making up the value of that column. Data will be copied for each call to this method.
// *
// * @param column the column index (0-based)
// * @return a buffer with the raw data
// */
// public Buffer getRawBytes(int column) {
// int lenData = buffer.getInt(indexes[column]);
// if (lenData == -1) return new Buffer(0); // NULL
// return buffer.getBuffer(indexes[column] + 4, indexes[column] + 4 + lenData);
// }
//
// public Buffer getBuffer() {
// return buffer;
// }
//
// /** Return the length of the data in the column. If -1, there is no data, return null */
// public int len(int col) {
// return buffer.getInt(indexes[col]);
// }
//
// /** Return the position in the buffer where the data starts. If length is -1, there is no data, return null */
// public int pos(int col) {
// return indexes[col] + 4;
// }
//
// }
// Path: src/main/java/us/monoid/psql/async/Row.java
import org.vertx.java.core.buffer.Buffer;
import us.monoid.psql.async.converter.Converter;
import us.monoid.psql.async.message.DataRow;
int col = columns().index(colName);
return asFloat(col);
}
public double asDouble(String colName) {
int col = columns().index(colName);
return asDouble(col);
}
/** Get a copy of the bytes for the requested column */
public Buffer asBuffer(String colName) {
int col = columns().index(colName);
return asBuffer(col);
}
/** Return the length of a column in bytes. Might return -1 in which case the value is NULL */
public int length(int col) {
return row.len(col);
}
/** Append bytes for column 'col' to target buffer. Return the number of bytes written.
* @return number of bytes copied
* This should work for Strings / varchar / character varying if both buffers use UTF8 as String encoding
*/
public int appendBytes(Buffer target, int col) {
target.appendBuffer(row.getRawBytes(col)); // can't get deep enough access to Netty to use buffer transfer, too bad
return row.len(col);
}
| private Converter converter(int col) { |
MinecraftForge/ForgeGradle | src/mcp/java/net/minecraftforge/gradle/mcp/function/DownloadVersionJSONFunction.java | // Path: src/mcp/java/net/minecraftforge/gradle/mcp/util/MCPEnvironment.java
// public class MCPEnvironment {
//
// private final MCPRuntime runtime;
// public final Project project;
// public final String side;
// public Logger logger;
// private final MinecraftVersion mcVersion;
// private final JavaLanguageVersion javaVersion;
//
// public MCPEnvironment(MCPRuntime runtime, String mcVersion, int javaVersion, String side) {
// this.runtime = runtime;
// this.project = runtime.project;
// this.side = side;
// this.mcVersion = MinecraftVersion.from(mcVersion);
// this.javaVersion = JavaLanguageVersion.of(javaVersion);
// }
//
// public Map<String, Object> getArguments() {
// return runtime.currentStep.arguments;
// }
//
// public File getWorkingDir() {
// return runtime.currentStep.workingDirectory;
// }
//
// public File getConfigZip() {
// return runtime.zipFile;
// }
//
// public File getFile(String name) {
// File file = new File(name);
// if (file.getAbsolutePath().equals(name)) { // If this is already an absolute path, don't mess with it
// return file;
// } else if (name.startsWith("/")) {
// return new File(runtime.mcpDirectory, name);
// } else {
// return new File(getWorkingDir(), name);
// }
// }
//
// public File getStepOutput(String name) {
// MCPRuntime.Step step = runtime.steps.get(name);
// if (step == null) {
// throw new IllegalArgumentException("Could not find a step named " + name);
// }
// if (step.output == null) {
// throw new IllegalArgumentException("Attempted to get the output of an unexecuted step: " + name);
// }
// return step.output;
// }
//
// public MinecraftVersion getMinecraftVersion() {
// return this.mcVersion;
// }
//
// /**
// * @return The Java version used to run the MCP steps (decompilation, etc.)
// */
// public JavaLanguageVersion getJavaVersion() {
// return javaVersion;
// }
// }
| import net.minecraftforge.gradle.mcp.util.MCPEnvironment;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader; | /*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.mcp.function;
class DownloadVersionJSONFunction extends DownloadFileFunction {
private static final String DEFAULT_OUTPUT = "version.json";
public DownloadVersionJSONFunction() {
super(env -> DEFAULT_OUTPUT, DownloadVersionJSONFunction::getDownloadInfo);
}
| // Path: src/mcp/java/net/minecraftforge/gradle/mcp/util/MCPEnvironment.java
// public class MCPEnvironment {
//
// private final MCPRuntime runtime;
// public final Project project;
// public final String side;
// public Logger logger;
// private final MinecraftVersion mcVersion;
// private final JavaLanguageVersion javaVersion;
//
// public MCPEnvironment(MCPRuntime runtime, String mcVersion, int javaVersion, String side) {
// this.runtime = runtime;
// this.project = runtime.project;
// this.side = side;
// this.mcVersion = MinecraftVersion.from(mcVersion);
// this.javaVersion = JavaLanguageVersion.of(javaVersion);
// }
//
// public Map<String, Object> getArguments() {
// return runtime.currentStep.arguments;
// }
//
// public File getWorkingDir() {
// return runtime.currentStep.workingDirectory;
// }
//
// public File getConfigZip() {
// return runtime.zipFile;
// }
//
// public File getFile(String name) {
// File file = new File(name);
// if (file.getAbsolutePath().equals(name)) { // If this is already an absolute path, don't mess with it
// return file;
// } else if (name.startsWith("/")) {
// return new File(runtime.mcpDirectory, name);
// } else {
// return new File(getWorkingDir(), name);
// }
// }
//
// public File getStepOutput(String name) {
// MCPRuntime.Step step = runtime.steps.get(name);
// if (step == null) {
// throw new IllegalArgumentException("Could not find a step named " + name);
// }
// if (step.output == null) {
// throw new IllegalArgumentException("Attempted to get the output of an unexecuted step: " + name);
// }
// return step.output;
// }
//
// public MinecraftVersion getMinecraftVersion() {
// return this.mcVersion;
// }
//
// /**
// * @return The Java version used to run the MCP steps (decompilation, etc.)
// */
// public JavaLanguageVersion getJavaVersion() {
// return javaVersion;
// }
// }
// Path: src/mcp/java/net/minecraftforge/gradle/mcp/function/DownloadVersionJSONFunction.java
import net.minecraftforge.gradle.mcp.util.MCPEnvironment;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.mcp.function;
class DownloadVersionJSONFunction extends DownloadFileFunction {
private static final String DEFAULT_OUTPUT = "version.json";
public DownloadVersionJSONFunction() {
super(env -> DEFAULT_OUTPUT, DownloadVersionJSONFunction::getDownloadInfo);
}
| private static DownloadInfo getDownloadInfo(MCPEnvironment environment) { |
MinecraftForge/ForgeGradle | src/mcp/java/net/minecraftforge/gradle/mcp/function/DownloadCoreFunction.java | // Path: src/mcp/java/net/minecraftforge/gradle/mcp/util/MCPEnvironment.java
// public class MCPEnvironment {
//
// private final MCPRuntime runtime;
// public final Project project;
// public final String side;
// public Logger logger;
// private final MinecraftVersion mcVersion;
// private final JavaLanguageVersion javaVersion;
//
// public MCPEnvironment(MCPRuntime runtime, String mcVersion, int javaVersion, String side) {
// this.runtime = runtime;
// this.project = runtime.project;
// this.side = side;
// this.mcVersion = MinecraftVersion.from(mcVersion);
// this.javaVersion = JavaLanguageVersion.of(javaVersion);
// }
//
// public Map<String, Object> getArguments() {
// return runtime.currentStep.arguments;
// }
//
// public File getWorkingDir() {
// return runtime.currentStep.workingDirectory;
// }
//
// public File getConfigZip() {
// return runtime.zipFile;
// }
//
// public File getFile(String name) {
// File file = new File(name);
// if (file.getAbsolutePath().equals(name)) { // If this is already an absolute path, don't mess with it
// return file;
// } else if (name.startsWith("/")) {
// return new File(runtime.mcpDirectory, name);
// } else {
// return new File(getWorkingDir(), name);
// }
// }
//
// public File getStepOutput(String name) {
// MCPRuntime.Step step = runtime.steps.get(name);
// if (step == null) {
// throw new IllegalArgumentException("Could not find a step named " + name);
// }
// if (step.output == null) {
// throw new IllegalArgumentException("Attempted to get the output of an unexecuted step: " + name);
// }
// return step.output;
// }
//
// public MinecraftVersion getMinecraftVersion() {
// return this.mcVersion;
// }
//
// /**
// * @return The Java version used to run the MCP steps (decompilation, etc.)
// */
// public JavaLanguageVersion getJavaVersion() {
// return javaVersion;
// }
// }
| import net.minecraftforge.gradle.mcp.util.MCPEnvironment;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader; | /*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.mcp.function;
class DownloadCoreFunction extends DownloadFileFunction {
DownloadCoreFunction(String artifact, String ext) {
super(env -> artifact + '.' + ext, env -> getDownloadInfo(env, artifact, ext));
}
| // Path: src/mcp/java/net/minecraftforge/gradle/mcp/util/MCPEnvironment.java
// public class MCPEnvironment {
//
// private final MCPRuntime runtime;
// public final Project project;
// public final String side;
// public Logger logger;
// private final MinecraftVersion mcVersion;
// private final JavaLanguageVersion javaVersion;
//
// public MCPEnvironment(MCPRuntime runtime, String mcVersion, int javaVersion, String side) {
// this.runtime = runtime;
// this.project = runtime.project;
// this.side = side;
// this.mcVersion = MinecraftVersion.from(mcVersion);
// this.javaVersion = JavaLanguageVersion.of(javaVersion);
// }
//
// public Map<String, Object> getArguments() {
// return runtime.currentStep.arguments;
// }
//
// public File getWorkingDir() {
// return runtime.currentStep.workingDirectory;
// }
//
// public File getConfigZip() {
// return runtime.zipFile;
// }
//
// public File getFile(String name) {
// File file = new File(name);
// if (file.getAbsolutePath().equals(name)) { // If this is already an absolute path, don't mess with it
// return file;
// } else if (name.startsWith("/")) {
// return new File(runtime.mcpDirectory, name);
// } else {
// return new File(getWorkingDir(), name);
// }
// }
//
// public File getStepOutput(String name) {
// MCPRuntime.Step step = runtime.steps.get(name);
// if (step == null) {
// throw new IllegalArgumentException("Could not find a step named " + name);
// }
// if (step.output == null) {
// throw new IllegalArgumentException("Attempted to get the output of an unexecuted step: " + name);
// }
// return step.output;
// }
//
// public MinecraftVersion getMinecraftVersion() {
// return this.mcVersion;
// }
//
// /**
// * @return The Java version used to run the MCP steps (decompilation, etc.)
// */
// public JavaLanguageVersion getJavaVersion() {
// return javaVersion;
// }
// }
// Path: src/mcp/java/net/minecraftforge/gradle/mcp/function/DownloadCoreFunction.java
import net.minecraftforge.gradle.mcp.util.MCPEnvironment;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.mcp.function;
class DownloadCoreFunction extends DownloadFileFunction {
DownloadCoreFunction(String artifact, String ext) {
super(env -> artifact + '.' + ext, env -> getDownloadInfo(env, artifact, ext));
}
| private static DownloadInfo getDownloadInfo(MCPEnvironment environment, String artifact, String extension) { |
MinecraftForge/ForgeGradle | src/userdev/java/net/minecraftforge/gradle/userdev/DependencyManagementExtension.java | // Path: src/userdev/java/net/minecraftforge/gradle/userdev/util/DependencyRemapper.java
// public class DependencyRemapper {
// private final Project project;
// @SuppressWarnings("unused")
// private Deobfuscator deobfuscator;
// private final List<Consumer<String>> mappingListeners = new ArrayList<>();
//
// public DependencyRemapper(Project project, Deobfuscator deobfuscator) {
// this.project = project;
// this.deobfuscator = deobfuscator;
// }
//
// /*
// * Impl note: Gradle uses a lot of internal instanceof checking,
// * so it's more reliable to use the same classes gradle uses.
// *
// * Best way to do it is Dependency#copy. If that's not possible,
// * internal classes starting with Default are an option. It should be a last resort,
// * as that is a part of internal unstable APIs.
// */
// public Dependency remap(Dependency dependency) {
// if (dependency instanceof ExternalModuleDependency) {
// return remapExternalModule((ExternalModuleDependency) dependency);
// }
//
// if (dependency instanceof FileCollectionDependency) {
// project.getLogger().warn("files(...) dependencies are not deobfuscated. Use a flatDir repository instead: https://docs.gradle.org/current/userguide/repository_types.html#sec:flat_dir_resolver");
// }
//
// project.getLogger().warn("Cannot deobfuscate dependency of type {}, using obfuscated version!", dependency.getClass().getSimpleName());
// return dependency;
// }
//
// private ExternalModuleDependency remapExternalModule(ExternalModuleDependency dependency) {
// ExternalModuleDependency newDep = dependency.copy();
// mappingListeners.add(m -> newDep.version(v -> v.strictly(newDep.getVersion() + "_mapped_" + m)));
// return newDep;
// }
//
// public void attachMappings(String mappings) {
// mappingListeners.forEach(l -> l.accept(mappings));
// }
//
// }
| import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;
import net.minecraftforge.gradle.userdev.util.DependencyRemapper;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Dependency; | /*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.userdev;
public class DependencyManagementExtension extends GroovyObjectSupport {
public static final String EXTENSION_NAME = "fg";
private final Project project; | // Path: src/userdev/java/net/minecraftforge/gradle/userdev/util/DependencyRemapper.java
// public class DependencyRemapper {
// private final Project project;
// @SuppressWarnings("unused")
// private Deobfuscator deobfuscator;
// private final List<Consumer<String>> mappingListeners = new ArrayList<>();
//
// public DependencyRemapper(Project project, Deobfuscator deobfuscator) {
// this.project = project;
// this.deobfuscator = deobfuscator;
// }
//
// /*
// * Impl note: Gradle uses a lot of internal instanceof checking,
// * so it's more reliable to use the same classes gradle uses.
// *
// * Best way to do it is Dependency#copy. If that's not possible,
// * internal classes starting with Default are an option. It should be a last resort,
// * as that is a part of internal unstable APIs.
// */
// public Dependency remap(Dependency dependency) {
// if (dependency instanceof ExternalModuleDependency) {
// return remapExternalModule((ExternalModuleDependency) dependency);
// }
//
// if (dependency instanceof FileCollectionDependency) {
// project.getLogger().warn("files(...) dependencies are not deobfuscated. Use a flatDir repository instead: https://docs.gradle.org/current/userguide/repository_types.html#sec:flat_dir_resolver");
// }
//
// project.getLogger().warn("Cannot deobfuscate dependency of type {}, using obfuscated version!", dependency.getClass().getSimpleName());
// return dependency;
// }
//
// private ExternalModuleDependency remapExternalModule(ExternalModuleDependency dependency) {
// ExternalModuleDependency newDep = dependency.copy();
// mappingListeners.add(m -> newDep.version(v -> v.strictly(newDep.getVersion() + "_mapped_" + m)));
// return newDep;
// }
//
// public void attachMappings(String mappings) {
// mappingListeners.forEach(l -> l.accept(mappings));
// }
//
// }
// Path: src/userdev/java/net/minecraftforge/gradle/userdev/DependencyManagementExtension.java
import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;
import net.minecraftforge.gradle.userdev.util.DependencyRemapper;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Dependency;
/*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.userdev;
public class DependencyManagementExtension extends GroovyObjectSupport {
public static final String EXTENSION_NAME = "fg";
private final Project project; | private final DependencyRemapper remapper; |
MinecraftForge/ForgeGradle | src/common/java/net/minecraftforge/gradle/common/tasks/DownloadMCMeta.java | // Path: src/common/java/net/minecraftforge/gradle/common/util/ManifestJson.java
// public class ManifestJson {
// public ManifestJson.VersionInfo[] versions;
// public static class VersionInfo {
// public String id;
// public URL url;
// }
//
// @Nullable
// public URL getUrl(@Nullable String version) {
// if (version == null) {
// return null;
// }
// for (VersionInfo info : versions) {
// if (version.equals(info.id)) {
// return info.url;
// }
// }
// return null;
// }
// }
| import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import net.minecraftforge.gradle.common.util.ManifestJson;
import org.apache.commons.io.FileUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction; | /*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.common.tasks;
public abstract class DownloadMCMeta extends DefaultTask {
// TODO: convert this into a property?
private static final String MANIFEST_URL = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
private static final Gson GSON = new GsonBuilder().create();
public DownloadMCMeta() {
getManifest().convention(getProject().getLayout().getBuildDirectory().dir(getName()).map(s -> s.file("manifest.json")));
getOutput().convention(getProject().getLayout().getBuildDirectory().dir(getName()).map(s -> s.file("version.json")));
}
@TaskAction
public void downloadMCMeta() throws IOException {
try (InputStream manin = new URL(MANIFEST_URL).openStream()) { | // Path: src/common/java/net/minecraftforge/gradle/common/util/ManifestJson.java
// public class ManifestJson {
// public ManifestJson.VersionInfo[] versions;
// public static class VersionInfo {
// public String id;
// public URL url;
// }
//
// @Nullable
// public URL getUrl(@Nullable String version) {
// if (version == null) {
// return null;
// }
// for (VersionInfo info : versions) {
// if (version.equals(info.id)) {
// return info.url;
// }
// }
// return null;
// }
// }
// Path: src/common/java/net/minecraftforge/gradle/common/tasks/DownloadMCMeta.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import net.minecraftforge.gradle.common.util.ManifestJson;
import org.apache.commons.io.FileUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
/*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.common.tasks;
public abstract class DownloadMCMeta extends DefaultTask {
// TODO: convert this into a property?
private static final String MANIFEST_URL = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
private static final Gson GSON = new GsonBuilder().create();
public DownloadMCMeta() {
getManifest().convention(getProject().getLayout().getBuildDirectory().dir(getName()).map(s -> s.file("manifest.json")));
getOutput().convention(getProject().getLayout().getBuildDirectory().dir(getName()).map(s -> s.file("version.json")));
}
@TaskAction
public void downloadMCMeta() throws IOException {
try (InputStream manin = new URL(MANIFEST_URL).openStream()) { | URL url = GSON.fromJson(new InputStreamReader(manin), ManifestJson.class).getUrl(getMCVersion().get()); |
MinecraftForge/ForgeGradle | src/patcher/java/net/minecraftforge/gradle/patcher/tasks/CreateExc.java | // Path: src/common/java/net/minecraftforge/gradle/common/config/MCPConfigV2.java
// public class MCPConfigV2 extends MCPConfigV1 {
// public static MCPConfigV2 get(InputStream stream) {
// return Utils.fromJson(stream, MCPConfigV2.class);
// }
// public static MCPConfigV2 get(byte[] data) {
// return get(new ByteArrayInputStream(data));
// }
//
// public static MCPConfigV2 getFromArchive(File path) throws IOException {
// try (ZipFile zip = new ZipFile(path)) {
// ZipEntry entry = zip.getEntry("config.json");
// if (entry == null)
// throw new IllegalStateException("Could not find 'config.json' in " + path.getAbsolutePath());
//
// byte[] data = IOUtils.toByteArray(zip.getInputStream(entry));
// int spec = Config.getSpec(data);
// if (spec == 2 || spec == 3)
// return MCPConfigV2.get(data);
// if (spec == 1)
// return new MCPConfigV2(MCPConfigV1.get(data));
//
// throw new IllegalStateException("Invalid MCP Config: " + path.getAbsolutePath() + " Unknown spec: " + spec);
// }
// }
//
// private boolean official = false;
// private int java_target = 8;
// @Nullable
// private String encoding = "UTF-8";
//
// public boolean isOfficial() {
// return this.official;
// }
//
// public int getJavaTarget() {
// return this.java_target;
// }
//
// public String getEncoding() {
// return this.encoding == null ? "UTF-8" : this.encoding;
// }
//
// public MCPConfigV2(MCPConfigV1 old) {
// this.version = old.version;
// this.data = old.data;
// this.steps = old.steps;
// this.functions = old.functions;
// this.libraries = old.libraries;
// }
// }
| import net.minecraftforge.gradle.common.config.MCPConfigV2;
import net.minecraftforge.srgutils.IMappingFile;
import org.apache.commons.io.IOUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import de.siegmar.fastcsv.reader.NamedCsvReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipFile; | /*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.patcher.tasks;
public abstract class CreateExc extends DefaultTask {
private static final Pattern CLS_ENTRY = Pattern.compile("L([^;]+);");
public CreateExc() {
getOutput().convention(getProject().getLayout().getBuildDirectory().dir(getName()).map(d -> d.file("output.exc")));
}
@TaskAction
public void run() throws IOException { | // Path: src/common/java/net/minecraftforge/gradle/common/config/MCPConfigV2.java
// public class MCPConfigV2 extends MCPConfigV1 {
// public static MCPConfigV2 get(InputStream stream) {
// return Utils.fromJson(stream, MCPConfigV2.class);
// }
// public static MCPConfigV2 get(byte[] data) {
// return get(new ByteArrayInputStream(data));
// }
//
// public static MCPConfigV2 getFromArchive(File path) throws IOException {
// try (ZipFile zip = new ZipFile(path)) {
// ZipEntry entry = zip.getEntry("config.json");
// if (entry == null)
// throw new IllegalStateException("Could not find 'config.json' in " + path.getAbsolutePath());
//
// byte[] data = IOUtils.toByteArray(zip.getInputStream(entry));
// int spec = Config.getSpec(data);
// if (spec == 2 || spec == 3)
// return MCPConfigV2.get(data);
// if (spec == 1)
// return new MCPConfigV2(MCPConfigV1.get(data));
//
// throw new IllegalStateException("Invalid MCP Config: " + path.getAbsolutePath() + " Unknown spec: " + spec);
// }
// }
//
// private boolean official = false;
// private int java_target = 8;
// @Nullable
// private String encoding = "UTF-8";
//
// public boolean isOfficial() {
// return this.official;
// }
//
// public int getJavaTarget() {
// return this.java_target;
// }
//
// public String getEncoding() {
// return this.encoding == null ? "UTF-8" : this.encoding;
// }
//
// public MCPConfigV2(MCPConfigV1 old) {
// this.version = old.version;
// this.data = old.data;
// this.steps = old.steps;
// this.functions = old.functions;
// this.libraries = old.libraries;
// }
// }
// Path: src/patcher/java/net/minecraftforge/gradle/patcher/tasks/CreateExc.java
import net.minecraftforge.gradle.common.config.MCPConfigV2;
import net.minecraftforge.srgutils.IMappingFile;
import org.apache.commons.io.IOUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import de.siegmar.fastcsv.reader.NamedCsvReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipFile;
/*
* ForgeGradle
* Copyright (C) 2018 Forge Development LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.minecraftforge.gradle.patcher.tasks;
public abstract class CreateExc extends DefaultTask {
private static final Pattern CLS_ENTRY = Pattern.compile("L([^;]+);");
public CreateExc() {
getOutput().convention(getProject().getLayout().getBuildDirectory().dir(getName()).map(d -> d.file("output.exc")));
}
@TaskAction
public void run() throws IOException { | MCPConfigV2 cfg = MCPConfigV2.getFromArchive(getConfig().get().getAsFile()); |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class, "test.jar")
.addClasses(
WeldEmbeddedIntegrationTestCase.class, | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationTestCase.java
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class, "test.jar")
.addClasses(
WeldEmbeddedIntegrationTestCase.class, | MyBean.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/shrinkwrap/ShrinkwrapBeanDeploymentArchiveTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import java.util.Collection;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded.shrinkwrap;
/**
* ShrinkwrapBeanDeploymentArchiveTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
public class ShrinkwrapBeanDeploymentArchiveTestCase
{
@Test
public void shouldBeAbleToFindAllClasses() throws Exception
{
JavaArchive archive = ShrinkWrap.create(JavaArchive.class) | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/shrinkwrap/ShrinkwrapBeanDeploymentArchiveTestCase.java
import java.util.Collection;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded.shrinkwrap;
/**
* ShrinkwrapBeanDeploymentArchiveTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
public class ShrinkwrapBeanDeploymentArchiveTestCase
{
@Test
public void shouldBeAbleToFindAllClasses() throws Exception
{
JavaArchive archive = ShrinkWrap.create(JavaArchive.class) | .addPackage(MyBean.class.getPackage()) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/UtilsTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import java.util.Collection;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.resources.DefaultResourceLoader;
import org.junit.Assert;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.classloader.ShrinkWrapClassLoader;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test; | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* UtilsTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @author Matt Benson
* @version $Revision: $
*/
public class UtilsTestCase
{
@Test
public void shouldBeAbleToFindAllClasses() throws Exception
{
JavaArchive archive = ShrinkWrap.create(JavaArchive.class) | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/UtilsTestCase.java
import java.util.Collection;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.resources.DefaultResourceLoader;
import org.junit.Assert;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.classloader.ShrinkWrapClassLoader;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* UtilsTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @author Matt Benson
* @version $Revision: $
*/
public class UtilsTestCase
{
@Test
public void shouldBeAbleToFindAllClasses() throws Exception
{
JavaArchive archive = ShrinkWrap.create(JavaArchive.class) | .addClass(MyBean.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedDeploymentExceptionTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/LoopingProducer.java
// @Dependent
// public class LoopingProducer
// {
// @Produces
// public String test(String string)
// {
// return "";
// }
// }
| import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.ShouldThrowException;
import org.jboss.arquillian.container.weld.embedded.beans.LoopingProducer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.weld.exceptions.DeploymentException;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedDeploymentExceptionTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedDeploymentExceptionTestCase
{
@Deployment @ShouldThrowException(DeploymentException.class)
public static JavaArchive createDeployment()
{
return ShrinkWrap.create(JavaArchive.class) | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/LoopingProducer.java
// @Dependent
// public class LoopingProducer
// {
// @Produces
// public String test(String string)
// {
// return "";
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedDeploymentExceptionTestCase.java
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.ShouldThrowException;
import org.jboss.arquillian.container.weld.embedded.beans.LoopingProducer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.weld.exceptions.DeploymentException;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedDeploymentExceptionTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedDeploymentExceptionTestCase
{
@Deployment @ShouldThrowException(DeploymentException.class)
public static JavaArchive createDeployment()
{
return ShrinkWrap.create(JavaArchive.class) | .addClass(LoopingProducer.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/RemoveDuplicateBeanXmlTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TraceInterceptor.java
// @Interceptor @Trace
// public class TraceInterceptor {
//
// public static List<String> called = new ArrayList<String>();
//
// @AroundInvoke
// public Object manageTransaction(InvocationContext ctx) throws Exception {
// called.add(ctx.getMethod().getDeclaringClass().getSimpleName());
// return ctx.proceed();
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanOne.java
// @Trace
// @Dependent
// public class TracedBeanOne {
//
// public void call() {
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanTwo.java
// @Trace
// @Dependent
// public class TracedBeanTwo {
//
// public void call() {
// }
// }
| import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.trace.Trace;
import org.jboss.arquillian.container.weld.embedded.trace.TraceInterceptor;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanOne;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanTwo;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith; | package org.jboss.arquillian.container.weld.embedded;
@RunWith(Arquillian.class)
public class RemoveDuplicateBeanXmlTestCase {
@Deployment
public static WebArchive deploy() { | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TraceInterceptor.java
// @Interceptor @Trace
// public class TraceInterceptor {
//
// public static List<String> called = new ArrayList<String>();
//
// @AroundInvoke
// public Object manageTransaction(InvocationContext ctx) throws Exception {
// called.add(ctx.getMethod().getDeclaringClass().getSimpleName());
// return ctx.proceed();
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanOne.java
// @Trace
// @Dependent
// public class TracedBeanOne {
//
// public void call() {
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanTwo.java
// @Trace
// @Dependent
// public class TracedBeanTwo {
//
// public void call() {
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/RemoveDuplicateBeanXmlTestCase.java
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.trace.Trace;
import org.jboss.arquillian.container.weld.embedded.trace.TraceInterceptor;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanOne;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanTwo;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
package org.jboss.arquillian.container.weld.embedded;
@RunWith(Arquillian.class)
public class RemoveDuplicateBeanXmlTestCase {
@Deployment
public static WebArchive deploy() { | String beansxml = "<beans><interceptors><class>" + TraceInterceptor.class.getName() + "</class></interceptors></beans>"; |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/RemoveDuplicateBeanXmlTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TraceInterceptor.java
// @Interceptor @Trace
// public class TraceInterceptor {
//
// public static List<String> called = new ArrayList<String>();
//
// @AroundInvoke
// public Object manageTransaction(InvocationContext ctx) throws Exception {
// called.add(ctx.getMethod().getDeclaringClass().getSimpleName());
// return ctx.proceed();
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanOne.java
// @Trace
// @Dependent
// public class TracedBeanOne {
//
// public void call() {
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanTwo.java
// @Trace
// @Dependent
// public class TracedBeanTwo {
//
// public void call() {
// }
// }
| import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.trace.Trace;
import org.jboss.arquillian.container.weld.embedded.trace.TraceInterceptor;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanOne;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanTwo;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith; | package org.jboss.arquillian.container.weld.embedded;
@RunWith(Arquillian.class)
public class RemoveDuplicateBeanXmlTestCase {
@Deployment
public static WebArchive deploy() {
String beansxml = "<beans><interceptors><class>" + TraceInterceptor.class.getName() + "</class></interceptors></beans>";
return ShrinkWrap.create(WebArchive.class) | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TraceInterceptor.java
// @Interceptor @Trace
// public class TraceInterceptor {
//
// public static List<String> called = new ArrayList<String>();
//
// @AroundInvoke
// public Object manageTransaction(InvocationContext ctx) throws Exception {
// called.add(ctx.getMethod().getDeclaringClass().getSimpleName());
// return ctx.proceed();
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanOne.java
// @Trace
// @Dependent
// public class TracedBeanOne {
//
// public void call() {
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanTwo.java
// @Trace
// @Dependent
// public class TracedBeanTwo {
//
// public void call() {
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/RemoveDuplicateBeanXmlTestCase.java
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.trace.Trace;
import org.jboss.arquillian.container.weld.embedded.trace.TraceInterceptor;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanOne;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanTwo;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
package org.jboss.arquillian.container.weld.embedded;
@RunWith(Arquillian.class)
public class RemoveDuplicateBeanXmlTestCase {
@Deployment
public static WebArchive deploy() {
String beansxml = "<beans><interceptors><class>" + TraceInterceptor.class.getName() + "</class></interceptors></beans>";
return ShrinkWrap.create(WebArchive.class) | .addClasses(Trace.class, TraceInterceptor.class, TracedBeanOne.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/RemoveDuplicateBeanXmlTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TraceInterceptor.java
// @Interceptor @Trace
// public class TraceInterceptor {
//
// public static List<String> called = new ArrayList<String>();
//
// @AroundInvoke
// public Object manageTransaction(InvocationContext ctx) throws Exception {
// called.add(ctx.getMethod().getDeclaringClass().getSimpleName());
// return ctx.proceed();
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanOne.java
// @Trace
// @Dependent
// public class TracedBeanOne {
//
// public void call() {
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanTwo.java
// @Trace
// @Dependent
// public class TracedBeanTwo {
//
// public void call() {
// }
// }
| import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.trace.Trace;
import org.jboss.arquillian.container.weld.embedded.trace.TraceInterceptor;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanOne;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanTwo;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith; | package org.jboss.arquillian.container.weld.embedded;
@RunWith(Arquillian.class)
public class RemoveDuplicateBeanXmlTestCase {
@Deployment
public static WebArchive deploy() {
String beansxml = "<beans><interceptors><class>" + TraceInterceptor.class.getName() + "</class></interceptors></beans>";
return ShrinkWrap.create(WebArchive.class)
.addClasses(Trace.class, TraceInterceptor.class, TracedBeanOne.class)
.addAsWebInfResource(new StringAsset(beansxml), "beans.xml")
.addAsLibrary(
ShrinkWrap.create(JavaArchive.class) | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TraceInterceptor.java
// @Interceptor @Trace
// public class TraceInterceptor {
//
// public static List<String> called = new ArrayList<String>();
//
// @AroundInvoke
// public Object manageTransaction(InvocationContext ctx) throws Exception {
// called.add(ctx.getMethod().getDeclaringClass().getSimpleName());
// return ctx.proceed();
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanOne.java
// @Trace
// @Dependent
// public class TracedBeanOne {
//
// public void call() {
// }
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/trace/TracedBeanTwo.java
// @Trace
// @Dependent
// public class TracedBeanTwo {
//
// public void call() {
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/RemoveDuplicateBeanXmlTestCase.java
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.trace.Trace;
import org.jboss.arquillian.container.weld.embedded.trace.TraceInterceptor;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanOne;
import org.jboss.arquillian.container.weld.embedded.trace.TracedBeanTwo;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
package org.jboss.arquillian.container.weld.embedded;
@RunWith(Arquillian.class)
public class RemoveDuplicateBeanXmlTestCase {
@Deployment
public static WebArchive deploy() {
String beansxml = "<beans><interceptors><class>" + TraceInterceptor.class.getName() + "</class></interceptors></beans>";
return ShrinkWrap.create(WebArchive.class)
.addClasses(Trace.class, TraceInterceptor.class, TracedBeanOne.class)
.addAsWebInfResource(new StringAsset(beansxml), "beans.xml")
.addAsLibrary(
ShrinkWrap.create(JavaArchive.class) | .addClass(TracedBeanTwo.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationEARTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationEARTestCase
{
@Deployment
public static EnterpriseArchive createdeployment()
{
return ShrinkWrap.create(EnterpriseArchive.class)
.addAsModule(
ShrinkWrap.create(WebArchive.class)
.addClasses(
WeldEmbeddedIntegrationEARTestCase.class, | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationEARTestCase.java
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationEARTestCase
{
@Deployment
public static EnterpriseArchive createdeployment()
{
return ShrinkWrap.create(EnterpriseArchive.class)
.addAsModule(
ShrinkWrap.create(WebArchive.class)
.addClasses(
WeldEmbeddedIntegrationEARTestCase.class, | MyBean.class) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.