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 |
|---|---|---|---|---|---|---|
abraao/FastPicasaBrowser | src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java | // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils; | package com.guaranacode.android.fastpicasabrowser.storage;
/**
* Image downloading and storage.
*
* @author abe@guaranacode.com
*
*/
public class ImageStorage {
private static String APP_PACKAGE = "com.guaranacode.fastpicasabrowser";
private static String APP_STORAGE_PATH = APP_PACKAGE + "/files";
private static String TEMP_PHOTO_DIR = "temp_photos";
private static String TEMP_PHOTO_NAME = "temp_photo.jpg";
public static String getLocalPathForThumbnail(IStorableModel model, boolean includeFilename) {
String relativePath = APP_STORAGE_PATH + "/" + model.getDir();
return getLocalPathForImage(model.getUrl(), relativePath, includeFilename);
}
public static String getFilenameFromUrl(String imageUrl) { | // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
// Path: src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils;
package com.guaranacode.android.fastpicasabrowser.storage;
/**
* Image downloading and storage.
*
* @author abe@guaranacode.com
*
*/
public class ImageStorage {
private static String APP_PACKAGE = "com.guaranacode.fastpicasabrowser";
private static String APP_STORAGE_PATH = APP_PACKAGE + "/files";
private static String TEMP_PHOTO_DIR = "temp_photos";
private static String TEMP_PHOTO_NAME = "temp_photo.jpg";
public static String getLocalPathForThumbnail(IStorableModel model, boolean includeFilename) {
String relativePath = APP_STORAGE_PATH + "/" + model.getDir();
return getLocalPathForImage(model.getUrl(), relativePath, includeFilename);
}
public static String getFilenameFromUrl(String imageUrl) { | if(StringUtils.isNullOrEmpty(imageUrl)) { |
abraao/FastPicasaBrowser | src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java | // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils; | package com.guaranacode.android.fastpicasabrowser.storage;
/**
* Image downloading and storage.
*
* @author abe@guaranacode.com
*
*/
public class ImageStorage {
private static String APP_PACKAGE = "com.guaranacode.fastpicasabrowser";
private static String APP_STORAGE_PATH = APP_PACKAGE + "/files";
private static String TEMP_PHOTO_DIR = "temp_photos";
private static String TEMP_PHOTO_NAME = "temp_photo.jpg";
public static String getLocalPathForThumbnail(IStorableModel model, boolean includeFilename) {
String relativePath = APP_STORAGE_PATH + "/" + model.getDir();
return getLocalPathForImage(model.getUrl(), relativePath, includeFilename);
}
public static String getFilenameFromUrl(String imageUrl) {
if(StringUtils.isNullOrEmpty(imageUrl)) {
return null;
}
String filename = null;
int lastSlashIdx = imageUrl.lastIndexOf('/');
if(lastSlashIdx > 0) {
filename = imageUrl.substring(lastSlashIdx + 1);
}
return filename;
}
private static Bitmap getFromLocalStorage(IStorableModel model) {
if(null == model) {
return null;
}
| // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
// Path: src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils;
package com.guaranacode.android.fastpicasabrowser.storage;
/**
* Image downloading and storage.
*
* @author abe@guaranacode.com
*
*/
public class ImageStorage {
private static String APP_PACKAGE = "com.guaranacode.fastpicasabrowser";
private static String APP_STORAGE_PATH = APP_PACKAGE + "/files";
private static String TEMP_PHOTO_DIR = "temp_photos";
private static String TEMP_PHOTO_NAME = "temp_photo.jpg";
public static String getLocalPathForThumbnail(IStorableModel model, boolean includeFilename) {
String relativePath = APP_STORAGE_PATH + "/" + model.getDir();
return getLocalPathForImage(model.getUrl(), relativePath, includeFilename);
}
public static String getFilenameFromUrl(String imageUrl) {
if(StringUtils.isNullOrEmpty(imageUrl)) {
return null;
}
String filename = null;
int lastSlashIdx = imageUrl.lastIndexOf('/');
if(lastSlashIdx > 0) {
filename = imageUrl.substring(lastSlashIdx + 1);
}
return filename;
}
private static Bitmap getFromLocalStorage(IStorableModel model) {
if(null == model) {
return null;
}
| if(!StorageUtils.canReadFromExternalStorage()) { |
abraao/FastPicasaBrowser | src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java | // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils; | */
private static String getSdDirPath() {
String sdDirPath;
File sdDir = Environment.getExternalStorageDirectory();
if(null == sdDir) {
return null;
}
try {
sdDirPath = sdDir.getCanonicalPath();
} catch (IOException e) {
sdDirPath = null;
}
return sdDirPath;
}
private static boolean storeLocally(IStorableModel model, Bitmap thumbnail) {
if(!StorageUtils.canWriteToExternalStorage()) {
return false;
}
String localPath = getLocalPathForThumbnail(model, true);
String localDir = getLocalPathForThumbnail(model, false);
if(StringUtils.isNullOrEmpty(localPath)) {
return false;
}
| // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
// Path: src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils;
*/
private static String getSdDirPath() {
String sdDirPath;
File sdDir = Environment.getExternalStorageDirectory();
if(null == sdDir) {
return null;
}
try {
sdDirPath = sdDir.getCanonicalPath();
} catch (IOException e) {
sdDirPath = null;
}
return sdDirPath;
}
private static boolean storeLocally(IStorableModel model, Bitmap thumbnail) {
if(!StorageUtils.canWriteToExternalStorage()) {
return false;
}
String localPath = getLocalPathForThumbnail(model, true);
String localDir = getLocalPathForThumbnail(model, false);
if(StringUtils.isNullOrEmpty(localPath)) {
return false;
}
| FileUtils.createPath(localDir); |
abraao/FastPicasaBrowser | src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java | // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils; | private static Bitmap resizeThumbnail(InputStream bitmapStream) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeStream(bitmapStream, null, options);
return bitmap;
}
public static Bitmap downloadThumbnailAndStoreLocally(IStorableModel model) {
Bitmap thumbnail = downloadBitmap(model.getUrl(), true);
if(null != thumbnail) {
storeLocally(model, thumbnail);
}
return thumbnail;
}
public static Bitmap setImageThumbnail(IStorableModel model, ImageView imageView) {
Bitmap thumbnail = null;
try {
if(null == model) {
return null;
}
thumbnail = getFromLocalStorage(model);
if(null == thumbnail) { | // Path: src/com/guaranacode/android/fastpicasabrowser/tasks/DownloadImageTask.java
// public class DownloadImageTask extends AsyncTask<IStorableModel, Integer, Bitmap> {
// private ImageView mView;
// private String mUrl;
//
// public DownloadImageTask(ImageView view) {
// mView = view;
// }
//
// @Override
// protected Bitmap doInBackground(IStorableModel... storableList) {
// mUrl = storableList[0].getUrl();
//
// Bitmap bitmap = ImageStorage.downloadThumbnailAndStoreLocally(storableList[0]);
// return bitmap;
// }
//
// protected void onPostExecute(Bitmap result) {
// if((null != mView) && (null != result) && (mUrl.equals((String)mView.getTag()))) {
// mView.setImageBitmap(result);
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/FileUtils.java
// public class FileUtils {
//
// /**
// * Creates all directories in the specified path if they don't already exist. Returns
// * true if successful, false otherwise.
// * @param path
// * @return
// */
// public static boolean createPath(String path) {
// File dirs = new File(path);
// return dirs.mkdirs();
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param path
// */
// public static void deleteFile(String path) {
// File dir = new File(path);
// deleteFile(dir);
// }
//
// /**
// * Deletes a file or a directory and everything in it.
// * @param file
// */
// public static void deleteFile(File file) {
// if((null == file)) {
// return;
// }
//
// if(file.isFile()) {
// file.delete();
// }
// else if(file.isDirectory()) {
// for(String child : file.list()) {
// deleteFile(file.getAbsolutePath() + "/" + child);
// }
//
// file.delete();
// }
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StorageUtils.java
// public class StorageUtils {
// /**
// * Returns true if the media is currently mounted and writable, false otherwise.
// * @return
// */
// public static boolean canWriteToExternalStorage() {
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// }
//
// /**
// * Returns true if media is currently mounted and readable.
// * @return
// */
// public static boolean canReadFromExternalStorage() {
// if(canWriteToExternalStorage()) {
// return true;
// }
//
// return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
// }
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
// Path: src/com/guaranacode/android/fastpicasabrowser/storage/ImageStorage.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.guaranacode.android.fastpicasabrowser.tasks.DownloadImageTask;
import com.guaranacode.android.fastpicasabrowser.util.FileUtils;
import com.guaranacode.android.fastpicasabrowser.util.StorageUtils;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils;
private static Bitmap resizeThumbnail(InputStream bitmapStream) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeStream(bitmapStream, null, options);
return bitmap;
}
public static Bitmap downloadThumbnailAndStoreLocally(IStorableModel model) {
Bitmap thumbnail = downloadBitmap(model.getUrl(), true);
if(null != thumbnail) {
storeLocally(model, thumbnail);
}
return thumbnail;
}
public static Bitmap setImageThumbnail(IStorableModel model, ImageView imageView) {
Bitmap thumbnail = null;
try {
if(null == model) {
return null;
}
thumbnail = getFromLocalStorage(model);
if(null == thumbnail) { | new DownloadImageTask(imageView).execute(model); |
abraao/FastPicasaBrowser | src/com/guaranacode/android/fastpicasabrowser/picasa/model/PhotoEntry.java | // Path: src/com/guaranacode/android/fastpicasabrowser/storage/IStorableModel.java
// public interface IStorableModel {
//
// /**
// * The URL to the resource.
// * @return
// */
// String getUrl();
//
// /**
// * Get the directory in the application's path where we store files.
// * @return
// */
// String getDir();
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
| import com.google.api.client.util.Key;
import com.guaranacode.android.fastpicasabrowser.storage.IStorableModel;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils; | package com.guaranacode.android.fastpicasabrowser.picasa.model;
/**
* A photo in the photo feed.
*
* @author abe@guaranacode.com
*
*/
public class PhotoEntry extends Entry implements IStorableModel {
@Key("gphoto:id")
public String photoId;
@Key("media:group")
public MediaGroup mediaGroup;
public String albumId;
public String thumbnailUrl;
public String getDir() {
return "photo_thumbnails";
}
public String getUrl() { | // Path: src/com/guaranacode/android/fastpicasabrowser/storage/IStorableModel.java
// public interface IStorableModel {
//
// /**
// * The URL to the resource.
// * @return
// */
// String getUrl();
//
// /**
// * Get the directory in the application's path where we store files.
// * @return
// */
// String getDir();
// }
//
// Path: src/com/guaranacode/android/fastpicasabrowser/util/StringUtils.java
// public class StringUtils {
//
// /**
// * Returns true if the string is null or contains only whitespace.
// *
// * @param string
// * @return
// */
// public static boolean isNullOrEmpty(String string) {
// return (null == string) || (string.trim().length() == 0);
// }
// }
// Path: src/com/guaranacode/android/fastpicasabrowser/picasa/model/PhotoEntry.java
import com.google.api.client.util.Key;
import com.guaranacode.android.fastpicasabrowser.storage.IStorableModel;
import com.guaranacode.android.fastpicasabrowser.util.StringUtils;
package com.guaranacode.android.fastpicasabrowser.picasa.model;
/**
* A photo in the photo feed.
*
* @author abe@guaranacode.com
*
*/
public class PhotoEntry extends Entry implements IStorableModel {
@Key("gphoto:id")
public String photoId;
@Key("media:group")
public MediaGroup mediaGroup;
public String albumId;
public String thumbnailUrl;
public String getDir() {
return "photo_thumbnails";
}
public String getUrl() { | if(!StringUtils.isNullOrEmpty(thumbnailUrl)) { |
vickychijwani/udacity-p1-p2-popular-movies | app/src/main/java/me/vickychijwani/popularmovies/ui/MovieDetailsActivity.java | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/event/events/MovieLoadedEvent.java
// public class MovieLoadedEvent {
//
// public final Movie movie;
//
// public MovieLoadedEvent(@NonNull Movie movie) {
// this.movie = movie;
// }
//
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.squareup.otto.Subscribe;
import butterknife.ButterKnife;
import me.vickychijwani.popularmovies.R;
import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.event.events.MovieLoadedEvent; | package me.vickychijwani.popularmovies.ui;
public class MovieDetailsActivity extends BaseActivity {
private static final String TAG = "MovieDetailsActivity";
| // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/event/events/MovieLoadedEvent.java
// public class MovieLoadedEvent {
//
// public final Movie movie;
//
// public MovieLoadedEvent(@NonNull Movie movie) {
// this.movie = movie;
// }
//
// }
// Path: app/src/main/java/me/vickychijwani/popularmovies/ui/MovieDetailsActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.squareup.otto.Subscribe;
import butterknife.ButterKnife;
import me.vickychijwani.popularmovies.R;
import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.event.events.MovieLoadedEvent;
package me.vickychijwani.popularmovies.ui;
public class MovieDetailsActivity extends BaseActivity {
private static final String TAG = "MovieDetailsActivity";
| private Movie mMovie; |
vickychijwani/udacity-p1-p2-popular-movies | app/src/main/java/me/vickychijwani/popularmovies/ui/BaseActivity.java | // Path: app/src/main/java/me/vickychijwani/popularmovies/event/DataBusProvider.java
// public class DataBusProvider {
//
// private static final Bus mBus = new DataBus();
//
// private DataBusProvider() {}
//
// public static Bus getBus() { return mBus; }
//
// private static final class DataBus extends Bus {
// private static final String TAG = "DataBus";
//
// public DataBus() {
// super();
// log(Log.INFO, "INIT", "");
// }
//
// @Override
// public void register(Object object) {
// super.register(object);
// log(Log.INFO, "REG", object.getClass().getSimpleName());
// }
//
// @Override
// public void unregister(Object object) {
// log(Log.INFO, "UNREG", object.getClass().getSimpleName());
// super.unregister(object);
// }
//
// @Override
// public void post(Object event) {
// if (event instanceof DeadEvent) {
// String deadEventName = ((DeadEvent) event).event.getClass().getSimpleName();
// log(Log.WARN, "DEAD", "Dead event posted: " + deadEventName);
// } else {
// log(Log.DEBUG, "POST", event.toString());
// }
// super.post(event);
// }
//
// private void log(int priority, String type, String message) {
// if (BuildConfig.DEBUG || priority >= Log.WARN) {
// String logMsg = String.format("[%1$5s] %2$s on %3$s", type, message, toString());
// Log.println(priority, TAG, logMsg);
// }
// }
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import com.squareup.otto.Bus;
import io.realm.Realm;
import me.vickychijwani.popularmovies.BuildConfig;
import me.vickychijwani.popularmovies.event.DataBusProvider; | package me.vickychijwani.popularmovies.ui;
public abstract class BaseActivity extends AppCompatActivity {
private static final String LIFECYCLE = "Lifecycle";
private Realm mRealmReference = null;
protected Bus getDataBus() { | // Path: app/src/main/java/me/vickychijwani/popularmovies/event/DataBusProvider.java
// public class DataBusProvider {
//
// private static final Bus mBus = new DataBus();
//
// private DataBusProvider() {}
//
// public static Bus getBus() { return mBus; }
//
// private static final class DataBus extends Bus {
// private static final String TAG = "DataBus";
//
// public DataBus() {
// super();
// log(Log.INFO, "INIT", "");
// }
//
// @Override
// public void register(Object object) {
// super.register(object);
// log(Log.INFO, "REG", object.getClass().getSimpleName());
// }
//
// @Override
// public void unregister(Object object) {
// log(Log.INFO, "UNREG", object.getClass().getSimpleName());
// super.unregister(object);
// }
//
// @Override
// public void post(Object event) {
// if (event instanceof DeadEvent) {
// String deadEventName = ((DeadEvent) event).event.getClass().getSimpleName();
// log(Log.WARN, "DEAD", "Dead event posted: " + deadEventName);
// } else {
// log(Log.DEBUG, "POST", event.toString());
// }
// super.post(event);
// }
//
// private void log(int priority, String type, String message) {
// if (BuildConfig.DEBUG || priority >= Log.WARN) {
// String logMsg = String.format("[%1$5s] %2$s on %3$s", type, message, toString());
// Log.println(priority, TAG, logMsg);
// }
// }
// }
//
// }
// Path: app/src/main/java/me/vickychijwani/popularmovies/ui/BaseActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import com.squareup.otto.Bus;
import io.realm.Realm;
import me.vickychijwani.popularmovies.BuildConfig;
import me.vickychijwani.popularmovies.event.DataBusProvider;
package me.vickychijwani.popularmovies.ui;
public abstract class BaseActivity extends AppCompatActivity {
private static final String LIFECYCLE = "Lifecycle";
private Realm mRealmReference = null;
protected Bus getDataBus() { | return DataBusProvider.getBus(); |
vickychijwani/udacity-p1-p2-popular-movies | app/src/main/java/me/vickychijwani/popularmovies/event/events/MoviesLoadedEvent.java | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/entity/MovieResults.java
// public class MovieResults extends Results<Movie> {
//
// public enum SortCriteria {
// POPULARITY("popularity.desc"), RATING("vote_average.desc"), FAVORITES("favorites");
// public final String str;
// SortCriteria(String str) {
// this.str = str;
// }
// public int getId() {
// return this.str.hashCode();
// }
// public String toString() {
// return this.str;
// }
// }
//
// }
| import java.util.List;
import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.entity.MovieResults; | package me.vickychijwani.popularmovies.event.events;
public final class MoviesLoadedEvent {
public final List<Movie> movies; | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/entity/MovieResults.java
// public class MovieResults extends Results<Movie> {
//
// public enum SortCriteria {
// POPULARITY("popularity.desc"), RATING("vote_average.desc"), FAVORITES("favorites");
// public final String str;
// SortCriteria(String str) {
// this.str = str;
// }
// public int getId() {
// return this.str.hashCode();
// }
// public String toString() {
// return this.str;
// }
// }
//
// }
// Path: app/src/main/java/me/vickychijwani/popularmovies/event/events/MoviesLoadedEvent.java
import java.util.List;
import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.entity.MovieResults;
package me.vickychijwani.popularmovies.event.events;
public final class MoviesLoadedEvent {
public final List<Movie> movies; | public final MovieResults.SortCriteria sortCriteria; |
vickychijwani/udacity-p1-p2-popular-movies | app/src/main/java/me/vickychijwani/popularmovies/ui/ReviewActivity.java | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Review.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Review.class })
// public class Review extends RealmObject {
//
// @PrimaryKey
// private String id;
// private String author;
// private String content;
// private String url;
//
//
//
// public Review() {}
//
// public Review(@NonNull Review other) {
// this.id = other.getId();
// this.author = other.getAuthor();
// this.content = other.getContent();
// this.url = other.getUrl();
// }
//
// public static Parcelable toParcelable(Review review) {
// return Parcels.wrap(Review.class, review);
// }
//
// public static Review fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
//
//
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public static class RealmListParcelConverter extends
// me.vickychijwani.popularmovies.entity.RealmListParcelConverter<Review> {
// @Override
// public void itemToParcel(Review input, android.os.Parcel parcel) {
// parcel.writeParcelable(Parcels.wrap(Review.class, input), 0);
// }
//
// @Override
// public Review itemFromParcel(android.os.Parcel parcel) {
// return Parcels.unwrap(parcel.readParcelable(Review.class.getClassLoader()));
// }
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import butterknife.ButterKnife;
import me.vickychijwani.popularmovies.R;
import me.vickychijwani.popularmovies.entity.Review; | package me.vickychijwani.popularmovies.ui;
public class ReviewActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review);
ButterKnife.bind(this);
Bundle extras = getIntent().getExtras(); | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Review.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Review.class })
// public class Review extends RealmObject {
//
// @PrimaryKey
// private String id;
// private String author;
// private String content;
// private String url;
//
//
//
// public Review() {}
//
// public Review(@NonNull Review other) {
// this.id = other.getId();
// this.author = other.getAuthor();
// this.content = other.getContent();
// this.url = other.getUrl();
// }
//
// public static Parcelable toParcelable(Review review) {
// return Parcels.wrap(Review.class, review);
// }
//
// public static Review fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
//
//
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public static class RealmListParcelConverter extends
// me.vickychijwani.popularmovies.entity.RealmListParcelConverter<Review> {
// @Override
// public void itemToParcel(Review input, android.os.Parcel parcel) {
// parcel.writeParcelable(Parcels.wrap(Review.class, input), 0);
// }
//
// @Override
// public Review itemFromParcel(android.os.Parcel parcel) {
// return Parcels.unwrap(parcel.readParcelable(Review.class.getClassLoader()));
// }
// }
//
// }
// Path: app/src/main/java/me/vickychijwani/popularmovies/ui/ReviewActivity.java
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import butterknife.ButterKnife;
import me.vickychijwani.popularmovies.R;
import me.vickychijwani.popularmovies.entity.Review;
package me.vickychijwani.popularmovies.ui;
public class ReviewActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review);
ButterKnife.bind(this);
Bundle extras = getIntent().getExtras(); | Review review = Review.fromParcelable(extras.getParcelable(BundleKeys.REVIEW)); |
vickychijwani/udacity-p1-p2-popular-movies | app/src/main/java/me/vickychijwani/popularmovies/model/MovieDBApiService.java | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/entity/MovieResults.java
// public class MovieResults extends Results<Movie> {
//
// public enum SortCriteria {
// POPULARITY("popularity.desc"), RATING("vote_average.desc"), FAVORITES("favorites");
// public final String str;
// SortCriteria(String str) {
// this.str = str;
// }
// public int getId() {
// return this.str.hashCode();
// }
// public String toString() {
// return this.str;
// }
// }
//
// }
| import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.entity.MovieResults;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query; | package me.vickychijwani.popularmovies.model;
interface MovieDBApiService {
@GET("discover/movie?vote_count.gte=250") | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/entity/MovieResults.java
// public class MovieResults extends Results<Movie> {
//
// public enum SortCriteria {
// POPULARITY("popularity.desc"), RATING("vote_average.desc"), FAVORITES("favorites");
// public final String str;
// SortCriteria(String str) {
// this.str = str;
// }
// public int getId() {
// return this.str.hashCode();
// }
// public String toString() {
// return this.str;
// }
// }
//
// }
// Path: app/src/main/java/me/vickychijwani/popularmovies/model/MovieDBApiService.java
import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.entity.MovieResults;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
package me.vickychijwani.popularmovies.model;
interface MovieDBApiService {
@GET("discover/movie?vote_count.gte=250") | Call<MovieResults> fetchMovies(@Query("api_key") String apiKey, @Query("sort_by") String sortBy); |
vickychijwani/udacity-p1-p2-popular-movies | app/src/main/java/me/vickychijwani/popularmovies/model/MovieDBApiService.java | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/entity/MovieResults.java
// public class MovieResults extends Results<Movie> {
//
// public enum SortCriteria {
// POPULARITY("popularity.desc"), RATING("vote_average.desc"), FAVORITES("favorites");
// public final String str;
// SortCriteria(String str) {
// this.str = str;
// }
// public int getId() {
// return this.str.hashCode();
// }
// public String toString() {
// return this.str;
// }
// }
//
// }
| import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.entity.MovieResults;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query; | package me.vickychijwani.popularmovies.model;
interface MovieDBApiService {
@GET("discover/movie?vote_count.gte=250")
Call<MovieResults> fetchMovies(@Query("api_key") String apiKey, @Query("sort_by") String sortBy);
@GET("movie/{id}?append_to_response=videos,reviews") | // Path: app/src/main/java/me/vickychijwani/popularmovies/entity/Movie.java
// @RealmClass
// @Parcel(value = Parcel.Serialization.BEAN, analyze = { Movie.class })
// public class Movie extends RealmObject {
//
// @PrimaryKey
// private int id;
// private String title;
// private String posterPath;
// private String backdropPath;
//
// @SerializedName("overview")
// private String synopsis;
//
// @SerializedName("vote_average")
// private float rating;
//
// private Date releaseDate;
//
// // relationships
// private RealmList<Review> reviews = new RealmList<>();
// private RealmList<Video> videos = new RealmList<>();
//
// // transient fields are not serialized / deserialized by Gson
// private transient boolean isFavorite = false;
//
//
//
// public Movie() {}
//
// public Movie(@NonNull Movie other) {
// this.id = other.getId();
// this.title = other.getTitle();
// this.posterPath = other.getPosterPath();
// this.backdropPath = other.getBackdropPath();
// this.synopsis = other.getSynopsis();
// this.rating = other.getRating();
// this.releaseDate = other.getReleaseDate();
// this.isFavorite = other.isFavorite();
// this.reviews = new RealmList<>();
// if (other.getReviews() != null) {
// for (Review review : other.getReviews()) {
// this.reviews.add(new Review(review));
// }
// }
// this.videos = new RealmList<>();
// if (other.getVideos() != null) {
// for (Video video : other.getVideos()) {
// this.videos.add(new Video(video));
// }
// }
// }
//
// public static List<Video> getTrailers(Movie movie) {
// List<Video> trailers = new ArrayList<>();
// for (Video video : movie.getVideos()) {
// if (Video.TYPE_TRAILER.equals(video.getType())) {
// trailers.add(video);
// }
// }
// return trailers;
// }
//
// public static Parcelable toParcelable(Movie movie) {
// return Parcels.wrap(Movie.class, movie);
// }
//
// public static ArrayList<Parcelable> toParcelable(List<Movie> movies) {
// ArrayList<Parcelable> parcelables = new ArrayList<>(movies.size());
// for (Movie movie : movies) {
// parcelables.add(Parcels.wrap(Movie.class, movie));
// }
// return parcelables;
// }
//
// public static Movie fromParcelable(Parcelable parcelable) {
// return Parcels.unwrap(parcelable);
// }
//
// public static List<Movie> fromParcelable(List<Parcelable> parcelables) {
// List<Movie> movies = new ArrayList<>(parcelables.size());
// for (Parcelable parcelable : parcelables) {
// movies.add(Parcels.<Movie>unwrap(parcelable));
// }
// return movies;
// }
//
//
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getPosterPath() {
// return posterPath;
// }
//
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// public String getBackdropPath() {
// return backdropPath;
// }
//
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// public String getSynopsis() {
// return synopsis;
// }
//
// public void setSynopsis(String synopsis) {
// this.synopsis = synopsis;
// }
//
// public float getRating() {
// return rating;
// }
//
// public void setRating(float rating) {
// this.rating = rating;
// }
//
// public Date getReleaseDate() {
// return releaseDate;
// }
//
// public void setReleaseDate(Date releaseDate) {
// this.releaseDate = releaseDate;
// }
//
// public RealmList<Review> getReviews() {
// return reviews;
// }
//
// @ParcelPropertyConverter(Review.RealmListParcelConverter.class)
// public void setReviews(RealmList<Review> reviews) {
// this.reviews = reviews;
// }
//
// public RealmList<Video> getVideos() {
// return videos;
// }
//
// @ParcelPropertyConverter(Video.RealmListParcelConverter.class)
// public void setVideos(RealmList<Video> videos) {
// this.videos = videos;
// }
//
// public boolean isFavorite() {
// return isFavorite;
// }
//
// public void setFavorite(boolean favorite) {
// isFavorite = favorite;
// }
//
// }
//
// Path: app/src/main/java/me/vickychijwani/popularmovies/entity/MovieResults.java
// public class MovieResults extends Results<Movie> {
//
// public enum SortCriteria {
// POPULARITY("popularity.desc"), RATING("vote_average.desc"), FAVORITES("favorites");
// public final String str;
// SortCriteria(String str) {
// this.str = str;
// }
// public int getId() {
// return this.str.hashCode();
// }
// public String toString() {
// return this.str;
// }
// }
//
// }
// Path: app/src/main/java/me/vickychijwani/popularmovies/model/MovieDBApiService.java
import me.vickychijwani.popularmovies.entity.Movie;
import me.vickychijwani.popularmovies.entity.MovieResults;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;
package me.vickychijwani.popularmovies.model;
interface MovieDBApiService {
@GET("discover/movie?vote_count.gte=250")
Call<MovieResults> fetchMovies(@Query("api_key") String apiKey, @Query("sort_by") String sortBy);
@GET("movie/{id}?append_to_response=videos,reviews") | Call<Movie> fetchMovie(@Path("id") int id, @Query("api_key") String apiKey); |
vickychijwani/udacity-p1-p2-popular-movies | app/src/main/java/me/vickychijwani/popularmovies/ui/BaseFragment.java | // Path: app/src/main/java/me/vickychijwani/popularmovies/event/DataBusProvider.java
// public class DataBusProvider {
//
// private static final Bus mBus = new DataBus();
//
// private DataBusProvider() {}
//
// public static Bus getBus() { return mBus; }
//
// private static final class DataBus extends Bus {
// private static final String TAG = "DataBus";
//
// public DataBus() {
// super();
// log(Log.INFO, "INIT", "");
// }
//
// @Override
// public void register(Object object) {
// super.register(object);
// log(Log.INFO, "REG", object.getClass().getSimpleName());
// }
//
// @Override
// public void unregister(Object object) {
// log(Log.INFO, "UNREG", object.getClass().getSimpleName());
// super.unregister(object);
// }
//
// @Override
// public void post(Object event) {
// if (event instanceof DeadEvent) {
// String deadEventName = ((DeadEvent) event).event.getClass().getSimpleName();
// log(Log.WARN, "DEAD", "Dead event posted: " + deadEventName);
// } else {
// log(Log.DEBUG, "POST", event.toString());
// }
// super.post(event);
// }
//
// private void log(int priority, String type, String message) {
// if (BuildConfig.DEBUG || priority >= Log.WARN) {
// String logMsg = String.format("[%1$5s] %2$s on %3$s", type, message, toString());
// Log.println(priority, TAG, logMsg);
// }
// }
// }
//
// }
| import android.support.v4.app.Fragment;
import com.squareup.otto.Bus;
import butterknife.ButterKnife;
import me.vickychijwani.popularmovies.event.DataBusProvider; | package me.vickychijwani.popularmovies.ui;
public abstract class BaseFragment extends Fragment {
protected Bus getDataBus() { | // Path: app/src/main/java/me/vickychijwani/popularmovies/event/DataBusProvider.java
// public class DataBusProvider {
//
// private static final Bus mBus = new DataBus();
//
// private DataBusProvider() {}
//
// public static Bus getBus() { return mBus; }
//
// private static final class DataBus extends Bus {
// private static final String TAG = "DataBus";
//
// public DataBus() {
// super();
// log(Log.INFO, "INIT", "");
// }
//
// @Override
// public void register(Object object) {
// super.register(object);
// log(Log.INFO, "REG", object.getClass().getSimpleName());
// }
//
// @Override
// public void unregister(Object object) {
// log(Log.INFO, "UNREG", object.getClass().getSimpleName());
// super.unregister(object);
// }
//
// @Override
// public void post(Object event) {
// if (event instanceof DeadEvent) {
// String deadEventName = ((DeadEvent) event).event.getClass().getSimpleName();
// log(Log.WARN, "DEAD", "Dead event posted: " + deadEventName);
// } else {
// log(Log.DEBUG, "POST", event.toString());
// }
// super.post(event);
// }
//
// private void log(int priority, String type, String message) {
// if (BuildConfig.DEBUG || priority >= Log.WARN) {
// String logMsg = String.format("[%1$5s] %2$s on %3$s", type, message, toString());
// Log.println(priority, TAG, logMsg);
// }
// }
// }
//
// }
// Path: app/src/main/java/me/vickychijwani/popularmovies/ui/BaseFragment.java
import android.support.v4.app.Fragment;
import com.squareup.otto.Bus;
import butterknife.ButterKnife;
import me.vickychijwani.popularmovies.event.DataBusProvider;
package me.vickychijwani.popularmovies.ui;
public abstract class BaseFragment extends Fragment {
protected Bus getDataBus() { | return DataBusProvider.getBus(); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/api/Disease.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/DiseaseCraft.java
// @SuppressWarnings("unchecked")
// @Mod(modid = References.MODID, name = References.NAME, version = References.VERSION)
// public class DiseaseCraft {
//
// @SidedProxy(clientSide = "mc.Mitchellbrine.diseaseCraft.proxy.ClientProxy", serverSide = "mc.Mitchellbrine.diseaseCraft.proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static Logger logger = LogManager.getLogger(References.MODID);
//
// public static ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
//
// public static boolean shouldUpdate = false;
//
// public static final double MC_VERSION = 7.10;
//
// @Mod.Instance
// public static DiseaseCraft instance;
//
// public DiseaseCraft() {
// new ClassHelper();
// }
//
// /**
// * The order in disease loading is such:
// *
// * Pre-init: Register all the JSON diseases
// * Init: Allow mods to register their diseases in code
// * Post-init: Everything Disease related should be finished processing.
// *
// */
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// ConfigRegistry.init(new File((FMLInjectionData.data()[6]) + File.separator + "config" + File.separator));
// ConfigRegistry.doConfig(new Configuration(event.getSuggestedConfigurationFile()));
//
//
// proxy.registerStuff();
//
// if (!ConfigRegistry.useNativeDiseases && DiseaseCraft.shouldUpdate && ConfigRegistry.autoUpdate) {
// DiseaseDownloader.init();
// }
//
// /*
//
// THE FOLLOWING WAS TEST CODE!
//
// try {
// Class clazz = Class.forName("mc.Mitchellbrine.diseaseCraft.DiseaseCraft");
// clazz.getMethod("hello").setAccessible(true);
// Method method = clazz.getMethod("hello");
// if (method.getGenericReturnType() == Boolean.TYPE) {
// boolean worked = (Boolean)method.invoke(this);
// System.out.println(worked);
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
//
// Disease test = new Disease("testDisease");
//
// Disease domainTest = new Disease("blahblah:testTwo");
//
// Disease newerTest = new Disease("blahTwo:newer");
// newerTest.setMinimumVersion(3.0);
//
// Disease effectTest = new Disease("blahThree:effect");
// for (int i = 1; i <= 16;i++) {
// effectTest.addEffect(i);
// }
//
// Diseases.registerDisease(test);
// Diseases.registerDisease(domainTest);
// Diseases.registerDisease(newerTest);
// Diseases.registerDisease(effectTest);
//
// System.out.println(test.isRequirementMet());
// System.out.println(test);
//
// System.out.println(domainTest.isRequirementMet());
// System.out.println(domainTest);
//
// System.out.println(newerTest.isRequirementMet());
// System.out.println(newerTest);
//
// System.out.println(effectTest.isRequirementMet());
// System.out.println(effectTest); */
//
// new Diseases();
//
// DiseaseManager.findAllDiseases();
//
// ConfigRegistry.STATE = 0;
// ConfigRegistry.triggerState();
//
// registerAllEvents();
// EntityRegistration.init();
// ItemRegistry.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(DiseaseCraft.instance, new GuiHandler());
// PacketHandler.init();
//
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DiseaseManager.readAllJSONs();
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void server(FMLServerStartingEvent event) {
// ConfigRegistry.triggerState();
// }
//
// public boolean hello() {
// System.out.println("Hello world!");
// return true;
// }
//
// private void registerAllEvents() {
// MinecraftForge.EVENT_BUS.register(new ContractingEvents());
// FMLCommonHandler.instance().bus().register(new ContractingEvents());
// MinecraftForge.ORE_GEN_BUS.register(new ContractingEvents());
// MinecraftForge.TERRAIN_GEN_BUS.register(new ContractingEvents());
//
// if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
// MinecraftForge.EVENT_BUS.register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// FMLCommonHandler.instance().bus().register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// }
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/utils/References.java
// public class References {
//
// public static final String MODID = "DiseaseCraft";
// public static final String NAME = "DiseaseCraft";
// public static final String VERSION = "3.0";
//
// }
| import mc.Mitchellbrine.diseaseCraft.DiseaseCraft;
import mc.Mitchellbrine.diseaseCraft.utils.References;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | package mc.Mitchellbrine.diseaseCraft.api;
/**
* Created by Mitchellbrine on 2015.
*/
public class Disease {
private String identifier;
private String domain;
private String lore;
private List<String> waysToContract;
private Map<String,Object[]> contractParameters;
public List<Integer> effects;
public int level;
private int deathRate = -1;
private double minimumRequiredVersion;
private boolean isJoke, isVanilla;
public String bloodType;
public Disease(String id) { | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/DiseaseCraft.java
// @SuppressWarnings("unchecked")
// @Mod(modid = References.MODID, name = References.NAME, version = References.VERSION)
// public class DiseaseCraft {
//
// @SidedProxy(clientSide = "mc.Mitchellbrine.diseaseCraft.proxy.ClientProxy", serverSide = "mc.Mitchellbrine.diseaseCraft.proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static Logger logger = LogManager.getLogger(References.MODID);
//
// public static ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
//
// public static boolean shouldUpdate = false;
//
// public static final double MC_VERSION = 7.10;
//
// @Mod.Instance
// public static DiseaseCraft instance;
//
// public DiseaseCraft() {
// new ClassHelper();
// }
//
// /**
// * The order in disease loading is such:
// *
// * Pre-init: Register all the JSON diseases
// * Init: Allow mods to register their diseases in code
// * Post-init: Everything Disease related should be finished processing.
// *
// */
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// ConfigRegistry.init(new File((FMLInjectionData.data()[6]) + File.separator + "config" + File.separator));
// ConfigRegistry.doConfig(new Configuration(event.getSuggestedConfigurationFile()));
//
//
// proxy.registerStuff();
//
// if (!ConfigRegistry.useNativeDiseases && DiseaseCraft.shouldUpdate && ConfigRegistry.autoUpdate) {
// DiseaseDownloader.init();
// }
//
// /*
//
// THE FOLLOWING WAS TEST CODE!
//
// try {
// Class clazz = Class.forName("mc.Mitchellbrine.diseaseCraft.DiseaseCraft");
// clazz.getMethod("hello").setAccessible(true);
// Method method = clazz.getMethod("hello");
// if (method.getGenericReturnType() == Boolean.TYPE) {
// boolean worked = (Boolean)method.invoke(this);
// System.out.println(worked);
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
//
// Disease test = new Disease("testDisease");
//
// Disease domainTest = new Disease("blahblah:testTwo");
//
// Disease newerTest = new Disease("blahTwo:newer");
// newerTest.setMinimumVersion(3.0);
//
// Disease effectTest = new Disease("blahThree:effect");
// for (int i = 1; i <= 16;i++) {
// effectTest.addEffect(i);
// }
//
// Diseases.registerDisease(test);
// Diseases.registerDisease(domainTest);
// Diseases.registerDisease(newerTest);
// Diseases.registerDisease(effectTest);
//
// System.out.println(test.isRequirementMet());
// System.out.println(test);
//
// System.out.println(domainTest.isRequirementMet());
// System.out.println(domainTest);
//
// System.out.println(newerTest.isRequirementMet());
// System.out.println(newerTest);
//
// System.out.println(effectTest.isRequirementMet());
// System.out.println(effectTest); */
//
// new Diseases();
//
// DiseaseManager.findAllDiseases();
//
// ConfigRegistry.STATE = 0;
// ConfigRegistry.triggerState();
//
// registerAllEvents();
// EntityRegistration.init();
// ItemRegistry.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(DiseaseCraft.instance, new GuiHandler());
// PacketHandler.init();
//
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DiseaseManager.readAllJSONs();
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void server(FMLServerStartingEvent event) {
// ConfigRegistry.triggerState();
// }
//
// public boolean hello() {
// System.out.println("Hello world!");
// return true;
// }
//
// private void registerAllEvents() {
// MinecraftForge.EVENT_BUS.register(new ContractingEvents());
// FMLCommonHandler.instance().bus().register(new ContractingEvents());
// MinecraftForge.ORE_GEN_BUS.register(new ContractingEvents());
// MinecraftForge.TERRAIN_GEN_BUS.register(new ContractingEvents());
//
// if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
// MinecraftForge.EVENT_BUS.register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// FMLCommonHandler.instance().bus().register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// }
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/utils/References.java
// public class References {
//
// public static final String MODID = "DiseaseCraft";
// public static final String NAME = "DiseaseCraft";
// public static final String VERSION = "3.0";
//
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/api/Disease.java
import mc.Mitchellbrine.diseaseCraft.DiseaseCraft;
import mc.Mitchellbrine.diseaseCraft.utils.References;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package mc.Mitchellbrine.diseaseCraft.api;
/**
* Created by Mitchellbrine on 2015.
*/
public class Disease {
private String identifier;
private String domain;
private String lore;
private List<String> waysToContract;
private Map<String,Object[]> contractParameters;
public List<Integer> effects;
public int level;
private int deathRate = -1;
private double minimumRequiredVersion;
private boolean isJoke, isVanilla;
public String bloodType;
public Disease(String id) { | this.domain = "DiseaseCraft"; |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/client/render/RenderRat.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
| import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import net.minecraft.client.model.ModelSilverfish;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation; | package mc.Mitchellbrine.diseaseCraft.client.render;
/**
* Created by Mitchellbrine on 2015.
*/
public class RenderRat extends RenderLiving {
public ModelSilverfish model;
private static final ResourceLocation rat = new ResourceLocation("DiseaseCraft:textures/mob/rat.png");
private static final ResourceLocation scaryRat = new ResourceLocation("DiseaseCraft:textures/mob/rat_scary.png");
public static String room1People = "Lomeli12 azreth allout58 mage_kkaylium YSPilot sci4me";
public RenderRat()
{
super(new ModelSilverfish(), 0.3F);
}
| // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/render/RenderRat.java
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import net.minecraft.client.model.ModelSilverfish;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;
package mc.Mitchellbrine.diseaseCraft.client.render;
/**
* Created by Mitchellbrine on 2015.
*/
public class RenderRat extends RenderLiving {
public ModelSilverfish model;
private static final ResourceLocation rat = new ResourceLocation("DiseaseCraft:textures/mob/rat.png");
private static final ResourceLocation scaryRat = new ResourceLocation("DiseaseCraft:textures/mob/rat_scary.png");
public static String room1People = "Lomeli12 azreth allout58 mage_kkaylium YSPilot sci4me";
public RenderRat()
{
super(new ModelSilverfish(), 0.3F);
}
| protected ResourceLocation getEntityTexture(EntityRat rat) |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/utils/ClassHelper.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/api/Module.java
// public abstract class Module {
//
// public abstract void preInit();
//
// public abstract void init();
//
// public abstract void postInit();
//
// public abstract void serverStart();
//
// }
| import cpw.mods.fml.common.DummyModContainer;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.discovery.ASMDataTable;
import mc.Mitchellbrine.diseaseCraft.api.DCModule;
import mc.Mitchellbrine.diseaseCraft.api.Module;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; | package mc.Mitchellbrine.diseaseCraft.utils;
/**
* Created by Mitchellbrine on 2015.
*/
public class ClassHelper {
public static Map<String,DCModule> modules; | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/api/Module.java
// public abstract class Module {
//
// public abstract void preInit();
//
// public abstract void init();
//
// public abstract void postInit();
//
// public abstract void serverStart();
//
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/utils/ClassHelper.java
import cpw.mods.fml.common.DummyModContainer;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.discovery.ASMDataTable;
import mc.Mitchellbrine.diseaseCraft.api.DCModule;
import mc.Mitchellbrine.diseaseCraft.api.Module;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
package mc.Mitchellbrine.diseaseCraft.utils;
/**
* Created by Mitchellbrine on 2015.
*/
public class ClassHelper {
public static Map<String,DCModule> modules; | public static Map<DCModule,Module> moduleMap; |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/modules/ModuleJoke.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/api/Module.java
// public abstract class Module {
//
// public abstract void preInit();
//
// public abstract void init();
//
// public abstract void postInit();
//
// public abstract void serverStart();
//
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/jokeDisease/JokeEvents.java
// public class JokeEvents {
//
// @SubscribeEvent
// public void livingUpdate(DiseaseEvent.DiseaseTickEvent event) {
// if (DiseaseHelper.diseaseExists("shrekRabies") && event.disease == DiseaseHelper.getDiseaseInstance("shrekRabies")) {
// int posX = MathHelper.floor_double(event.entityLiving.posX);
// int posY = MathHelper.floor_double(event.entityLiving.posY);
// int posZ = MathHelper.floor_double(event.entityLiving.posZ);
//
// if ((event.entityLiving.worldObj.getBlock(posX, posY, posZ).getMaterial() == Material.water || event.entityLiving.worldObj.getBlock(posX,posY-1,posZ).getMaterial() == Material.water) && event.entityLiving.worldObj.getBiomeGenForCoordsBody(posX,posZ) != BiomeGenBase.swampland) {
// if (event.entityLiving.worldObj.getTotalWorldTime() % 20 == 0) {
// event.entityLiving.attackEntityFrom(ModuleJoke.shrekDamage,1.0F);
// if (!event.entityLiving.worldObj.isRemote) {
// if (GenericEffects.rand.nextInt(3) == 0)
// event.entityLiving.worldObj.playSoundAtEntity(event.entityLiving, "DiseaseCraft:mySwamp", 1.0f, 1.0f);
// }
// }
// }
// }
// }
//
// @SubscribeEvent
// public void death(LivingDeathEvent event) {
// if (event.source == ModuleJoke.shrekDamage) {
// if (GenericEffects.rand.nextInt(2) == 0) {
// event.entityLiving.worldObj.playSoundAtEntity(event.entityLiving, "DiseaseCraft:neverOgre", 1.0f, 1.0f);
// } else {
// event.entityLiving.worldObj.playSoundAtEntity(event.entityLiving, "DiseaseCraft:allOgre", 1.0f, 1.0f);
// }
// }
// }
//
// }
| import cpw.mods.fml.common.FMLCommonHandler;
import mc.Mitchellbrine.diseaseCraft.api.DCModule;
import mc.Mitchellbrine.diseaseCraft.api.Module;
import mc.Mitchellbrine.diseaseCraft.modules.jokeDisease.JokeEvents;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.MinecraftForge; | package mc.Mitchellbrine.diseaseCraft.modules;
/**
* Created by Mitchellbrine on 2015.
*/
@DCModule(id = "jokeDisease",modid = "DiseaseCraft",dcVersion = "2.0",version = "1.0",canBeDisabled = true,isEnabled = false)
public class ModuleJoke extends Module{
public static DamageSource shrekDamage = new DamageSource("shrek").setDamageBypassesArmor().setDifficultyScaled();
@Override
public void preInit() { | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/api/Module.java
// public abstract class Module {
//
// public abstract void preInit();
//
// public abstract void init();
//
// public abstract void postInit();
//
// public abstract void serverStart();
//
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/jokeDisease/JokeEvents.java
// public class JokeEvents {
//
// @SubscribeEvent
// public void livingUpdate(DiseaseEvent.DiseaseTickEvent event) {
// if (DiseaseHelper.diseaseExists("shrekRabies") && event.disease == DiseaseHelper.getDiseaseInstance("shrekRabies")) {
// int posX = MathHelper.floor_double(event.entityLiving.posX);
// int posY = MathHelper.floor_double(event.entityLiving.posY);
// int posZ = MathHelper.floor_double(event.entityLiving.posZ);
//
// if ((event.entityLiving.worldObj.getBlock(posX, posY, posZ).getMaterial() == Material.water || event.entityLiving.worldObj.getBlock(posX,posY-1,posZ).getMaterial() == Material.water) && event.entityLiving.worldObj.getBiomeGenForCoordsBody(posX,posZ) != BiomeGenBase.swampland) {
// if (event.entityLiving.worldObj.getTotalWorldTime() % 20 == 0) {
// event.entityLiving.attackEntityFrom(ModuleJoke.shrekDamage,1.0F);
// if (!event.entityLiving.worldObj.isRemote) {
// if (GenericEffects.rand.nextInt(3) == 0)
// event.entityLiving.worldObj.playSoundAtEntity(event.entityLiving, "DiseaseCraft:mySwamp", 1.0f, 1.0f);
// }
// }
// }
// }
// }
//
// @SubscribeEvent
// public void death(LivingDeathEvent event) {
// if (event.source == ModuleJoke.shrekDamage) {
// if (GenericEffects.rand.nextInt(2) == 0) {
// event.entityLiving.worldObj.playSoundAtEntity(event.entityLiving, "DiseaseCraft:neverOgre", 1.0f, 1.0f);
// } else {
// event.entityLiving.worldObj.playSoundAtEntity(event.entityLiving, "DiseaseCraft:allOgre", 1.0f, 1.0f);
// }
// }
// }
//
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/ModuleJoke.java
import cpw.mods.fml.common.FMLCommonHandler;
import mc.Mitchellbrine.diseaseCraft.api.DCModule;
import mc.Mitchellbrine.diseaseCraft.api.Module;
import mc.Mitchellbrine.diseaseCraft.modules.jokeDisease.JokeEvents;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.MinecraftForge;
package mc.Mitchellbrine.diseaseCraft.modules;
/**
* Created by Mitchellbrine on 2015.
*/
@DCModule(id = "jokeDisease",modid = "DiseaseCraft",dcVersion = "2.0",version = "1.0",canBeDisabled = true,isEnabled = false)
public class ModuleJoke extends Module{
public static DamageSource shrekDamage = new DamageSource("shrek").setDamageBypassesArmor().setDifficultyScaled();
@Override
public void preInit() { | MinecraftForge.EVENT_BUS.register(new JokeEvents()); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/client/gui/book/GuiBook.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/containers/GuiBookContainer.java
// public class GuiBookContainer extends Container{
// @Override
// public boolean canInteractWith(EntityPlayer p_75145_1_) {
// return false;
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/utils/References.java
// public class References {
//
// public static final String MODID = "DiseaseCraft";
// public static final String NAME = "DiseaseCraft";
// public static final String VERSION = "3.0";
//
// }
| import mc.Mitchellbrine.diseaseCraft.containers.GuiBookContainer;
import mc.Mitchellbrine.diseaseCraft.utils.References;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List; | package mc.Mitchellbrine.diseaseCraft.client.gui.book;
public abstract class GuiBook extends GuiContainer
{
public int page, rot, del;
public boolean prevHover, nextHover;
public World world;
protected final List<GuiTab> tabs;
protected GuiTab activeTab;
protected EntityPlayer player;
public GuiBook(EntityPlayer player)
{ | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/containers/GuiBookContainer.java
// public class GuiBookContainer extends Container{
// @Override
// public boolean canInteractWith(EntityPlayer p_75145_1_) {
// return false;
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/utils/References.java
// public class References {
//
// public static final String MODID = "DiseaseCraft";
// public static final String NAME = "DiseaseCraft";
// public static final String VERSION = "3.0";
//
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/gui/book/GuiBook.java
import mc.Mitchellbrine.diseaseCraft.containers.GuiBookContainer;
import mc.Mitchellbrine.diseaseCraft.utils.References;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
package mc.Mitchellbrine.diseaseCraft.client.gui.book;
public abstract class GuiBook extends GuiContainer
{
public int page, rot, del;
public boolean prevHover, nextHover;
public World world;
protected final List<GuiTab> tabs;
protected GuiTab activeTab;
protected EntityPlayer player;
public GuiBook(EntityPlayer player)
{ | super(new GuiBookContainer()); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/client/gui/book/GuiBook.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/containers/GuiBookContainer.java
// public class GuiBookContainer extends Container{
// @Override
// public boolean canInteractWith(EntityPlayer p_75145_1_) {
// return false;
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/utils/References.java
// public class References {
//
// public static final String MODID = "DiseaseCraft";
// public static final String NAME = "DiseaseCraft";
// public static final String VERSION = "3.0";
//
// }
| import mc.Mitchellbrine.diseaseCraft.containers.GuiBookContainer;
import mc.Mitchellbrine.diseaseCraft.utils.References;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List; | public World world;
protected final List<GuiTab> tabs;
protected GuiTab activeTab;
protected EntityPlayer player;
public GuiBook(EntityPlayer player)
{
super(new GuiBookContainer());
page = 1;
rot = 0;
del = 0;
this.world = player.worldObj;
this.player = player;
tabs = new ArrayList<GuiTab>();
}
@Override
public void initGui() {
super.initGui();
}
@Override
protected void drawGuiContainerBackgroundLayer(float f, int i, int j)
{
nextHover = false;
prevHover = false;
if(del == 0) rot++;
del++;
if(del >= 2) del = 0; | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/containers/GuiBookContainer.java
// public class GuiBookContainer extends Container{
// @Override
// public boolean canInteractWith(EntityPlayer p_75145_1_) {
// return false;
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/utils/References.java
// public class References {
//
// public static final String MODID = "DiseaseCraft";
// public static final String NAME = "DiseaseCraft";
// public static final String VERSION = "3.0";
//
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/gui/book/GuiBook.java
import mc.Mitchellbrine.diseaseCraft.containers.GuiBookContainer;
import mc.Mitchellbrine.diseaseCraft.utils.References;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
public World world;
protected final List<GuiTab> tabs;
protected GuiTab activeTab;
protected EntityPlayer player;
public GuiBook(EntityPlayer player)
{
super(new GuiBookContainer());
page = 1;
rot = 0;
del = 0;
this.world = player.worldObj;
this.player = player;
tabs = new ArrayList<GuiTab>();
}
@Override
public void initGui() {
super.initGui();
}
@Override
protected void drawGuiContainerBackgroundLayer(float f, int i, int j)
{
nextHover = false;
prevHover = false;
if(del == 0) rot++;
del++;
if(del >= 2) del = 0; | Minecraft.getMinecraft().getTextureManager().bindTexture(new ResourceLocation(References.MODID.toLowerCase(), "textures/guis/guidePage.png")); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/proxy/ClientProxy.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/render/RenderRat.java
// public class RenderRat extends RenderLiving {
//
// public ModelSilverfish model;
//
// private static final ResourceLocation rat = new ResourceLocation("DiseaseCraft:textures/mob/rat.png");
// private static final ResourceLocation scaryRat = new ResourceLocation("DiseaseCraft:textures/mob/rat_scary.png");
//
// public static String room1People = "Lomeli12 azreth allout58 mage_kkaylium YSPilot sci4me";
//
// public RenderRat()
// {
// super(new ModelSilverfish(), 0.3F);
// }
//
// protected ResourceLocation getEntityTexture(EntityRat rat)
// {
// if (rat.getAITarget() != null) {
// return scaryRat;
// }
// return this.rat;
// }
// protected float getDeathMaxRotation(EntityLivingBase par1EntityLivingBase)
// {
// return 180.0F;
// }
//
// protected ResourceLocation getEntityTexture(Entity par1Entity)
// {
// return this.getEntityTexture((EntityRat)par1Entity);
// }
//
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
| import mc.Mitchellbrine.diseaseCraft.client.render.RenderRat;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import net.minecraft.client.Minecraft;
import cpw.mods.fml.client.registry.RenderingRegistry; | package mc.Mitchellbrine.diseaseCraft.proxy;
/**
* Created by Mitchellbrine on 2015.
*/
public class ClientProxy extends CommonProxy {
@Override
public void registerStuff() { | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/render/RenderRat.java
// public class RenderRat extends RenderLiving {
//
// public ModelSilverfish model;
//
// private static final ResourceLocation rat = new ResourceLocation("DiseaseCraft:textures/mob/rat.png");
// private static final ResourceLocation scaryRat = new ResourceLocation("DiseaseCraft:textures/mob/rat_scary.png");
//
// public static String room1People = "Lomeli12 azreth allout58 mage_kkaylium YSPilot sci4me";
//
// public RenderRat()
// {
// super(new ModelSilverfish(), 0.3F);
// }
//
// protected ResourceLocation getEntityTexture(EntityRat rat)
// {
// if (rat.getAITarget() != null) {
// return scaryRat;
// }
// return this.rat;
// }
// protected float getDeathMaxRotation(EntityLivingBase par1EntityLivingBase)
// {
// return 180.0F;
// }
//
// protected ResourceLocation getEntityTexture(Entity par1Entity)
// {
// return this.getEntityTexture((EntityRat)par1Entity);
// }
//
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/proxy/ClientProxy.java
import mc.Mitchellbrine.diseaseCraft.client.render.RenderRat;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import net.minecraft.client.Minecraft;
import cpw.mods.fml.client.registry.RenderingRegistry;
package mc.Mitchellbrine.diseaseCraft.proxy;
/**
* Created by Mitchellbrine on 2015.
*/
public class ClientProxy extends CommonProxy {
@Override
public void registerStuff() { | RenderingRegistry.registerEntityRenderingHandler(EntityRat.class, new RenderRat()); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/proxy/ClientProxy.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/render/RenderRat.java
// public class RenderRat extends RenderLiving {
//
// public ModelSilverfish model;
//
// private static final ResourceLocation rat = new ResourceLocation("DiseaseCraft:textures/mob/rat.png");
// private static final ResourceLocation scaryRat = new ResourceLocation("DiseaseCraft:textures/mob/rat_scary.png");
//
// public static String room1People = "Lomeli12 azreth allout58 mage_kkaylium YSPilot sci4me";
//
// public RenderRat()
// {
// super(new ModelSilverfish(), 0.3F);
// }
//
// protected ResourceLocation getEntityTexture(EntityRat rat)
// {
// if (rat.getAITarget() != null) {
// return scaryRat;
// }
// return this.rat;
// }
// protected float getDeathMaxRotation(EntityLivingBase par1EntityLivingBase)
// {
// return 180.0F;
// }
//
// protected ResourceLocation getEntityTexture(Entity par1Entity)
// {
// return this.getEntityTexture((EntityRat)par1Entity);
// }
//
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
| import mc.Mitchellbrine.diseaseCraft.client.render.RenderRat;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import net.minecraft.client.Minecraft;
import cpw.mods.fml.client.registry.RenderingRegistry; | package mc.Mitchellbrine.diseaseCraft.proxy;
/**
* Created by Mitchellbrine on 2015.
*/
public class ClientProxy extends CommonProxy {
@Override
public void registerStuff() { | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/render/RenderRat.java
// public class RenderRat extends RenderLiving {
//
// public ModelSilverfish model;
//
// private static final ResourceLocation rat = new ResourceLocation("DiseaseCraft:textures/mob/rat.png");
// private static final ResourceLocation scaryRat = new ResourceLocation("DiseaseCraft:textures/mob/rat_scary.png");
//
// public static String room1People = "Lomeli12 azreth allout58 mage_kkaylium YSPilot sci4me";
//
// public RenderRat()
// {
// super(new ModelSilverfish(), 0.3F);
// }
//
// protected ResourceLocation getEntityTexture(EntityRat rat)
// {
// if (rat.getAITarget() != null) {
// return scaryRat;
// }
// return this.rat;
// }
// protected float getDeathMaxRotation(EntityLivingBase par1EntityLivingBase)
// {
// return 180.0F;
// }
//
// protected ResourceLocation getEntityTexture(Entity par1Entity)
// {
// return this.getEntityTexture((EntityRat)par1Entity);
// }
//
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/proxy/ClientProxy.java
import mc.Mitchellbrine.diseaseCraft.client.render.RenderRat;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import net.minecraft.client.Minecraft;
import cpw.mods.fml.client.registry.RenderingRegistry;
package mc.Mitchellbrine.diseaseCraft.proxy;
/**
* Created by Mitchellbrine on 2015.
*/
public class ClientProxy extends CommonProxy {
@Override
public void registerStuff() { | RenderingRegistry.registerEntityRenderingHandler(EntityRat.class, new RenderRat()); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRegistration.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/DiseaseCraft.java
// @SuppressWarnings("unchecked")
// @Mod(modid = References.MODID, name = References.NAME, version = References.VERSION)
// public class DiseaseCraft {
//
// @SidedProxy(clientSide = "mc.Mitchellbrine.diseaseCraft.proxy.ClientProxy", serverSide = "mc.Mitchellbrine.diseaseCraft.proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static Logger logger = LogManager.getLogger(References.MODID);
//
// public static ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
//
// public static boolean shouldUpdate = false;
//
// public static final double MC_VERSION = 7.10;
//
// @Mod.Instance
// public static DiseaseCraft instance;
//
// public DiseaseCraft() {
// new ClassHelper();
// }
//
// /**
// * The order in disease loading is such:
// *
// * Pre-init: Register all the JSON diseases
// * Init: Allow mods to register their diseases in code
// * Post-init: Everything Disease related should be finished processing.
// *
// */
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// ConfigRegistry.init(new File((FMLInjectionData.data()[6]) + File.separator + "config" + File.separator));
// ConfigRegistry.doConfig(new Configuration(event.getSuggestedConfigurationFile()));
//
//
// proxy.registerStuff();
//
// if (!ConfigRegistry.useNativeDiseases && DiseaseCraft.shouldUpdate && ConfigRegistry.autoUpdate) {
// DiseaseDownloader.init();
// }
//
// /*
//
// THE FOLLOWING WAS TEST CODE!
//
// try {
// Class clazz = Class.forName("mc.Mitchellbrine.diseaseCraft.DiseaseCraft");
// clazz.getMethod("hello").setAccessible(true);
// Method method = clazz.getMethod("hello");
// if (method.getGenericReturnType() == Boolean.TYPE) {
// boolean worked = (Boolean)method.invoke(this);
// System.out.println(worked);
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
//
// Disease test = new Disease("testDisease");
//
// Disease domainTest = new Disease("blahblah:testTwo");
//
// Disease newerTest = new Disease("blahTwo:newer");
// newerTest.setMinimumVersion(3.0);
//
// Disease effectTest = new Disease("blahThree:effect");
// for (int i = 1; i <= 16;i++) {
// effectTest.addEffect(i);
// }
//
// Diseases.registerDisease(test);
// Diseases.registerDisease(domainTest);
// Diseases.registerDisease(newerTest);
// Diseases.registerDisease(effectTest);
//
// System.out.println(test.isRequirementMet());
// System.out.println(test);
//
// System.out.println(domainTest.isRequirementMet());
// System.out.println(domainTest);
//
// System.out.println(newerTest.isRequirementMet());
// System.out.println(newerTest);
//
// System.out.println(effectTest.isRequirementMet());
// System.out.println(effectTest); */
//
// new Diseases();
//
// DiseaseManager.findAllDiseases();
//
// ConfigRegistry.STATE = 0;
// ConfigRegistry.triggerState();
//
// registerAllEvents();
// EntityRegistration.init();
// ItemRegistry.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(DiseaseCraft.instance, new GuiHandler());
// PacketHandler.init();
//
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DiseaseManager.readAllJSONs();
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void server(FMLServerStartingEvent event) {
// ConfigRegistry.triggerState();
// }
//
// public boolean hello() {
// System.out.println("Hello world!");
// return true;
// }
//
// private void registerAllEvents() {
// MinecraftForge.EVENT_BUS.register(new ContractingEvents());
// FMLCommonHandler.instance().bus().register(new ContractingEvents());
// MinecraftForge.ORE_GEN_BUS.register(new ContractingEvents());
// MinecraftForge.TERRAIN_GEN_BUS.register(new ContractingEvents());
//
// if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
// MinecraftForge.EVENT_BUS.register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// FMLCommonHandler.instance().bus().register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// }
// }
// }
| import mc.Mitchellbrine.diseaseCraft.DiseaseCraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import cpw.mods.fml.common.registry.EntityRegistry; | package mc.Mitchellbrine.diseaseCraft.entity;
/**
* Created by Mitchellbrine on 2015.
*/
public class EntityRegistration {
private static int START_ID = 500;
public static void init() {
registerEntity(EntityRat.class,"rat",7237230,3158064);
}
@SuppressWarnings("unchecked")
private static void registerEntity(Class<? extends Entity> entity, String name) {
int id = getUniqueId(); | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/DiseaseCraft.java
// @SuppressWarnings("unchecked")
// @Mod(modid = References.MODID, name = References.NAME, version = References.VERSION)
// public class DiseaseCraft {
//
// @SidedProxy(clientSide = "mc.Mitchellbrine.diseaseCraft.proxy.ClientProxy", serverSide = "mc.Mitchellbrine.diseaseCraft.proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static Logger logger = LogManager.getLogger(References.MODID);
//
// public static ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
//
// public static boolean shouldUpdate = false;
//
// public static final double MC_VERSION = 7.10;
//
// @Mod.Instance
// public static DiseaseCraft instance;
//
// public DiseaseCraft() {
// new ClassHelper();
// }
//
// /**
// * The order in disease loading is such:
// *
// * Pre-init: Register all the JSON diseases
// * Init: Allow mods to register their diseases in code
// * Post-init: Everything Disease related should be finished processing.
// *
// */
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// ConfigRegistry.init(new File((FMLInjectionData.data()[6]) + File.separator + "config" + File.separator));
// ConfigRegistry.doConfig(new Configuration(event.getSuggestedConfigurationFile()));
//
//
// proxy.registerStuff();
//
// if (!ConfigRegistry.useNativeDiseases && DiseaseCraft.shouldUpdate && ConfigRegistry.autoUpdate) {
// DiseaseDownloader.init();
// }
//
// /*
//
// THE FOLLOWING WAS TEST CODE!
//
// try {
// Class clazz = Class.forName("mc.Mitchellbrine.diseaseCraft.DiseaseCraft");
// clazz.getMethod("hello").setAccessible(true);
// Method method = clazz.getMethod("hello");
// if (method.getGenericReturnType() == Boolean.TYPE) {
// boolean worked = (Boolean)method.invoke(this);
// System.out.println(worked);
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
//
// Disease test = new Disease("testDisease");
//
// Disease domainTest = new Disease("blahblah:testTwo");
//
// Disease newerTest = new Disease("blahTwo:newer");
// newerTest.setMinimumVersion(3.0);
//
// Disease effectTest = new Disease("blahThree:effect");
// for (int i = 1; i <= 16;i++) {
// effectTest.addEffect(i);
// }
//
// Diseases.registerDisease(test);
// Diseases.registerDisease(domainTest);
// Diseases.registerDisease(newerTest);
// Diseases.registerDisease(effectTest);
//
// System.out.println(test.isRequirementMet());
// System.out.println(test);
//
// System.out.println(domainTest.isRequirementMet());
// System.out.println(domainTest);
//
// System.out.println(newerTest.isRequirementMet());
// System.out.println(newerTest);
//
// System.out.println(effectTest.isRequirementMet());
// System.out.println(effectTest); */
//
// new Diseases();
//
// DiseaseManager.findAllDiseases();
//
// ConfigRegistry.STATE = 0;
// ConfigRegistry.triggerState();
//
// registerAllEvents();
// EntityRegistration.init();
// ItemRegistry.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(DiseaseCraft.instance, new GuiHandler());
// PacketHandler.init();
//
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DiseaseManager.readAllJSONs();
// ConfigRegistry.triggerState();
// }
//
// @Mod.EventHandler
// public void server(FMLServerStartingEvent event) {
// ConfigRegistry.triggerState();
// }
//
// public boolean hello() {
// System.out.println("Hello world!");
// return true;
// }
//
// private void registerAllEvents() {
// MinecraftForge.EVENT_BUS.register(new ContractingEvents());
// FMLCommonHandler.instance().bus().register(new ContractingEvents());
// MinecraftForge.ORE_GEN_BUS.register(new ContractingEvents());
// MinecraftForge.TERRAIN_GEN_BUS.register(new ContractingEvents());
//
// if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
// MinecraftForge.EVENT_BUS.register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// FMLCommonHandler.instance().bus().register(new mc.Mitchellbrine.diseaseCraft.client.gui.ClientGuiEvents());
// }
// }
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRegistration.java
import mc.Mitchellbrine.diseaseCraft.DiseaseCraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import cpw.mods.fml.common.registry.EntityRegistry;
package mc.Mitchellbrine.diseaseCraft.entity;
/**
* Created by Mitchellbrine on 2015.
*/
public class EntityRegistration {
private static int START_ID = 500;
public static void init() {
registerEntity(EntityRat.class,"rat",7237230,3158064);
}
@SuppressWarnings("unchecked")
private static void registerEntity(Class<? extends Entity> entity, String name) {
int id = getUniqueId(); | EntityRegistry.registerModEntity(entity, name, id, DiseaseCraft.instance, 80, 3, true); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/client/gui/GuiHandler.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/containers/GuiBookContainer.java
// public class GuiBookContainer extends Container{
// @Override
// public boolean canInteractWith(EntityPlayer p_75145_1_) {
// return false;
// }
// }
| import cpw.mods.fml.common.network.IGuiHandler;
import mc.Mitchellbrine.diseaseCraft.containers.GuiBookContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World; | package mc.Mitchellbrine.diseaseCraft.client.gui;
/**
* Created by Mitchellbrine on 2015.
*/
public class GuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/containers/GuiBookContainer.java
// public class GuiBookContainer extends Container{
// @Override
// public boolean canInteractWith(EntityPlayer p_75145_1_) {
// return false;
// }
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/client/gui/GuiHandler.java
import cpw.mods.fml.common.network.IGuiHandler;
import mc.Mitchellbrine.diseaseCraft.containers.GuiBookContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
package mc.Mitchellbrine.diseaseCraft.client.gui;
/**
* Created by Mitchellbrine on 2015.
*/
public class GuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { | if (ID == IDS.JOURNAL || ID == IDS.USER_JOURNAL) return new GuiBookContainer(); |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/modules/bioWar/event/ChemicalEvents.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/ModuleWarfare.java
// @DCModule(id = "bioWarfare",modid = "DiseaseCraft",version = "1.0",dcVersion = References.VERSION, canBeDisabled = true)
// public class ModuleWarfare extends Module {
//
// public static CreativeTabs tab;
//
// public static Item chemicalExtractor;
//
// public void preInit() {
// tab = new CreativeTabs(CreativeTabs.getNextID(),"bioWarfare") {
// @Override
// public Item getTabIconItem() {
// return chemicalExtractor;
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(chemicalExtractor,1,1);
// }
// };
// chemicalExtractor = new ChemicalExtractor().setUnlocalizedName("chemicalExtractor");
// MinecraftForge.EVENT_BUS.register(new ChemicalEvents());
// FMLCommonHandler.instance().bus().register(new ChemicalEvents());
// }
//
// public void init() {
//
// }
//
// public void postInit() {
//
// }
//
// public void serverStart() {
//
// }
// }
| import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import mc.Mitchellbrine.diseaseCraft.modules.ModuleWarfare;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraftforge.event.entity.player.EntityInteractEvent;
import java.util.Random; | package mc.Mitchellbrine.diseaseCraft.modules.bioWar.event;
/**
* Created by Mitchellbrine on 2015.
*/
public class ChemicalEvents {
@SubscribeEvent
public void interact(EntityInteractEvent event) {
Random random = new Random();
if (!event.entityLiving.worldObj.isRemote) { | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/ModuleWarfare.java
// @DCModule(id = "bioWarfare",modid = "DiseaseCraft",version = "1.0",dcVersion = References.VERSION, canBeDisabled = true)
// public class ModuleWarfare extends Module {
//
// public static CreativeTabs tab;
//
// public static Item chemicalExtractor;
//
// public void preInit() {
// tab = new CreativeTabs(CreativeTabs.getNextID(),"bioWarfare") {
// @Override
// public Item getTabIconItem() {
// return chemicalExtractor;
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(chemicalExtractor,1,1);
// }
// };
// chemicalExtractor = new ChemicalExtractor().setUnlocalizedName("chemicalExtractor");
// MinecraftForge.EVENT_BUS.register(new ChemicalEvents());
// FMLCommonHandler.instance().bus().register(new ChemicalEvents());
// }
//
// public void init() {
//
// }
//
// public void postInit() {
//
// }
//
// public void serverStart() {
//
// }
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/bioWar/event/ChemicalEvents.java
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import mc.Mitchellbrine.diseaseCraft.modules.ModuleWarfare;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraftforge.event.entity.player.EntityInteractEvent;
import java.util.Random;
package mc.Mitchellbrine.diseaseCraft.modules.bioWar.event;
/**
* Created by Mitchellbrine on 2015.
*/
public class ChemicalEvents {
@SubscribeEvent
public void interact(EntityInteractEvent event) {
Random random = new Random();
if (!event.entityLiving.worldObj.isRemote) { | if (event.entityPlayer.getCurrentEquippedItem() != null && event.entityPlayer.getCurrentEquippedItem().getItem() == ModuleWarfare.chemicalExtractor && event.entityPlayer.getCurrentEquippedItem().getItemDamage() == 0) { |
Mitchellbrine/DiseaseCraft-2.0 | src/main/java/mc/Mitchellbrine/diseaseCraft/modules/bioWar/event/ChemicalEvents.java | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/ModuleWarfare.java
// @DCModule(id = "bioWarfare",modid = "DiseaseCraft",version = "1.0",dcVersion = References.VERSION, canBeDisabled = true)
// public class ModuleWarfare extends Module {
//
// public static CreativeTabs tab;
//
// public static Item chemicalExtractor;
//
// public void preInit() {
// tab = new CreativeTabs(CreativeTabs.getNextID(),"bioWarfare") {
// @Override
// public Item getTabIconItem() {
// return chemicalExtractor;
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(chemicalExtractor,1,1);
// }
// };
// chemicalExtractor = new ChemicalExtractor().setUnlocalizedName("chemicalExtractor");
// MinecraftForge.EVENT_BUS.register(new ChemicalEvents());
// FMLCommonHandler.instance().bus().register(new ChemicalEvents());
// }
//
// public void init() {
//
// }
//
// public void postInit() {
//
// }
//
// public void serverStart() {
//
// }
// }
| import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import mc.Mitchellbrine.diseaseCraft.modules.ModuleWarfare;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraftforge.event.entity.player.EntityInteractEvent;
import java.util.Random; | package mc.Mitchellbrine.diseaseCraft.modules.bioWar.event;
/**
* Created by Mitchellbrine on 2015.
*/
public class ChemicalEvents {
@SubscribeEvent
public void interact(EntityInteractEvent event) {
Random random = new Random();
if (!event.entityLiving.worldObj.isRemote) {
if (event.entityPlayer.getCurrentEquippedItem() != null && event.entityPlayer.getCurrentEquippedItem().getItem() == ModuleWarfare.chemicalExtractor && event.entityPlayer.getCurrentEquippedItem().getItemDamage() == 0) { | // Path: src/main/java/mc/Mitchellbrine/diseaseCraft/entity/EntityRat.java
// public class EntityRat extends EntityMob {
//
// public EntityRat(World world) {
// super(world);
// this.setSize(0.4F, 0.3F);
// this.tasks.addTask(1, new EntityAISwimming(this));
// this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false));
// this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true));
// }
//
// protected void applyEntityAttributes()
// {
// super.applyEntityAttributes();
// this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
// this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D);
// this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(0.0F);
// }
//
// public float getEyeHeight()
// {
// return 0.1F;
// }
//
//
// protected boolean canTriggerWalking()
// {
// return false;
// }
//
// protected String getLivingSound()
// {
// return "mob.silverfish.say";
// }
//
// protected String getHurtSound()
// {
// return "mob.silverfish.hit";
// }
//
// protected String getDeathSound()
// {
// return "mob.silverfish.kill";
// }
//
// public void onUpdate()
// {
// this.renderYawOffset = this.rotationYaw;
// super.onUpdate();
// }
//
// protected Item getDropItem()
// {
// return null;
// }
//
// protected boolean isValidLightLevel()
// {
// return true;
// }
//
// public boolean getCanSpawnHere()
// {
// if (super.getCanSpawnHere())
// {
// EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D);
// return entityplayer == null;
// }
// else
// {
// return false;
// }
// }
//
// public EnumCreatureAttribute getCreatureAttribute()
// {
// return EnumCreatureAttribute.ARTHROPOD;
// }
//
// @Override
// public boolean attackEntityAsMob(Entity p_70652_1_) {
// return false;
// }
//
// @Override
// protected void attackEntity(Entity p_70785_1_, float p_70785_2_) {
// }
//
// @Override
// protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
// if (Calendar.getInstance().get(Calendar.MONTH) == Calendar.MAY && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
// int range = 6 - p_70628_2_ > 0 ? 6 - p_70628_2_ : 1;
// if (this.rand.nextInt(range) == 0) {
// int j = this.rand.nextInt(3 + p_70628_2_);
//
// for (int k = 0; k < j; ++k) {
// this.dropItem(Items.cake, 1);
// }
// }
// }
// }
// }
//
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/ModuleWarfare.java
// @DCModule(id = "bioWarfare",modid = "DiseaseCraft",version = "1.0",dcVersion = References.VERSION, canBeDisabled = true)
// public class ModuleWarfare extends Module {
//
// public static CreativeTabs tab;
//
// public static Item chemicalExtractor;
//
// public void preInit() {
// tab = new CreativeTabs(CreativeTabs.getNextID(),"bioWarfare") {
// @Override
// public Item getTabIconItem() {
// return chemicalExtractor;
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(chemicalExtractor,1,1);
// }
// };
// chemicalExtractor = new ChemicalExtractor().setUnlocalizedName("chemicalExtractor");
// MinecraftForge.EVENT_BUS.register(new ChemicalEvents());
// FMLCommonHandler.instance().bus().register(new ChemicalEvents());
// }
//
// public void init() {
//
// }
//
// public void postInit() {
//
// }
//
// public void serverStart() {
//
// }
// }
// Path: src/main/java/mc/Mitchellbrine/diseaseCraft/modules/bioWar/event/ChemicalEvents.java
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import mc.Mitchellbrine.diseaseCraft.entity.EntityRat;
import mc.Mitchellbrine.diseaseCraft.modules.ModuleWarfare;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraftforge.event.entity.player.EntityInteractEvent;
import java.util.Random;
package mc.Mitchellbrine.diseaseCraft.modules.bioWar.event;
/**
* Created by Mitchellbrine on 2015.
*/
public class ChemicalEvents {
@SubscribeEvent
public void interact(EntityInteractEvent event) {
Random random = new Random();
if (!event.entityLiving.worldObj.isRemote) {
if (event.entityPlayer.getCurrentEquippedItem() != null && event.entityPlayer.getCurrentEquippedItem().getItem() == ModuleWarfare.chemicalExtractor && event.entityPlayer.getCurrentEquippedItem().getItemDamage() == 0) { | if (event.target instanceof EntityRat) { |
bingoohuang/excel2javabeans | src/main/java/com/github/bingoohuang/excel2beans/RowObjectCreator.java | // Path: src/main/java/com/github/bingoohuang/instantiator/BeanInstantiator.java
// public interface BeanInstantiator<T> {
// T newInstance();
// }
| import com.github.bingoohuang.instantiator.BeanInstantiator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map; | package com.github.bingoohuang.excel2beans;
class RowObjectCreator<T> {
private final List<ExcelBeanField> beanFields;
private final boolean cellDataMapAttachable;
private final Sheet sheet;
private final Row row;
private final Table<Integer, Integer, ImageData> imageDataTable;
private final DataFormatter cellFormatter;
private final Map<String, CellData> cellDataMap;
private final T object;
private int emptyNum;
@SuppressWarnings("unchecked") | // Path: src/main/java/com/github/bingoohuang/instantiator/BeanInstantiator.java
// public interface BeanInstantiator<T> {
// T newInstance();
// }
// Path: src/main/java/com/github/bingoohuang/excel2beans/RowObjectCreator.java
import com.github.bingoohuang.instantiator.BeanInstantiator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
package com.github.bingoohuang.excel2beans;
class RowObjectCreator<T> {
private final List<ExcelBeanField> beanFields;
private final boolean cellDataMapAttachable;
private final Sheet sheet;
private final Row row;
private final Table<Integer, Integer, ImageData> imageDataTable;
private final DataFormatter cellFormatter;
private final Map<String, CellData> cellDataMap;
private final T object;
private int emptyNum;
@SuppressWarnings("unchecked") | public RowObjectCreator(BeanInstantiator<T> instantiator, |
bingoohuang/excel2javabeans | src/main/java/com/github/bingoohuang/excel2beans/ExcelSheetToBeans.java | // Path: src/main/java/com/github/bingoohuang/instantiator/BeanInstantiator.java
// public interface BeanInstantiator<T> {
// T newInstance();
// }
//
// Path: src/main/java/com/github/bingoohuang/instantiator/BeanInstantiatorFactory.java
// public class BeanInstantiatorFactory {
// @SuppressWarnings("unchecked")
// public static <T> BeanInstantiator<T> newBeanInstantiator(Class<T> beanClass) {
// val ctors = (Constructor<T>[]) beanClass.getConstructors();
// for (val ctor : ctors) {
// if (ctor.getParameterTypes().length == 0) {
// return new ConstructorBeanInstantiator<T>(ctor);
// }
// }
//
// return new ObjenesisBeanInstantiator<T>(beanClass);
// }
// }
| import com.github.bingoohuang.instantiator.BeanInstantiator;
import com.github.bingoohuang.instantiator.BeanInstantiatorFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;
import lombok.Getter;
import lombok.val;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.List; | package com.github.bingoohuang.excel2beans;
public class ExcelSheetToBeans<T> {
private final BeanInstantiator<T> instantiator;
private final List<ExcelBeanField> beanFields;
private @Getter final boolean hasTitle;
private final DataFormatter cellFormatter = new DataFormatter();
private final Sheet sheet;
private final Table<Integer, Integer, ImageData> imageDataTable;
private final boolean cellDataMapAttachable;
public ExcelSheetToBeans(Workbook workbook, Class<T> beanClass) { | // Path: src/main/java/com/github/bingoohuang/instantiator/BeanInstantiator.java
// public interface BeanInstantiator<T> {
// T newInstance();
// }
//
// Path: src/main/java/com/github/bingoohuang/instantiator/BeanInstantiatorFactory.java
// public class BeanInstantiatorFactory {
// @SuppressWarnings("unchecked")
// public static <T> BeanInstantiator<T> newBeanInstantiator(Class<T> beanClass) {
// val ctors = (Constructor<T>[]) beanClass.getConstructors();
// for (val ctor : ctors) {
// if (ctor.getParameterTypes().length == 0) {
// return new ConstructorBeanInstantiator<T>(ctor);
// }
// }
//
// return new ObjenesisBeanInstantiator<T>(beanClass);
// }
// }
// Path: src/main/java/com/github/bingoohuang/excel2beans/ExcelSheetToBeans.java
import com.github.bingoohuang.instantiator.BeanInstantiator;
import com.github.bingoohuang.instantiator.BeanInstantiatorFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;
import lombok.Getter;
import lombok.val;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.List;
package com.github.bingoohuang.excel2beans;
public class ExcelSheetToBeans<T> {
private final BeanInstantiator<T> instantiator;
private final List<ExcelBeanField> beanFields;
private @Getter final boolean hasTitle;
private final DataFormatter cellFormatter = new DataFormatter();
private final Sheet sheet;
private final Table<Integer, Integer, ImageData> imageDataTable;
private final boolean cellDataMapAttachable;
public ExcelSheetToBeans(Workbook workbook, Class<T> beanClass) { | this.instantiator = BeanInstantiatorFactory.newBeanInstantiator(beanClass); |
bingoohuang/excel2javabeans | src/main/java/com/github/bingoohuang/excel2maps/ExcelSheetToMaps.java | // Path: src/main/java/com/github/bingoohuang/excel2maps/impl/ColumnRef.java
// @AllArgsConstructor @Value public class ColumnRef {
// ColumnDef columnDef;
// int columnIndex;
//
// public Ignored putMapOrIgnored(Map<String, String> map, String cellValue) {
// val upper = StringUtils.upperCase(cellValue);
// if (wildMatch(upper, columnDef.getIgnorePattern())) return Ignored.YES;
//
// map.put(columnDef.getColumnName(), cellValue);
// return Ignored.NO;
// }
//
// /**
// * The following Java method tests if a string matches a wildcard expression
// * (supporting ? for exactly one character or * for an arbitrary number of characters):
// *
// * @param text Text to test
// * @param pattern (Wildcard) pattern to test
// * @return True if the text matches the wildcard pattern
// */
// public static boolean wildMatch(String text, String pattern) {
// if (pattern == null) return false;
//
// return text.matches(pattern.replace("?", ".?")
// .replace("*", ".*?"));
// }
// }
//
// Path: src/main/java/com/github/bingoohuang/excel2maps/impl/Ignored.java
// public enum Ignored {
// YES, NO
// }
| import com.github.bingoohuang.excel2maps.impl.ColumnRef;
import com.github.bingoohuang.excel2maps.impl.Ignored;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.trim; | package com.github.bingoohuang.excel2maps;
public class ExcelSheetToMaps {
private final Workbook workbook;
private final ExcelToMapsConfig excelToMapsConfig; | // Path: src/main/java/com/github/bingoohuang/excel2maps/impl/ColumnRef.java
// @AllArgsConstructor @Value public class ColumnRef {
// ColumnDef columnDef;
// int columnIndex;
//
// public Ignored putMapOrIgnored(Map<String, String> map, String cellValue) {
// val upper = StringUtils.upperCase(cellValue);
// if (wildMatch(upper, columnDef.getIgnorePattern())) return Ignored.YES;
//
// map.put(columnDef.getColumnName(), cellValue);
// return Ignored.NO;
// }
//
// /**
// * The following Java method tests if a string matches a wildcard expression
// * (supporting ? for exactly one character or * for an arbitrary number of characters):
// *
// * @param text Text to test
// * @param pattern (Wildcard) pattern to test
// * @return True if the text matches the wildcard pattern
// */
// public static boolean wildMatch(String text, String pattern) {
// if (pattern == null) return false;
//
// return text.matches(pattern.replace("?", ".?")
// .replace("*", ".*?"));
// }
// }
//
// Path: src/main/java/com/github/bingoohuang/excel2maps/impl/Ignored.java
// public enum Ignored {
// YES, NO
// }
// Path: src/main/java/com/github/bingoohuang/excel2maps/ExcelSheetToMaps.java
import com.github.bingoohuang.excel2maps.impl.ColumnRef;
import com.github.bingoohuang.excel2maps.impl.Ignored;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.trim;
package com.github.bingoohuang.excel2maps;
public class ExcelSheetToMaps {
private final Workbook workbook;
private final ExcelToMapsConfig excelToMapsConfig; | private final List<ColumnRef> columnRefs; |
bingoohuang/excel2javabeans | src/main/java/com/github/bingoohuang/excel2maps/ExcelSheetToMaps.java | // Path: src/main/java/com/github/bingoohuang/excel2maps/impl/ColumnRef.java
// @AllArgsConstructor @Value public class ColumnRef {
// ColumnDef columnDef;
// int columnIndex;
//
// public Ignored putMapOrIgnored(Map<String, String> map, String cellValue) {
// val upper = StringUtils.upperCase(cellValue);
// if (wildMatch(upper, columnDef.getIgnorePattern())) return Ignored.YES;
//
// map.put(columnDef.getColumnName(), cellValue);
// return Ignored.NO;
// }
//
// /**
// * The following Java method tests if a string matches a wildcard expression
// * (supporting ? for exactly one character or * for an arbitrary number of characters):
// *
// * @param text Text to test
// * @param pattern (Wildcard) pattern to test
// * @return True if the text matches the wildcard pattern
// */
// public static boolean wildMatch(String text, String pattern) {
// if (pattern == null) return false;
//
// return text.matches(pattern.replace("?", ".?")
// .replace("*", ".*?"));
// }
// }
//
// Path: src/main/java/com/github/bingoohuang/excel2maps/impl/Ignored.java
// public enum Ignored {
// YES, NO
// }
| import com.github.bingoohuang.excel2maps.impl.ColumnRef;
import com.github.bingoohuang.excel2maps.impl.Ignored;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.trim; | package com.github.bingoohuang.excel2maps;
public class ExcelSheetToMaps {
private final Workbook workbook;
private final ExcelToMapsConfig excelToMapsConfig;
private final List<ColumnRef> columnRefs;
private final DataFormatter cellFormatter = new DataFormatter();
public ExcelSheetToMaps(Workbook workbook, ExcelToMapsConfig excelToMapsConfig) {
this.workbook = workbook;
this.excelToMapsConfig = excelToMapsConfig;
this.columnRefs = Lists.newArrayList();
}
public List<Map<String, String>> convert(int sheetIndex) {
List<Map<String, String>> beans = Lists.newArrayList();
val sheet = workbook.getSheetAt(sheetIndex);
val startRowNum = jumpToStartDataRow(sheet);
for (int i = startRowNum, ii = sheet.getLastRowNum(); i <= ii; ++i) {
val map = createRowMap(sheet, i);
if (map != null) {
map.put("_row", Integer.toString(i));
beans.add(map);
}
}
return beans;
}
private Map<String, String> createRowMap(Sheet sheet, int i) {
val row = sheet.getRow(i);
if (row != null) {
Map<String, String> map = Maps.newHashMap();
val ignore = processOrIgnoreRow(row, map); | // Path: src/main/java/com/github/bingoohuang/excel2maps/impl/ColumnRef.java
// @AllArgsConstructor @Value public class ColumnRef {
// ColumnDef columnDef;
// int columnIndex;
//
// public Ignored putMapOrIgnored(Map<String, String> map, String cellValue) {
// val upper = StringUtils.upperCase(cellValue);
// if (wildMatch(upper, columnDef.getIgnorePattern())) return Ignored.YES;
//
// map.put(columnDef.getColumnName(), cellValue);
// return Ignored.NO;
// }
//
// /**
// * The following Java method tests if a string matches a wildcard expression
// * (supporting ? for exactly one character or * for an arbitrary number of characters):
// *
// * @param text Text to test
// * @param pattern (Wildcard) pattern to test
// * @return True if the text matches the wildcard pattern
// */
// public static boolean wildMatch(String text, String pattern) {
// if (pattern == null) return false;
//
// return text.matches(pattern.replace("?", ".?")
// .replace("*", ".*?"));
// }
// }
//
// Path: src/main/java/com/github/bingoohuang/excel2maps/impl/Ignored.java
// public enum Ignored {
// YES, NO
// }
// Path: src/main/java/com/github/bingoohuang/excel2maps/ExcelSheetToMaps.java
import com.github.bingoohuang.excel2maps.impl.ColumnRef;
import com.github.bingoohuang.excel2maps.impl.Ignored;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.trim;
package com.github.bingoohuang.excel2maps;
public class ExcelSheetToMaps {
private final Workbook workbook;
private final ExcelToMapsConfig excelToMapsConfig;
private final List<ColumnRef> columnRefs;
private final DataFormatter cellFormatter = new DataFormatter();
public ExcelSheetToMaps(Workbook workbook, ExcelToMapsConfig excelToMapsConfig) {
this.workbook = workbook;
this.excelToMapsConfig = excelToMapsConfig;
this.columnRefs = Lists.newArrayList();
}
public List<Map<String, String>> convert(int sheetIndex) {
List<Map<String, String>> beans = Lists.newArrayList();
val sheet = workbook.getSheetAt(sheetIndex);
val startRowNum = jumpToStartDataRow(sheet);
for (int i = startRowNum, ii = sheet.getLastRowNum(); i <= ii; ++i) {
val map = createRowMap(sheet, i);
if (map != null) {
map.put("_row", Integer.toString(i));
beans.add(map);
}
}
return beans;
}
private Map<String, String> createRowMap(Sheet sheet, int i) {
val row = sheet.getRow(i);
if (row != null) {
Map<String, String> map = Maps.newHashMap();
val ignore = processOrIgnoreRow(row, map); | if (ignore != Ignored.YES) { |
bingoohuang/excel2javabeans | src/test/java/com/github/bingoohuang/excel2beans/BeanWithTitleTest.java | // Path: src/main/java/com/github/bingoohuang/excel2beans/PoiUtil.java
// @SneakyThrows
// public static Workbook getClassPathWorkbook(String classPathExcelName) {
// @Cleanup val is = Classpath.loadRes(classPathExcelName);
// return WorkbookFactory.create(is);
// }
| import com.github.bingoohuang.excel2beans.annotations.ExcelColTitle;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static com.github.bingoohuang.excel2beans.PoiUtil.getClassPathWorkbook;
import static com.google.common.truth.Truth.assertThat; | package com.github.bingoohuang.excel2beans;
@SuppressWarnings("unchecked")
public class BeanWithTitleTest {
@SneakyThrows
@Test public void test() { | // Path: src/main/java/com/github/bingoohuang/excel2beans/PoiUtil.java
// @SneakyThrows
// public static Workbook getClassPathWorkbook(String classPathExcelName) {
// @Cleanup val is = Classpath.loadRes(classPathExcelName);
// return WorkbookFactory.create(is);
// }
// Path: src/test/java/com/github/bingoohuang/excel2beans/BeanWithTitleTest.java
import com.github.bingoohuang.excel2beans.annotations.ExcelColTitle;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static com.github.bingoohuang.excel2beans.PoiUtil.getClassPathWorkbook;
import static com.google.common.truth.Truth.assertThat;
package com.github.bingoohuang.excel2beans;
@SuppressWarnings("unchecked")
public class BeanWithTitleTest {
@SneakyThrows
@Test public void test() { | @Cleanup val workbook = getClassPathWorkbook("member.xlsx"); |
bingoohuang/excel2javabeans | src/main/java/com/github/bingoohuang/excel2beans/ExcelBeanFieldParser.java | // Path: src/main/java/com/github/bingoohuang/excel2beans/annotations/ExcelColAlign.java
// public enum ExcelColAlign {
// LEFT, CENTER, RIGHT, NONE
// }
| import com.github.bingoohuang.excel2beans.annotations.ExcelColAlign;
import com.github.bingoohuang.excel2beans.annotations.ExcelColIgnore;
import com.github.bingoohuang.excel2beans.annotations.ExcelColStyle;
import com.github.bingoohuang.utils.reflect.Fields;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Sheet;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; | Set<String> includedFields,
ReflectAsmCache reflectAsmCache) {
if (Fields.shouldIgnored(field, ExcelColIgnore.class)) return;
if (includedFields != null && !includedFields.contains(field.getName())) return;
val bf = new ExcelBeanField(field, fields.size(), reflectAsmCache);
if (bf.isElementTypeSupported()) {
setStyle(field, bf);
fields.add(bf);
} else {
log.debug("bean field {} was ignored by unsupported type {}",
field, bf.getElementType());
}
}
private void setStyle(Field field, ExcelBeanField beanField) {
val colStyle = field.getAnnotation(ExcelColStyle.class);
if (colStyle == null) return;
beanField.setCellStyle(createAlign(colStyle));
}
private CellStyle createAlign(ExcelColStyle colStyle) {
val style = sheet.getWorkbook().createCellStyle();
style.setAlignment(convertAlign(colStyle.align(), style.getAlignmentEnum()));
return style;
}
| // Path: src/main/java/com/github/bingoohuang/excel2beans/annotations/ExcelColAlign.java
// public enum ExcelColAlign {
// LEFT, CENTER, RIGHT, NONE
// }
// Path: src/main/java/com/github/bingoohuang/excel2beans/ExcelBeanFieldParser.java
import com.github.bingoohuang.excel2beans.annotations.ExcelColAlign;
import com.github.bingoohuang.excel2beans.annotations.ExcelColIgnore;
import com.github.bingoohuang.excel2beans.annotations.ExcelColStyle;
import com.github.bingoohuang.utils.reflect.Fields;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Sheet;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
Set<String> includedFields,
ReflectAsmCache reflectAsmCache) {
if (Fields.shouldIgnored(field, ExcelColIgnore.class)) return;
if (includedFields != null && !includedFields.contains(field.getName())) return;
val bf = new ExcelBeanField(field, fields.size(), reflectAsmCache);
if (bf.isElementTypeSupported()) {
setStyle(field, bf);
fields.add(bf);
} else {
log.debug("bean field {} was ignored by unsupported type {}",
field, bf.getElementType());
}
}
private void setStyle(Field field, ExcelBeanField beanField) {
val colStyle = field.getAnnotation(ExcelColStyle.class);
if (colStyle == null) return;
beanField.setCellStyle(createAlign(colStyle));
}
private CellStyle createAlign(ExcelColStyle colStyle) {
val style = sheet.getWorkbook().createCellStyle();
style.setAlignment(convertAlign(colStyle.align(), style.getAlignmentEnum()));
return style;
}
| private HorizontalAlignment convertAlign(ExcelColAlign align, HorizontalAlignment defaultAlign) { |
roquendm/JGO-Grabbag | src/roquen/math/sfc/Morton3D.java | // Path: src/roquen/fake/Vect3i.java
// public class Vect3i {
// public int x,y,z;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y,z));
// }
// }
| import roquen.fake.Vect3i; | package roquen.math.sfc;
/**
* Static utilities for 3-to-1 mappings based on Morton/Z-Order/Lebesgue curve.
*/
public enum Morton3D {
;
| // Path: src/roquen/fake/Vect3i.java
// public class Vect3i {
// public int x,y,z;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y,z));
// }
// }
// Path: src/roquen/math/sfc/Morton3D.java
import roquen.fake.Vect3i;
package roquen.math.sfc;
/**
* Static utilities for 3-to-1 mappings based on Morton/Z-Order/Lebesgue curve.
*/
public enum Morton3D {
;
| public static int encode5(Vect3i v) |
roquendm/JGO-Grabbag | src/roquen/math/sfc/Index2D.java | // Path: src/roquen/fake/Vect2i.java
// public class Vect2i {
// public int x, y;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
| import roquen.fake.Vect2i;
| package roquen.math.sfc;
/**
* Base class of maintaining a 2-to-1 representation of a 2D coordinate.
*/
public abstract class Index2D<T extends Index2D<T>>
{
/** Scattered version of x. Publicly visible for copy/storage/restoring. */
public int sx;
/** Scattered version of y. Publicly visible for copy/storage/restoring. */
public int sy;
/** Returns the current index */
public abstract int getIndex();
/** Copies the represented coordinate 'v' into this. */
public abstract void set(T v);
/** Set the represented 2D coordinate */
| // Path: src/roquen/fake/Vect2i.java
// public class Vect2i {
// public int x, y;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
// Path: src/roquen/math/sfc/Index2D.java
import roquen.fake.Vect2i;
package roquen.math.sfc;
/**
* Base class of maintaining a 2-to-1 representation of a 2D coordinate.
*/
public abstract class Index2D<T extends Index2D<T>>
{
/** Scattered version of x. Publicly visible for copy/storage/restoring. */
public int sx;
/** Scattered version of y. Publicly visible for copy/storage/restoring. */
public int sy;
/** Returns the current index */
public abstract int getIndex();
/** Copies the represented coordinate 'v' into this. */
public abstract void set(T v);
/** Set the represented 2D coordinate */
| public abstract void set(Vect2i v);
|
roquendm/JGO-Grabbag | src/roquen/interp/RayGrid2D.java | // Path: src/roquen/fake/Vect2f.java
// public class Vect2f {
// public float x,y;
//
// public Vect2f set(float x, float y)
// {
// this.x=x; this.y=y;
// return this;
// }
//
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
| import roquen.fake.Vect2f;
| package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 2D grid which
* are crossed by a line segment or ray. All covered cells are visited
* however it does not provide supercoverage. Supercoverage is when
* all four cells are visited in the case where the ray passes through
* a corner. For a corner case this will visit three out of four. At
* each step the next cell will be either a horizontal or vertical move
* so in the extreme pathological case this will visit "false positive"
* cells, the worst case situation begin a 45 degree angle ray
* perfectly through corners where half the visited cells will be
* "false positives". These false positives only occur when hitting
* a corner so is of no concern unless the use-case is something like
* rayshooting from the center of a cell in only horizontal, vertical or
* diagonal directions which isn't the intended usage.
* <p>
* Passed in values make the assumption that the extent of cells are
* of one unit. User code scaling is required for other sizes.
*/
public class RayGrid2D
{
private double cx,cy;
private double ax,ay;
private int ux,uy;
/** Current cell coordinate */
public int x,y;
| // Path: src/roquen/fake/Vect2f.java
// public class Vect2f {
// public float x,y;
//
// public Vect2f set(float x, float y)
// {
// this.x=x; this.y=y;
// return this;
// }
//
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
// Path: src/roquen/interp/RayGrid2D.java
import roquen.fake.Vect2f;
package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 2D grid which
* are crossed by a line segment or ray. All covered cells are visited
* however it does not provide supercoverage. Supercoverage is when
* all four cells are visited in the case where the ray passes through
* a corner. For a corner case this will visit three out of four. At
* each step the next cell will be either a horizontal or vertical move
* so in the extreme pathological case this will visit "false positive"
* cells, the worst case situation begin a 45 degree angle ray
* perfectly through corners where half the visited cells will be
* "false positives". These false positives only occur when hitting
* a corner so is of no concern unless the use-case is something like
* rayshooting from the center of a cell in only horizontal, vertical or
* diagonal directions which isn't the intended usage.
* <p>
* Passed in values make the assumption that the extent of cells are
* of one unit. User code scaling is required for other sizes.
*/
public class RayGrid2D
{
private double cx,cy;
private double ax,ay;
private int ux,uy;
/** Current cell coordinate */
public int x,y;
| public void set(Vect2f p0, Vect2f p1)
|
roquendm/JGO-Grabbag | src/roquen/math/sfc/Morton2D.java | // Path: src/roquen/fake/Vect2i.java
// public class Vect2i {
// public int x, y;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
| import roquen.fake.Vect2i; |
/**
* Gather all the even bits into the lower 16. Odd
* bits must be already zero.
*/
public static int gather1_(int x)
{
x = (x ^ (x >>> 1)) & 0x33333333;
x = (x ^ (x >>> 2)) & 0x0F0F0F0F;
x = (x ^ (x >>> 4)) & 0x00FF00FF;
x = (x ^ (x >>> 8)) & 0x0000FFFF;
return x;
}
/**
* Gather all the even bits into the lower 16.
*/
public static int gather1(int x)
{
x &= MASK_X;
x = (x ^ (x >>> 1)) & 0x33333333;
x = (x ^ (x >>> 2)) & 0x0F0F0F0F;
x = (x ^ (x >>> 4)) & 0x00FF00FF;
x = (x ^ (x >>> 8)) & 0x0000FFFF;
return x;
}
/**
*
*/ | // Path: src/roquen/fake/Vect2i.java
// public class Vect2i {
// public int x, y;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
// Path: src/roquen/math/sfc/Morton2D.java
import roquen.fake.Vect2i;
/**
* Gather all the even bits into the lower 16. Odd
* bits must be already zero.
*/
public static int gather1_(int x)
{
x = (x ^ (x >>> 1)) & 0x33333333;
x = (x ^ (x >>> 2)) & 0x0F0F0F0F;
x = (x ^ (x >>> 4)) & 0x00FF00FF;
x = (x ^ (x >>> 8)) & 0x0000FFFF;
return x;
}
/**
* Gather all the even bits into the lower 16.
*/
public static int gather1(int x)
{
x &= MASK_X;
x = (x ^ (x >>> 1)) & 0x33333333;
x = (x ^ (x >>> 2)) & 0x0F0F0F0F;
x = (x ^ (x >>> 4)) & 0x00FF00FF;
x = (x ^ (x >>> 8)) & 0x0000FFFF;
return x;
}
/**
*
*/ | public static int encode4(Vect2i v) |
roquendm/JGO-Grabbag | src/roquen/interp/RayGrid3D.java | // Path: src/roquen/fake/Vect3f.java
// public class Vect3f {
// public float x,y,z;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y,z));
// }
//
// public final float dot(Vect3f v)
// {
// return x*v.x + y*v.y + z*v.z;
// }
// }
| import roquen.fake.Vect3f;
| package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 3D grid which
* are crossed by a line segment or ray. For more details see {@link RayGrid2D}
*/
public class RayGrid3D {
private double cx,cy,cz;
private double ax,ay,az;
private int ux,uy,uz;
/** Current cell coordinate */
public int x,y,z;
| // Path: src/roquen/fake/Vect3f.java
// public class Vect3f {
// public float x,y,z;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y,z));
// }
//
// public final float dot(Vect3f v)
// {
// return x*v.x + y*v.y + z*v.z;
// }
// }
// Path: src/roquen/interp/RayGrid3D.java
import roquen.fake.Vect3f;
package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 3D grid which
* are crossed by a line segment or ray. For more details see {@link RayGrid2D}
*/
public class RayGrid3D {
private double cx,cy,cz;
private double ax,ay,az;
private int ux,uy,uz;
/** Current cell coordinate */
public int x,y,z;
| public void set(Vect3f p0, Vect3f p1)
|
roquendm/JGO-Grabbag | src/roquen/interp/DDA2D.java | // Path: src/roquen/fake/Vect2f.java
// public class Vect2f {
// public float x,y;
//
// public Vect2f set(float x, float y)
// {
// this.x=x; this.y=y;
// return this;
// }
//
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
| import roquen.fake.Vect2f;
| package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 2D grid which
* are crossed by a line segment or ray. It is equivalent to a
* Bresenham's line walk. The basic mechanism is to determine a major
* axis and walk a connected set of cells along that axis.
* <p>
* Passed in values make the assumption that the extent of cells are
* of one unit. User code scaling is required for other sizes.
* <p>
* The name is actually a misnomer as the computation is in floating
* point. This drastically reduces the complexity of the update.
*/
public class DDA2D {
/**
* use-case specific cell offset. default=0 (lower left).
* set to .5 for center of cell for example.
*/
private double offset;
/** current number of steps (integer) */
private double step;
/** inverse the number of steps (one rounding error) */
private double in;
/** coordinate of cell containing the first point (integer) */
private double x0,y0;
/** integer displacement from first to last cell (integer) */
private double dx,dy;
/** current step (cell) coordinate, includes fractional */
public double x,y;
public int set(float sx, float sy, float ex, float ey)
{
// find the cell coordinate of the end points
x0 = Math.floor(sx);
y0 = Math.floor(sy);
double x1 = Math.floor(ex);
double y1 = Math.floor(ey);
// initialize current cell coordinate
x = x0 + offset;
y = y0 + offset;
step = 1;
// calculate the deltas and find the maximum magnitude
dx = x1-x0;
dy = y1-y0;
double ax = Math.abs(dx);
double ay = Math.abs(dy);
double n = ax > ay ? ax : ay;
// calculate the step values
in = 1.0/n;
return (int)n;
}
/**
* Sets the instance to iterate over all cells covered
* by the line segment from p0 to p1 in order. Return
* the number of steps required.
* <p>
* The fields ({@link #x}, {@link #y}) are
* set to the first cell coordinate.
*/
| // Path: src/roquen/fake/Vect2f.java
// public class Vect2f {
// public float x,y;
//
// public Vect2f set(float x, float y)
// {
// this.x=x; this.y=y;
// return this;
// }
//
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
// Path: src/roquen/interp/DDA2D.java
import roquen.fake.Vect2f;
package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 2D grid which
* are crossed by a line segment or ray. It is equivalent to a
* Bresenham's line walk. The basic mechanism is to determine a major
* axis and walk a connected set of cells along that axis.
* <p>
* Passed in values make the assumption that the extent of cells are
* of one unit. User code scaling is required for other sizes.
* <p>
* The name is actually a misnomer as the computation is in floating
* point. This drastically reduces the complexity of the update.
*/
public class DDA2D {
/**
* use-case specific cell offset. default=0 (lower left).
* set to .5 for center of cell for example.
*/
private double offset;
/** current number of steps (integer) */
private double step;
/** inverse the number of steps (one rounding error) */
private double in;
/** coordinate of cell containing the first point (integer) */
private double x0,y0;
/** integer displacement from first to last cell (integer) */
private double dx,dy;
/** current step (cell) coordinate, includes fractional */
public double x,y;
public int set(float sx, float sy, float ex, float ey)
{
// find the cell coordinate of the end points
x0 = Math.floor(sx);
y0 = Math.floor(sy);
double x1 = Math.floor(ex);
double y1 = Math.floor(ey);
// initialize current cell coordinate
x = x0 + offset;
y = y0 + offset;
step = 1;
// calculate the deltas and find the maximum magnitude
dx = x1-x0;
dy = y1-y0;
double ax = Math.abs(dx);
double ay = Math.abs(dy);
double n = ax > ay ? ax : ay;
// calculate the step values
in = 1.0/n;
return (int)n;
}
/**
* Sets the instance to iterate over all cells covered
* by the line segment from p0 to p1 in order. Return
* the number of steps required.
* <p>
* The fields ({@link #x}, {@link #y}) are
* set to the first cell coordinate.
*/
| public int set(Vect2f p0, Vect2f p1)
|
roquendm/JGO-Grabbag | src/roquen/interp/DDA3D.java | // Path: src/roquen/fake/Vect3f.java
// public class Vect3f {
// public float x,y,z;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y,z));
// }
//
// public final float dot(Vect3f v)
// {
// return x*v.x + y*v.y + z*v.z;
// }
// }
| import roquen.fake.Vect3f;
| package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 3D grid which
* are crossed by a line segment or ray. It is equivalent to a
* Bresenham's line walk.
* <p>
* Passed in values make the assumption that the extent of cells are
* of one unit. User code scaling is required for other sizes.
* <p>
* The name is actually a misnomer as the computation is in floating
* point. This drastically reduces the complexity of the update.
*/
public class DDA3D {
// NOTE: Computation is in doubles. Usage requires little memory
// motion and the extra bits allow for larger grids.
/**
* use-case specific cell offset. default=0 (lower left).
* set to .5 for center of cell for example.
*/
private double offset;
/** current number of steps (integer) */
private double step;
/** inverse the number of steps (one rounding error) */
private double in;
/** coordinate of cell containing the first point (integer) */
private double x0,y0,z0;
/** integer displacement from first to last cell (integer) */
private double dx,dy,dz;
/** current step (cell) coordinate, includes fractional */
public double x,y,z;
/**
* Sets the instance to iterate over all cells covered
* by the line segment from p0 to p1 in order. Return
* the number of steps required.
* <p>
* The fields ({@link #x}, {@link #y}, {@link #z}) are
* set to the first cell coordinate.
*/
| // Path: src/roquen/fake/Vect3f.java
// public class Vect3f {
// public float x,y,z;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y,z));
// }
//
// public final float dot(Vect3f v)
// {
// return x*v.x + y*v.y + z*v.z;
// }
// }
// Path: src/roquen/interp/DDA3D.java
import roquen.fake.Vect3f;
package roquen.interp;
/**
* For performing in-order walks of cells on a uniform 3D grid which
* are crossed by a line segment or ray. It is equivalent to a
* Bresenham's line walk.
* <p>
* Passed in values make the assumption that the extent of cells are
* of one unit. User code scaling is required for other sizes.
* <p>
* The name is actually a misnomer as the computation is in floating
* point. This drastically reduces the complexity of the update.
*/
public class DDA3D {
// NOTE: Computation is in doubles. Usage requires little memory
// motion and the extra bits allow for larger grids.
/**
* use-case specific cell offset. default=0 (lower left).
* set to .5 for center of cell for example.
*/
private double offset;
/** current number of steps (integer) */
private double step;
/** inverse the number of steps (one rounding error) */
private double in;
/** coordinate of cell containing the first point (integer) */
private double x0,y0,z0;
/** integer displacement from first to last cell (integer) */
private double dx,dy,dz;
/** current step (cell) coordinate, includes fractional */
public double x,y,z;
/**
* Sets the instance to iterate over all cells covered
* by the line segment from p0 to p1 in order. Return
* the number of steps required.
* <p>
* The fields ({@link #x}, {@link #y}, {@link #z}) are
* set to the first cell coordinate.
*/
| public int set(Vect3f p0, Vect3f p1)
|
roquendm/JGO-Grabbag | src/roquen/interp/IndexedRayGrid2D.java | // Path: src/roquen/fake/Vect2f.java
// public class Vect2f {
// public float x,y;
//
// public Vect2f set(float x, float y)
// {
// this.x=x; this.y=y;
// return this;
// }
//
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
| import roquen.fake.Vect2f;
import roquen.math.sfc.*;
| // cell boundary.
cx = 1/dx;
cy = 1/dy;
// cross time accumulators. Initialized to
// the first cross time.
ax = cx * (1.0-(x0-x));
ay = cy * (1.0-(y0-y));
// movement directions
ux = dx >= 0;
uy = dy >= 0;
// TODO: temp hack
int ex = (int)x1;
int ey = (int)y1;
int nx = Math.abs(ex-x);
int ny = Math.abs(ey-y);
int n;
// todo: compute number of off major axis steps
if (nx > ny) {
n = nx;
} else {
n = ny;
}
return n;
}
| // Path: src/roquen/fake/Vect2f.java
// public class Vect2f {
// public float x,y;
//
// public Vect2f set(float x, float y)
// {
// this.x=x; this.y=y;
// return this;
// }
//
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
// Path: src/roquen/interp/IndexedRayGrid2D.java
import roquen.fake.Vect2f;
import roquen.math.sfc.*;
// cell boundary.
cx = 1/dx;
cy = 1/dy;
// cross time accumulators. Initialized to
// the first cross time.
ax = cx * (1.0-(x0-x));
ay = cy * (1.0-(y0-y));
// movement directions
ux = dx >= 0;
uy = dy >= 0;
// TODO: temp hack
int ex = (int)x1;
int ey = (int)y1;
int nx = Math.abs(ex-x);
int ny = Math.abs(ey-y);
int n;
// todo: compute number of off major axis steps
if (nx > ny) {
n = nx;
} else {
n = ny;
}
return n;
}
| public int set(Vect2f p0, Vect2f p1)
|
roquendm/JGO-Grabbag | src/roquen/math/sfc/RowLinearIndex2D.java | // Path: src/roquen/fake/Vect2i.java
// public class Vect2i {
// public int x, y;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
| import roquen.fake.Vect2i;
| package roquen.math.sfc;
/**
* Trivial indexing scheme for drop-in-replacement testing of apple-to-apples (almost)
*/
public final class RowLinearIndex2D extends Index2D<RowLinearIndex2D>
{
private final int D;
public RowLinearIndex2D(int dim)
{
D = dim;
}
@Override
| // Path: src/roquen/fake/Vect2i.java
// public class Vect2i {
// public int x, y;
//
// /** */
// private static final int HASH = hashMakeSeed(0);
//
// @Override
// public int hashCode()
// {
// return hashComplete(hashAdd(HASH,x,y));
// }
// }
// Path: src/roquen/math/sfc/RowLinearIndex2D.java
import roquen.fake.Vect2i;
package roquen.math.sfc;
/**
* Trivial indexing scheme for drop-in-replacement testing of apple-to-apples (almost)
*/
public final class RowLinearIndex2D extends Index2D<RowLinearIndex2D>
{
private final int D;
public RowLinearIndex2D(int dim)
{
D = dim;
}
@Override
| public final void set(Vect2i v)
|
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/extension/ChameleonRunnerAppender.java | // Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ArquillianChameleon.java
// public class ArquillianChameleon extends Arquillian {
//
// private static final Logger log = Logger.getLogger(ArquillianChameleon.class.getName());
//
// public ArquillianChameleon(Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// public void run(RunNotifier notifier) {
//
// final Class<?> testClass = getTestClass().getJavaClass();
// final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//
// synchronized (ArquillianChameleon.class) {
// if (isInClientSide(classLoader) && !isSpecialChameleonFile(classLoader)) {
//
// try {
// final Path arquillianChameleonConfiguration =
// new ArquillianChameleonConfigurator().setup(testClass, classLoader);
//
// log.info(String.format("Arquillian Configuration created by Chameleon runner is placed at %s.",
// arquillianChameleonConfiguration.toFile().getAbsolutePath()));
//
// createChameleonMarkerFile(arquillianChameleonConfiguration.getParent());
// addsArquillianFile(arquillianChameleonConfiguration.getParent(),
// classLoader);
// } catch (Exception e) {
// throw new IllegalArgumentException(e);
// }
// }
// }
// super.run(notifier);
// }
//
//
// // We need to create an special file and put it inside classloader. This is because Chameleon runner adds configuration files dynamically inside the classpath.
// // When you run your tests from your build tool, some or all of them shares the same classloader. So we need to avoid calling the same logic all the time to not get multiple files placed at classloader
// // representing different versions, because then you have uncertainty on which configuration file is really used
// private void createChameleonMarkerFile(Path parent) throws IOException {
// final Path chameleon = parent.resolve("chameleonrunner");
// Files.write(chameleon, "Chameleon Runner was there".getBytes());
// }
//
// private boolean isSpecialChameleonFile(ClassLoader parent) {
// return parent.getResource("chameleonrunner") != null;
// }
//
// private boolean isInClientSide(ClassLoader parent) {
// return parent.getResourceAsStream(ChameleonRunnerAppender.CHAMELEON_RUNNER_INCONTAINER_FILE) == null;
// }
//
// private void addsArquillianFile(Path file, ClassLoader classLoader) throws Exception {
// final URL url = file.toUri().toURL();
// final ClassLoader wrappedClassLoader = URLClassLoader.newInstance(new URL[]{url}, classLoader);
// Thread.currentThread().setContextClassLoader(wrappedClassLoader);
// }
//
// }
| import org.arquillian.container.chameleon.runner.ArquillianChameleon;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive; | package org.arquillian.container.chameleon.runner.extension;
public class ChameleonRunnerAppender implements AuxiliaryArchiveAppender {
public static final String CHAMELEON_RUNNER_INCONTAINER_FILE = "chameleonrunner.txt";
@Override
public Archive<?> createAuxiliaryArchive() {
return ShrinkWrap.create(JavaArchive.class, "arquillian-chameleon-runner.jar") | // Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ArquillianChameleon.java
// public class ArquillianChameleon extends Arquillian {
//
// private static final Logger log = Logger.getLogger(ArquillianChameleon.class.getName());
//
// public ArquillianChameleon(Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// public void run(RunNotifier notifier) {
//
// final Class<?> testClass = getTestClass().getJavaClass();
// final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//
// synchronized (ArquillianChameleon.class) {
// if (isInClientSide(classLoader) && !isSpecialChameleonFile(classLoader)) {
//
// try {
// final Path arquillianChameleonConfiguration =
// new ArquillianChameleonConfigurator().setup(testClass, classLoader);
//
// log.info(String.format("Arquillian Configuration created by Chameleon runner is placed at %s.",
// arquillianChameleonConfiguration.toFile().getAbsolutePath()));
//
// createChameleonMarkerFile(arquillianChameleonConfiguration.getParent());
// addsArquillianFile(arquillianChameleonConfiguration.getParent(),
// classLoader);
// } catch (Exception e) {
// throw new IllegalArgumentException(e);
// }
// }
// }
// super.run(notifier);
// }
//
//
// // We need to create an special file and put it inside classloader. This is because Chameleon runner adds configuration files dynamically inside the classpath.
// // When you run your tests from your build tool, some or all of them shares the same classloader. So we need to avoid calling the same logic all the time to not get multiple files placed at classloader
// // representing different versions, because then you have uncertainty on which configuration file is really used
// private void createChameleonMarkerFile(Path parent) throws IOException {
// final Path chameleon = parent.resolve("chameleonrunner");
// Files.write(chameleon, "Chameleon Runner was there".getBytes());
// }
//
// private boolean isSpecialChameleonFile(ClassLoader parent) {
// return parent.getResource("chameleonrunner") != null;
// }
//
// private boolean isInClientSide(ClassLoader parent) {
// return parent.getResourceAsStream(ChameleonRunnerAppender.CHAMELEON_RUNNER_INCONTAINER_FILE) == null;
// }
//
// private void addsArquillianFile(Path file, ClassLoader classLoader) throws Exception {
// final URL url = file.toUri().toURL();
// final ClassLoader wrappedClassLoader = URLClassLoader.newInstance(new URL[]{url}, classLoader);
// Thread.currentThread().setContextClassLoader(wrappedClassLoader);
// }
//
// }
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/extension/ChameleonRunnerAppender.java
import org.arquillian.container.chameleon.runner.ArquillianChameleon;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
package org.arquillian.container.chameleon.runner.extension;
public class ChameleonRunnerAppender implements AuxiliaryArchiveAppender {
public static final String CHAMELEON_RUNNER_INCONTAINER_FILE = "chameleonrunner.txt";
@Override
public Archive<?> createAuxiliaryArchive() {
return ShrinkWrap.create(JavaArchive.class, "arquillian-chameleon-runner.jar") | .addPackage(ArquillianChameleon.class.getPackage()) |
arquillian/arquillian-container-chameleon | arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/ContainerTestCase.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.junit.Assert;
import org.junit.Test; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon;
public class ContainerTestCase {
@Test
public void resolveJBossAS7() throws Exception { | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
// Path: arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/ContainerTestCase.java
import java.util.HashMap;
import java.util.Map;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.junit.Assert;
import org.junit.Test;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon;
public class ContainerTestCase {
@Test
public void resolveJBossAS7() throws Exception { | ContainerAdapter adapter = load("jboss as:7.1.1.Final:managed"); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/ContainerTestCase.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.junit.Assert;
import org.junit.Test; |
@Test
public void resolveJBossAS7DomainManaged() throws Exception {
ContainerAdapter adapter = load("jboss as domain:7.1.1.Final:managed");
Assert.assertEquals(
"org.jboss.as:jboss-as-arquillian-container-domain-managed:7.1.1.Final",
adapter.dependencies()[0]);
}
@Test
public void resolveJBossAS7DomainRemote() throws Exception {
ContainerAdapter adapter = load("jboss as domain:7.1.1.Final:remote");
Assert.assertEquals(
"org.jboss.as:jboss-as-arquillian-container-domain-remote:7.1.1.Final",
adapter.dependencies()[0]);
}
@Test
public void overrideDefaultProtocolJBossAs7() throws Exception {
ContainerAdapter adapter = load("jboss as:7.1.1.Final:managed");
Assert.assertTrue(
adapter.overrideDefaultProtocol());
Assert.assertEquals(
"Servlet 3.0",
adapter.getDefaultProtocol());
}
@Test
public void resolveJBossAS7DefaultType() throws Exception {
ContainerAdapter adapter = load("jboss as:7.1.1.Final"); | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
// Path: arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/ContainerTestCase.java
import java.util.HashMap;
import java.util.Map;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.junit.Assert;
import org.junit.Test;
@Test
public void resolveJBossAS7DomainManaged() throws Exception {
ContainerAdapter adapter = load("jboss as domain:7.1.1.Final:managed");
Assert.assertEquals(
"org.jboss.as:jboss-as-arquillian-container-domain-managed:7.1.1.Final",
adapter.dependencies()[0]);
}
@Test
public void resolveJBossAS7DomainRemote() throws Exception {
ContainerAdapter adapter = load("jboss as domain:7.1.1.Final:remote");
Assert.assertEquals(
"org.jboss.as:jboss-as-arquillian-container-domain-remote:7.1.1.Final",
adapter.dependencies()[0]);
}
@Test
public void overrideDefaultProtocolJBossAs7() throws Exception {
ContainerAdapter adapter = load("jboss as:7.1.1.Final:managed");
Assert.assertTrue(
adapter.overrideDefaultProtocol());
Assert.assertEquals(
"Servlet 3.0",
adapter.getDefaultProtocol());
}
@Test
public void resolveJBossAS7DefaultType() throws Exception {
ContainerAdapter adapter = load("jboss as:7.1.1.Final"); | Assert.assertEquals(Type.Managed, adapter.type()); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/ArquillianChameleonConfiguratorTest.java | // Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import javax.xml.transform.TransformerException;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package org.arquillian.container.chameleon.runner;
@RunWith(MockitoJUnitRunner.class)
public class ArquillianChameleonConfiguratorTest {
@Mock
ClassLoader classLoader;
@Mock
InputStream file;
@Rule
public final RestoreSystemProperties restoreSystemProperties
= new RestoreSystemProperties();
@Test
public void should_configure_arquillian_using_properties_if_it_is_not_configured_as_such()
throws IOException, TransformerException {
// given
final ArquillianChameleonConfigurator arquillianChameleonConfigurator = new ArquillianChameleonConfigurator();
when(classLoader.getResourceAsStream(ArquillianChameleonConfigurationGenerator.ARQUILLIAN_PROPERTIES))
.thenReturn(null);
// when | // Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/ArquillianChameleonConfiguratorTest.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import javax.xml.transform.TransformerException;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package org.arquillian.container.chameleon.runner;
@RunWith(MockitoJUnitRunner.class)
public class ArquillianChameleonConfiguratorTest {
@Mock
ClassLoader classLoader;
@Mock
InputStream file;
@Rule
public final RestoreSystemProperties restoreSystemProperties
= new RestoreSystemProperties();
@Test
public void should_configure_arquillian_using_properties_if_it_is_not_configured_as_such()
throws IOException, TransformerException {
// given
final ArquillianChameleonConfigurator arquillianChameleonConfigurator = new ArquillianChameleonConfigurator();
when(classLoader.getResourceAsStream(ArquillianChameleonConfigurationGenerator.ARQUILLIAN_PROPERTIES))
.thenReturn(null);
// when | final Path setup = arquillianChameleonConfigurator.setup(GenericTest.class, classLoader); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ChameleonTargetConfiguration.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/RunnerExpressionParser.java
// public static String parseExpressions(final String value) {
// return parseExpressions(value, new SystemPropertyResolver());
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.api.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static org.arquillian.container.chameleon.runner.RunnerExpressionParser.parseExpressions; | package org.arquillian.container.chameleon.runner;
public class ChameleonTargetConfiguration {
private static final int CONTAINER = 0;
public static final int VERSION = 1;
public static final int MODE = 2;
private String container;
private String version; | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/RunnerExpressionParser.java
// public static String parseExpressions(final String value) {
// return parseExpressions(value, new SystemPropertyResolver());
// }
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ChameleonTargetConfiguration.java
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.api.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static org.arquillian.container.chameleon.runner.RunnerExpressionParser.parseExpressions;
package org.arquillian.container.chameleon.runner;
public class ChameleonTargetConfiguration {
private static final int CONTAINER = 0;
public static final int VERSION = 1;
public static final int MODE = 2;
private String container;
private String version; | private Mode mode; |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ChameleonTargetConfiguration.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/RunnerExpressionParser.java
// public static String parseExpressions(final String value) {
// return parseExpressions(value, new SystemPropertyResolver());
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.api.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static org.arquillian.container.chameleon.runner.RunnerExpressionParser.parseExpressions; | package org.arquillian.container.chameleon.runner;
public class ChameleonTargetConfiguration {
private static final int CONTAINER = 0;
public static final int VERSION = 1;
public static final int MODE = 2;
private String container;
private String version;
private Mode mode;
private Map<String, String> customProperties = new HashMap<>();
protected ChameleonTargetConfiguration(String value) {
final String[] definition = value.split(":");
if (definition.length != 3) {
throw new IllegalArgumentException("Value of Chameleon expression must be of form container:version:mode. For example wildfly:9.0.0.Final:managed. "
+ "Refer to https://github.com/arquillian/arquillian-container-chameleon#supported-containers for the complete list of supported containers.");
}
this.container = definition[CONTAINER];
this.version = definition[VERSION];
this.mode = Mode.valueOf(definition[MODE].toUpperCase());
}
protected ChameleonTargetConfiguration(String container, String version, Mode mode,
Map<String, String> customProperties) {
this.container = container;
this.version = version;
this.mode = mode;
this.customProperties = customProperties;
}
public static ChameleonTargetConfiguration from(ChameleonTarget chameleonTarget) {
if (isContainerNotDefinedAsString(chameleonTarget)) {
return new ChameleonTargetConfiguration( | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/RunnerExpressionParser.java
// public static String parseExpressions(final String value) {
// return parseExpressions(value, new SystemPropertyResolver());
// }
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ChameleonTargetConfiguration.java
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.api.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static org.arquillian.container.chameleon.runner.RunnerExpressionParser.parseExpressions;
package org.arquillian.container.chameleon.runner;
public class ChameleonTargetConfiguration {
private static final int CONTAINER = 0;
public static final int VERSION = 1;
public static final int MODE = 2;
private String container;
private String version;
private Mode mode;
private Map<String, String> customProperties = new HashMap<>();
protected ChameleonTargetConfiguration(String value) {
final String[] definition = value.split(":");
if (definition.length != 3) {
throw new IllegalArgumentException("Value of Chameleon expression must be of form container:version:mode. For example wildfly:9.0.0.Final:managed. "
+ "Refer to https://github.com/arquillian/arquillian-container-chameleon#supported-containers for the complete list of supported containers.");
}
this.container = definition[CONTAINER];
this.version = definition[VERSION];
this.mode = Mode.valueOf(definition[MODE].toUpperCase());
}
protected ChameleonTargetConfiguration(String container, String version, Mode mode,
Map<String, String> customProperties) {
this.container = container;
this.version = version;
this.mode = mode;
this.customProperties = customProperties;
}
public static ChameleonTargetConfiguration from(ChameleonTarget chameleonTarget) {
if (isContainerNotDefinedAsString(chameleonTarget)) {
return new ChameleonTargetConfiguration( | parseExpressions(chameleonTarget.container()), |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
| import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; | package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given | final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
| import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; | package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0"); | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0"); | assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
| import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; | package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
assertThat(chameleonTargetConfiguration.getCustomProperties()).contains(entry("a", "b"));
}
@Test
public void should_get_proeprties_from_chameleon_annotation_with_system_properties() {
// given
System.setProperty("arquillian.container", "wildfly:8.2.0.Final:managed"); | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
assertThat(chameleonTargetConfiguration.getCustomProperties()).contains(entry("a", "b"));
}
@Test
public void should_get_proeprties_from_chameleon_annotation_with_system_properties() {
// given
System.setProperty("arquillian.container", "wildfly:8.2.0.Final:managed"); | final ChameleonTarget chameleonTarget = SystemPropertiesTest.class.getAnnotation(ChameleonTarget.class); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
| import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; | package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
assertThat(chameleonTargetConfiguration.getCustomProperties()).contains(entry("a", "b"));
}
@Test
public void should_get_proeprties_from_chameleon_annotation_with_system_properties() {
// given
System.setProperty("arquillian.container", "wildfly:8.2.0.Final:managed");
final ChameleonTarget chameleonTarget = SystemPropertiesTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("wildfly");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("8.2.0.Final");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
}
@Test
public void should__get_properties_from_meta_annotations() {
// given | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
assertThat(chameleonTargetConfiguration.getCustomProperties()).contains(entry("a", "b"));
}
@Test
public void should_get_proeprties_from_chameleon_annotation_with_system_properties() {
// given
System.setProperty("arquillian.container", "wildfly:8.2.0.Final:managed");
final ChameleonTarget chameleonTarget = SystemPropertiesTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("wildfly");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("8.2.0.Final");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
}
@Test
public void should__get_properties_from_meta_annotations() {
// given | final Tomcat tomcat = TomcatTest.class.getAnnotation(Tomcat.class); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
| import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; | package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
assertThat(chameleonTargetConfiguration.getCustomProperties()).contains(entry("a", "b"));
}
@Test
public void should_get_proeprties_from_chameleon_annotation_with_system_properties() {
// given
System.setProperty("arquillian.container", "wildfly:8.2.0.Final:managed");
final ChameleonTarget chameleonTarget = SystemPropertiesTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("wildfly");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("8.2.0.Final");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
}
@Test
public void should__get_properties_from_meta_annotations() {
// given
final Tomcat tomcat = TomcatTest.class.getAnnotation(Tomcat.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(tomcat);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
}
@Test
public void should_navigate_through_all_hierarchy_of_configurations() {
// given | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/SystemPropertiesTest.java
// @ChameleonTarget("${arquillian.container}")
// public class SystemPropertiesTest {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/Tomcat8Test.java
// @Tomcat8
// public class Tomcat8Test {
// }
//
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/TomcatTest.java
// @Tomcat
// public class TomcatTest {
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/AnnotationExtractorTest.java
import org.arquillian.container.chameleon.api.ChameleonTarget;
import org.arquillian.container.chameleon.api.Mode;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.arquillian.container.chameleon.runner.fixtures.SystemPropertiesTest;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8;
import org.arquillian.container.chameleon.runner.fixtures.Tomcat8Test;
import org.arquillian.container.chameleon.runner.fixtures.TomcatTest;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
package org.arquillian.container.chameleon.runner;
public class AnnotationExtractorTest {
@Test
public void should_get_proeprties_from_chameleon_annotation() {
// given
final ChameleonTarget chameleonTarget = GenericTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
assertThat(chameleonTargetConfiguration.getCustomProperties()).contains(entry("a", "b"));
}
@Test
public void should_get_proeprties_from_chameleon_annotation_with_system_properties() {
// given
System.setProperty("arquillian.container", "wildfly:8.2.0.Final:managed");
final ChameleonTarget chameleonTarget = SystemPropertiesTest.class.getAnnotation(ChameleonTarget.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(chameleonTarget);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("wildfly");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("8.2.0.Final");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
}
@Test
public void should__get_properties_from_meta_annotations() {
// given
final Tomcat tomcat = TomcatTest.class.getAnnotation(Tomcat.class);
// when
final ChameleonTargetConfiguration chameleonTargetConfiguration = AnnotationExtractor.extract(tomcat);
// then
assertThat(chameleonTargetConfiguration.getContainer()).isEqualTo("tomcat");
assertThat(chameleonTargetConfiguration.getVersion()).isEqualTo("7.0.0");
assertThat(chameleonTargetConfiguration.getMode()).isEqualTo(Mode.MANAGED);
}
@Test
public void should_navigate_through_all_hierarchy_of_configurations() {
// given | final Tomcat8 tomcat8 = Tomcat8Test.class.getAnnotation(Tomcat8.class); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/ArquillianChameleonConfigurationGeneratorTest.java | // Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
| import io.restassured.path.xml.XmlPath;
import io.restassured.path.xml.config.XmlPathConfig;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Properties;
import javax.xml.transform.TransformerException;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.when; | package org.arquillian.container.chameleon.runner;
public class ArquillianChameleonConfigurationGeneratorTest {
@Test
public void should_create_a_new_arquillian_properties() throws IOException {
// given
ArquillianChameleonConfigurationGenerator arquillianChameleonConfigurationGenerator = new ArquillianChameleonConfigurationGenerator();
// when | // Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/fixtures/GenericTest.java
// @ChameleonTarget(container = "tomcat", version = "7.0.0", customProperties = {
// @Property(name="a", value="b")
// })
// public class GenericTest {
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/ArquillianChameleonConfigurationGeneratorTest.java
import io.restassured.path.xml.XmlPath;
import io.restassured.path.xml.config.XmlPathConfig;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Properties;
import javax.xml.transform.TransformerException;
import org.arquillian.container.chameleon.runner.fixtures.GenericTest;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.when;
package org.arquillian.container.chameleon.runner;
public class ArquillianChameleonConfigurationGeneratorTest {
@Test
public void should_create_a_new_arquillian_properties() throws IOException {
// given
ArquillianChameleonConfigurationGenerator arquillianChameleonConfigurationGenerator = new ArquillianChameleonConfigurationGenerator();
// when | final Path generateArquillianProperties = arquillianChameleonConfigurationGenerator.generateNewArquillianProperties(GenericTest.class); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/ChameleonTargetConfigurationTest.java | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.arquillian.container.chameleon.api.Mode;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; | package org.arquillian.container.chameleon.runner;
public class ChameleonTargetConfigurationTest {
@Test
public void should_override_only_not_set_fields() {
// given | // Path: arquillian-chameleon-runner/api/src/main/java/org/arquillian/container/chameleon/api/Mode.java
// public enum Mode {
//
// EMBEDDED("embedded"),
// MANAGED("managed"),
// REMOTE("remote");
//
// private String mode;
//
// Mode(String mode) {
// this.mode = mode;
// }
//
// public String mode() {
// return this.mode;
// }
//
// }
// Path: arquillian-chameleon-runner/runner/src/test/java/org/arquillian/container/chameleon/runner/ChameleonTargetConfigurationTest.java
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.arquillian.container.chameleon.api.Mode;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
package org.arquillian.container.chameleon.runner;
public class ChameleonTargetConfigurationTest {
@Test
public void should_override_only_not_set_fields() {
// given | final ChameleonTargetConfiguration containerConf = new ChameleonTargetConfiguration("tomcat", "7.0.0", Mode.MANAGED, new HashMap<String, String>()); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/SimpleDeploymentTestCase.java | // Path: arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/Deployments.java
// static void enrichTomcatWithCdi(WebArchive archive) {
// String contextXml = "<Context>\n" +
// " <Resource name=\"BeanManager\" \n" +
// " auth=\"Container\"\n" +
// " type=\"javax.enterprise.inject.spi.BeanManager\"\n" +
// " factory=\"org.jboss.weld.resources.ManagerObjectFactory\"/>\n" +
// "</Context>\n";
//
// String webXml = "<web-app version=\"3.0\">\n" +
// "<listener>\n" +
// " <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>\n" +
// " </listener>" +
// " <resource-env-ref>\n" +
// " <resource-env-ref-name>BeanManager</resource-env-ref-name>\n" +
// " <resource-env-ref-type>\n" +
// " javax.enterprise.inject.spi.BeanManager\n" +
// " </resource-env-ref-type>\n" +
// " </resource-env-ref>\n" +
// "</web-app>";
//
// archive.addAsLibraries(WELD_SERVLET);
// archive.addAsManifestResource(new StringAsset(contextXml), "context.xml");
// archive.setWebXML(new StringAsset(webXml));
// }
| import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
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.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.arquillian.container.chameleon.Deployments.enrichTomcatWithCdi; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon;
@RunWith(Arquillian.class)
public class SimpleDeploymentTestCase {
@Inject
private SimpleBean bean;
@Deployment
public static WebArchive deploy() {
final String container =
System.getProperty("arq.container.chameleon.configuration.chameleonTarget", "chameleon/default");
final WebArchive archive = ShrinkWrap.create(WebArchive.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addClass(SimpleBean.class);
if (container.contains("tomcat")) { | // Path: arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/Deployments.java
// static void enrichTomcatWithCdi(WebArchive archive) {
// String contextXml = "<Context>\n" +
// " <Resource name=\"BeanManager\" \n" +
// " auth=\"Container\"\n" +
// " type=\"javax.enterprise.inject.spi.BeanManager\"\n" +
// " factory=\"org.jboss.weld.resources.ManagerObjectFactory\"/>\n" +
// "</Context>\n";
//
// String webXml = "<web-app version=\"3.0\">\n" +
// "<listener>\n" +
// " <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>\n" +
// " </listener>" +
// " <resource-env-ref>\n" +
// " <resource-env-ref-name>BeanManager</resource-env-ref-name>\n" +
// " <resource-env-ref-type>\n" +
// " javax.enterprise.inject.spi.BeanManager\n" +
// " </resource-env-ref-type>\n" +
// " </resource-env-ref>\n" +
// "</web-app>";
//
// archive.addAsLibraries(WELD_SERVLET);
// archive.addAsManifestResource(new StringAsset(contextXml), "context.xml");
// archive.setWebXML(new StringAsset(webXml));
// }
// Path: arquillian-chameleon-extension/src/test/java/org/arquillian/container/chameleon/SimpleDeploymentTestCase.java
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
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.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.arquillian.container.chameleon.Deployments.enrichTomcatWithCdi;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon;
@RunWith(Arquillian.class)
public class SimpleDeploymentTestCase {
@Inject
private SimpleBean bean;
@Deployment
public static WebArchive deploy() {
final String container =
System.getProperty("arq.container.chameleon.configuration.chameleonTarget", "chameleon/default");
final WebArchive archive = ShrinkWrap.create(WebArchive.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addClass(SimpleBean.class);
if (container.contains("tomcat")) { | enrichTomcatWithCdi(archive); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/FileUtils.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public class Target {
//
// private String server;
// private String version;
// private Type type;
//
// public static Target from(String source) {
// Target target = new Target();
//
// String[] sections = source.split(":");
// if (sections.length < 2 || sections.length > 3) {
// throw new ConfigurationException("Wrong target format [" + source + "] server:version:type");
// }
// target.server = sections[0].toLowerCase();
// target.version = sections[1];
// if (sections.length > 2) {
// for (Type type : Type.values()) {
// if (sections[2].toLowerCase().contains(type.name().toLowerCase())) {
// target.type = type;
// break;
// }
// }
// if (target.type == null) {
// throw new ConfigurationException(
// "Unknown target type " + sections[2] + ". Supported " + Target.Type.values());
// }
// } else {
// target.type = Type.Default;
// }
// return target;
// }
//
// public Type getType() {
// return type;
// }
//
// public String getServer() {
// return server;
// }
//
// public String getVersion() {
// return version;
// }
//
// @Override
// public String toString() {
// return server + ":" + version + ":" + type;
// }
//
// public boolean isSupported() throws Exception {
// Loader loader = new Loader();
// Container[] containers =
// loader.loadContainers(FileUtils.loadConfiguration("chameleon/default/containers.yaml", true));
//
// for (Container container : containers) {
// if (container.matches(this) != null) {
// return true;
// }
// }
// return false;
// }
//
// public boolean isVersionSupported() throws Exception {
// Loader loader = new Loader();
// Container[] containers =
// loader.loadContainers(FileUtils.loadConfiguration("chameleon/default/containers.yaml", true));
//
// for (Container container : containers) {
// if (container.isVersionMatches(this)) {
// return true;
// }
// }
// return false;
// }
//
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.arquillian.container.chameleon.spi.model.Target;
import org.jboss.arquillian.container.spi.ConfigurationException; | " nor classloader resource: " + resourceName);
}
}
return stream;
}
private static InputStream loadResource(String resourceName) {
InputStream stream = loadClassPathResource(resourceName);
if (stream == null) {
stream = loadFileResource(resourceName);
}
return stream;
}
private static InputStream loadFileResource(String resourceName) {
File file = new File(resourceName);
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
// should not happen unless file has been deleted since we did
// file.exists call
throw new IllegalStateException("Configuration file could not be found, " + resourceName);
}
}
return null;
}
private static InputStream loadClassPathResource(String resourceName) { | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public class Target {
//
// private String server;
// private String version;
// private Type type;
//
// public static Target from(String source) {
// Target target = new Target();
//
// String[] sections = source.split(":");
// if (sections.length < 2 || sections.length > 3) {
// throw new ConfigurationException("Wrong target format [" + source + "] server:version:type");
// }
// target.server = sections[0].toLowerCase();
// target.version = sections[1];
// if (sections.length > 2) {
// for (Type type : Type.values()) {
// if (sections[2].toLowerCase().contains(type.name().toLowerCase())) {
// target.type = type;
// break;
// }
// }
// if (target.type == null) {
// throw new ConfigurationException(
// "Unknown target type " + sections[2] + ". Supported " + Target.Type.values());
// }
// } else {
// target.type = Type.Default;
// }
// return target;
// }
//
// public Type getType() {
// return type;
// }
//
// public String getServer() {
// return server;
// }
//
// public String getVersion() {
// return version;
// }
//
// @Override
// public String toString() {
// return server + ":" + version + ":" + type;
// }
//
// public boolean isSupported() throws Exception {
// Loader loader = new Loader();
// Container[] containers =
// loader.loadContainers(FileUtils.loadConfiguration("chameleon/default/containers.yaml", true));
//
// for (Container container : containers) {
// if (container.matches(this) != null) {
// return true;
// }
// }
// return false;
// }
//
// public boolean isVersionSupported() throws Exception {
// Loader loader = new Loader();
// Container[] containers =
// loader.loadContainers(FileUtils.loadConfiguration("chameleon/default/containers.yaml", true));
//
// for (Container container : containers) {
// if (container.isVersionMatches(this)) {
// return true;
// }
// }
// return false;
// }
//
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
// }
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/FileUtils.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.arquillian.container.chameleon.spi.model.Target;
import org.jboss.arquillian.container.spi.ConfigurationException;
" nor classloader resource: " + resourceName);
}
}
return stream;
}
private static InputStream loadResource(String resourceName) {
InputStream stream = loadClassPathResource(resourceName);
if (stream == null) {
stream = loadFileResource(resourceName);
}
return stream;
}
private static InputStream loadFileResource(String resourceName) {
File file = new File(resourceName);
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
// should not happen unless file has been deleted since we did
// file.exists call
throw new IllegalStateException("Configuration file could not be found, " + resourceName);
}
}
return null;
}
private static InputStream loadClassPathResource(String resourceName) { | ClassLoader classLoader = Target.class.getClassLoader(); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/DistributionController.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/Utils.java
// public static MavenCoordinate toMavenCoordinate(String dep) {
// return MavenCoordinates.createCoordinate(dep);
// }
| import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.arquillian.spacelift.Spacelift;
import org.arquillian.spacelift.execution.Execution;
import org.arquillian.spacelift.task.net.DownloadTool;
import org.jboss.arquillian.config.descriptor.api.ContainerDef;
import org.jboss.arquillian.core.api.threading.ExecutorService;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
import org.jboss.shrinkwrap.api.importer.ZipImporter;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate;
import static org.arquillian.container.chameleon.Utils.toMavenCoordinate; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon.controller;
public class DistributionController {
private static final String PROGRESS_INDICATOR = ".";
private static final int HALF_A_SECOND = 500;
| // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/Utils.java
// public static MavenCoordinate toMavenCoordinate(String dep) {
// return MavenCoordinates.createCoordinate(dep);
// }
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/DistributionController.java
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.arquillian.spacelift.Spacelift;
import org.arquillian.spacelift.execution.Execution;
import org.arquillian.spacelift.task.net.DownloadTool;
import org.jboss.arquillian.config.descriptor.api.ContainerDef;
import org.jboss.arquillian.core.api.threading.ExecutorService;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
import org.jboss.shrinkwrap.api.importer.ZipImporter;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate;
import static org.arquillian.container.chameleon.Utils.toMavenCoordinate;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon.controller;
public class DistributionController {
private static final String PROGRESS_INDICATOR = ".";
private static final int HALF_A_SECOND = 500;
| private ContainerAdapter targetAdapter; |
arquillian/arquillian-container-chameleon | arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/DistributionController.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/Utils.java
// public static MavenCoordinate toMavenCoordinate(String dep) {
// return MavenCoordinates.createCoordinate(dep);
// }
| import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.arquillian.spacelift.Spacelift;
import org.arquillian.spacelift.execution.Execution;
import org.arquillian.spacelift.task.net.DownloadTool;
import org.jboss.arquillian.config.descriptor.api.ContainerDef;
import org.jboss.arquillian.core.api.threading.ExecutorService;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
import org.jboss.shrinkwrap.api.importer.ZipImporter;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate;
import static org.arquillian.container.chameleon.Utils.toMavenCoordinate; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon.controller;
public class DistributionController {
private static final String PROGRESS_INDICATOR = ".";
private static final int HALF_A_SECOND = 500;
private ContainerAdapter targetAdapter;
private String distributionDownloadFolder;
public DistributionController(ContainerAdapter targetAdapter, String distributionDownloadFolder) {
this.targetAdapter = targetAdapter;
this.distributionDownloadFolder = distributionDownloadFolder;
}
public void setup(ContainerDef targetConfiguration, ExecutorService executor) throws Exception {
if (requireDistribution(targetConfiguration)) {
updateTargetConfiguration(targetConfiguration, resolveDistribution(executor));
}
}
private boolean requireDistribution(ContainerDef targetConfiguration) {
if (targetAdapter.requireDistribution() && requiredConfigurationNotSet(targetConfiguration, targetAdapter)) { | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/Utils.java
// public static MavenCoordinate toMavenCoordinate(String dep) {
// return MavenCoordinates.createCoordinate(dep);
// }
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/DistributionController.java
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.arquillian.spacelift.Spacelift;
import org.arquillian.spacelift.execution.Execution;
import org.arquillian.spacelift.task.net.DownloadTool;
import org.jboss.arquillian.config.descriptor.api.ContainerDef;
import org.jboss.arquillian.core.api.threading.ExecutorService;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
import org.jboss.shrinkwrap.api.importer.ZipImporter;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate;
import static org.arquillian.container.chameleon.Utils.toMavenCoordinate;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon.controller;
public class DistributionController {
private static final String PROGRESS_INDICATOR = ".";
private static final int HALF_A_SECOND = 500;
private ContainerAdapter targetAdapter;
private String distributionDownloadFolder;
public DistributionController(ContainerAdapter targetAdapter, String distributionDownloadFolder) {
this.targetAdapter = targetAdapter;
this.distributionDownloadFolder = distributionDownloadFolder;
}
public void setup(ContainerDef targetConfiguration, ExecutorService executor) throws Exception {
if (requireDistribution(targetConfiguration)) {
updateTargetConfiguration(targetConfiguration, resolveDistribution(executor));
}
}
private boolean requireDistribution(ContainerDef targetConfiguration) {
if (targetAdapter.requireDistribution() && requiredConfigurationNotSet(targetConfiguration, targetAdapter)) { | if (targetAdapter.type() == Type.Embedded || targetAdapter.type() == Type.Managed) { |
arquillian/arquillian-container-chameleon | arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/DistributionController.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/Utils.java
// public static MavenCoordinate toMavenCoordinate(String dep) {
// return MavenCoordinates.createCoordinate(dep);
// }
| import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.arquillian.spacelift.Spacelift;
import org.arquillian.spacelift.execution.Execution;
import org.arquillian.spacelift.task.net.DownloadTool;
import org.jboss.arquillian.config.descriptor.api.ContainerDef;
import org.jboss.arquillian.core.api.threading.ExecutorService;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
import org.jboss.shrinkwrap.api.importer.ZipImporter;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate;
import static org.arquillian.container.chameleon.Utils.toMavenCoordinate; | serverName);
if (serverAlreadyDownloaded(targetDirectory)) {
return getDistributionHome(targetDirectory);
}
System.out.println("Arquillian Chameleon: downloading distribution from " + distribution);
final String targetArchive = targetDirectory + "/" + serverName + ".zip";
final Execution<File> download =
Spacelift.task(DownloadTool.class).from(distribution).to(targetArchive).execute();
try {
while (!download.isFinished()) {
System.out.print(PROGRESS_INDICATOR);
Thread.sleep(HALF_A_SECOND);
}
System.out.print(PROGRESS_INDICATOR);
final File compressedServer = download.await();
ShrinkWrap.create(ZipImporter.class, serverName)
.importFrom(compressedServer)
.as(ExplodedExporter.class)
.exportExploded(targetDirectory, ".");
compressedServer.delete();
return getDistributionHome(targetDirectory);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private File fetchFromMavenRepository(ExecutorService executor) { | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/ContainerAdapter.java
// public class ContainerAdapter {
//
// private String version;
// private Target.Type targetType;
// private Adapter adapter;
// private Dist dist;
// private String[] gavExcludeExpression;
// private String defaultProtocol;
//
// public ContainerAdapter(String version, Target.Type targetType, Adapter adapter, Dist dist,
// String[] gavExcludeExpression, String defaultProtocol) {
// this.version = version;
// this.targetType = targetType;
// this.adapter = adapter;
// this.dist = dist;
// this.gavExcludeExpression = gavExcludeExpression;
// this.defaultProtocol = defaultProtocol;
// }
//
// public Target.Type type() {
// return targetType;
// }
//
// public boolean overrideDefaultProtocol() {
// return this.defaultProtocol != null;
// }
//
// public String getDefaultProtocol() {
// return defaultProtocol;
// }
//
// public String adapterClass() {
// return adapter.adapterClass();
// }
//
// public String[] dependencies() {
// return resolve(adapter.dependencies());
// }
//
// public String distribution() {
// return resolve(dist.coordinates());
// }
//
// public String[] excludes() {
// return resolve(gavExcludeExpression);
// }
//
// public String[] configurationKeys() {
// return adapter.configuration().keySet().toArray(new String[] {});
// }
//
// public boolean requireDistribution() {
// return adapter.requireDist();
// }
//
// public Map<String, String> resolveConfiguration(Map<String, String> parameters) {
// Map<String, String> configuration = adapter.configuration();
// for (Map.Entry<String, String> entry : configuration.entrySet()) {
// for (Map.Entry<String, String> parameter : parameters.entrySet()) {
// entry.setValue(resolve(parameter.getKey(), parameter.getValue(), entry.getValue()));
// }
// }
// return configuration;
// }
//
// private String[] resolve(String[] values) {
// if (values == null) {
// return new String[0];
// }
// String[] resolved = new String[values.length];
// for (int i = 0; i < values.length; i++) {
// resolved[i] = resolve(values[i]);
// }
// return resolved;
// }
//
// private String resolve(String value) {
// return resolve("version", version, value);
// }
//
// private String resolve(String parameter, String value, String target) {
// return target.replaceAll(Pattern.quote("${" + parameter + "}"), Matcher.quoteReplacement(value));
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
// public enum Type {
// Remote, Managed, Embedded, Default;
//
// public static Type from(String name) {
// for (Type type : Type.values()) {
// if (type.name().equalsIgnoreCase(name)) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/Utils.java
// public static MavenCoordinate toMavenCoordinate(String dep) {
// return MavenCoordinates.createCoordinate(dep);
// }
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/DistributionController.java
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.arquillian.container.chameleon.spi.model.ContainerAdapter;
import org.arquillian.container.chameleon.spi.model.Target.Type;
import org.arquillian.spacelift.Spacelift;
import org.arquillian.spacelift.execution.Execution;
import org.arquillian.spacelift.task.net.DownloadTool;
import org.jboss.arquillian.config.descriptor.api.ContainerDef;
import org.jboss.arquillian.core.api.threading.ExecutorService;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
import org.jboss.shrinkwrap.api.importer.ZipImporter;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate;
import static org.arquillian.container.chameleon.Utils.toMavenCoordinate;
serverName);
if (serverAlreadyDownloaded(targetDirectory)) {
return getDistributionHome(targetDirectory);
}
System.out.println("Arquillian Chameleon: downloading distribution from " + distribution);
final String targetArchive = targetDirectory + "/" + serverName + ".zip";
final Execution<File> download =
Spacelift.task(DownloadTool.class).from(distribution).to(targetArchive).execute();
try {
while (!download.isFinished()) {
System.out.print(PROGRESS_INDICATOR);
Thread.sleep(HALF_A_SECOND);
}
System.out.print(PROGRESS_INDICATOR);
final File compressedServer = download.await();
ShrinkWrap.create(ZipImporter.class, serverName)
.importFrom(compressedServer)
.as(ExplodedExporter.class)
.exportExploded(targetDirectory, ".");
compressedServer.delete();
return getDistributionHome(targetDirectory);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private File fetchFromMavenRepository(ExecutorService executor) { | final MavenCoordinate distributableCoordinate = toMavenCoordinate(targetAdapter.distribution()); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/FileUtils.java
// public class FileUtils {
//
// public static InputStream loadConfiguration(String resourceName, boolean isDefault) {
// InputStream stream = loadResource(resourceName);
// if (stream == null) {
// if (isDefault) {
// throw new IllegalStateException(
// "Could not find built-in configuration as file nor classloader resource: " + resourceName + ". " +
// "Make sure that this file exists in classpath resource or in the project folder.");
// } else {
// throw new ConfigurationException(
// "Could not locate configured containerConfigurationFile as file" +
// " nor classloader resource: " + resourceName);
// }
// }
//
// return stream;
// }
//
// private static InputStream loadResource(String resourceName) {
// InputStream stream = loadClassPathResource(resourceName);
// if (stream == null) {
// stream = loadFileResource(resourceName);
// }
// return stream;
// }
//
// private static InputStream loadFileResource(String resourceName) {
// File file = new File(resourceName);
// if (file.exists()) {
// try {
// return new FileInputStream(file);
// } catch (FileNotFoundException e) {
// // should not happen unless file has been deleted since we did
// // file.exists call
// throw new IllegalStateException("Configuration file could not be found, " + resourceName);
// }
// }
// return null;
// }
//
// private static InputStream loadClassPathResource(String resourceName) {
// ClassLoader classLoader = Target.class.getClassLoader();
// return classLoader.getResourceAsStream(resourceName);
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/Loader.java
// public class Loader {
//
// /*
// Constructor constructor = new Constructor();
// constructor.addTypeDescription(new TypeDescription(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Yaml yaml = new Yaml(constructor);
// yaml.setBeanAccess(BeanAccess.FIELD);
//
// return yaml.loadAs(containers, Container[].class);
// */
// protected Container[] loadContainers(ClassLoader classloader, InputStream containers) throws Exception {
// Class<?> constructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.Constructor");
// Class<?> baseConstructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.BaseConstructor");
//
// Class<?> typeDescriptionClass = classloader.loadClass("org.yaml.snakeyaml.TypeDescription");
// Class<?> yamlClass = classloader.loadClass("org.yaml.snakeyaml.Yaml");
// Class<?> beanAccessClass = classloader.loadClass("org.yaml.snakeyaml.introspector.BeanAccess");
// Constructor<?> typeDescriptionConst =
// typeDescriptionClass.getConstructor(new Class[] {Class.class, String.class});
//
// Method addTypeDescription =
// constructorClass.getMethod("addTypeDescription", new Class<?>[] {typeDescriptionClass});
//
// Method setBeanAccess = yamlClass.getDeclaredMethod("setBeanAccess", new Class<?>[] {beanAccessClass});
// Method loadAs = yamlClass.getDeclaredMethod("loadAs", new Class<?>[] {InputStream.class, Class.class});
//
// Object constructor = constructorClass.newInstance();
//
// // Pre register type to avoid Yaml trying Class.forName on it's own classloader with our class.
// addTypeDescription.invoke(constructor,
// typeDescriptionConst.newInstance(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Object yaml =
// yamlClass.getConstructor(new Class[] {baseConstructorClass}).newInstance(new Object[] {constructor});
//
// Object fieldBeanAccess = null;
// for (Object beanAccess : beanAccessClass.getEnumConstants()) {
// if ("FIELD".equals(beanAccess.toString())) {
// fieldBeanAccess = beanAccess;
// break;
// }
// }
//
// setBeanAccess.invoke(yaml, fieldBeanAccess);
//
// return (Container[]) loadAs.invoke(yaml, new Object[] {containers, Container[].class});
// }
//
// public Container[] loadContainers(InputStream inputStream) throws Exception {
// return this.loadContainers(Target.class.getClassLoader(), inputStream);
// }
// }
| import org.arquillian.container.chameleon.FileUtils;
import org.arquillian.container.chameleon.Loader;
import org.jboss.arquillian.container.spi.ConfigurationException; | }
}
if (target.type == null) {
throw new ConfigurationException(
"Unknown target type " + sections[2] + ". Supported " + Target.Type.values());
}
} else {
target.type = Type.Default;
}
return target;
}
public Type getType() {
return type;
}
public String getServer() {
return server;
}
public String getVersion() {
return version;
}
@Override
public String toString() {
return server + ":" + version + ":" + type;
}
public boolean isSupported() throws Exception { | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/FileUtils.java
// public class FileUtils {
//
// public static InputStream loadConfiguration(String resourceName, boolean isDefault) {
// InputStream stream = loadResource(resourceName);
// if (stream == null) {
// if (isDefault) {
// throw new IllegalStateException(
// "Could not find built-in configuration as file nor classloader resource: " + resourceName + ". " +
// "Make sure that this file exists in classpath resource or in the project folder.");
// } else {
// throw new ConfigurationException(
// "Could not locate configured containerConfigurationFile as file" +
// " nor classloader resource: " + resourceName);
// }
// }
//
// return stream;
// }
//
// private static InputStream loadResource(String resourceName) {
// InputStream stream = loadClassPathResource(resourceName);
// if (stream == null) {
// stream = loadFileResource(resourceName);
// }
// return stream;
// }
//
// private static InputStream loadFileResource(String resourceName) {
// File file = new File(resourceName);
// if (file.exists()) {
// try {
// return new FileInputStream(file);
// } catch (FileNotFoundException e) {
// // should not happen unless file has been deleted since we did
// // file.exists call
// throw new IllegalStateException("Configuration file could not be found, " + resourceName);
// }
// }
// return null;
// }
//
// private static InputStream loadClassPathResource(String resourceName) {
// ClassLoader classLoader = Target.class.getClassLoader();
// return classLoader.getResourceAsStream(resourceName);
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/Loader.java
// public class Loader {
//
// /*
// Constructor constructor = new Constructor();
// constructor.addTypeDescription(new TypeDescription(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Yaml yaml = new Yaml(constructor);
// yaml.setBeanAccess(BeanAccess.FIELD);
//
// return yaml.loadAs(containers, Container[].class);
// */
// protected Container[] loadContainers(ClassLoader classloader, InputStream containers) throws Exception {
// Class<?> constructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.Constructor");
// Class<?> baseConstructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.BaseConstructor");
//
// Class<?> typeDescriptionClass = classloader.loadClass("org.yaml.snakeyaml.TypeDescription");
// Class<?> yamlClass = classloader.loadClass("org.yaml.snakeyaml.Yaml");
// Class<?> beanAccessClass = classloader.loadClass("org.yaml.snakeyaml.introspector.BeanAccess");
// Constructor<?> typeDescriptionConst =
// typeDescriptionClass.getConstructor(new Class[] {Class.class, String.class});
//
// Method addTypeDescription =
// constructorClass.getMethod("addTypeDescription", new Class<?>[] {typeDescriptionClass});
//
// Method setBeanAccess = yamlClass.getDeclaredMethod("setBeanAccess", new Class<?>[] {beanAccessClass});
// Method loadAs = yamlClass.getDeclaredMethod("loadAs", new Class<?>[] {InputStream.class, Class.class});
//
// Object constructor = constructorClass.newInstance();
//
// // Pre register type to avoid Yaml trying Class.forName on it's own classloader with our class.
// addTypeDescription.invoke(constructor,
// typeDescriptionConst.newInstance(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Object yaml =
// yamlClass.getConstructor(new Class[] {baseConstructorClass}).newInstance(new Object[] {constructor});
//
// Object fieldBeanAccess = null;
// for (Object beanAccess : beanAccessClass.getEnumConstants()) {
// if ("FIELD".equals(beanAccess.toString())) {
// fieldBeanAccess = beanAccess;
// break;
// }
// }
//
// setBeanAccess.invoke(yaml, fieldBeanAccess);
//
// return (Container[]) loadAs.invoke(yaml, new Object[] {containers, Container[].class});
// }
//
// public Container[] loadContainers(InputStream inputStream) throws Exception {
// return this.loadContainers(Target.class.getClassLoader(), inputStream);
// }
// }
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
import org.arquillian.container.chameleon.FileUtils;
import org.arquillian.container.chameleon.Loader;
import org.jboss.arquillian.container.spi.ConfigurationException;
}
}
if (target.type == null) {
throw new ConfigurationException(
"Unknown target type " + sections[2] + ". Supported " + Target.Type.values());
}
} else {
target.type = Type.Default;
}
return target;
}
public Type getType() {
return type;
}
public String getServer() {
return server;
}
public String getVersion() {
return version;
}
@Override
public String toString() {
return server + ":" + version + ":" + type;
}
public boolean isSupported() throws Exception { | Loader loader = new Loader(); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/FileUtils.java
// public class FileUtils {
//
// public static InputStream loadConfiguration(String resourceName, boolean isDefault) {
// InputStream stream = loadResource(resourceName);
// if (stream == null) {
// if (isDefault) {
// throw new IllegalStateException(
// "Could not find built-in configuration as file nor classloader resource: " + resourceName + ". " +
// "Make sure that this file exists in classpath resource or in the project folder.");
// } else {
// throw new ConfigurationException(
// "Could not locate configured containerConfigurationFile as file" +
// " nor classloader resource: " + resourceName);
// }
// }
//
// return stream;
// }
//
// private static InputStream loadResource(String resourceName) {
// InputStream stream = loadClassPathResource(resourceName);
// if (stream == null) {
// stream = loadFileResource(resourceName);
// }
// return stream;
// }
//
// private static InputStream loadFileResource(String resourceName) {
// File file = new File(resourceName);
// if (file.exists()) {
// try {
// return new FileInputStream(file);
// } catch (FileNotFoundException e) {
// // should not happen unless file has been deleted since we did
// // file.exists call
// throw new IllegalStateException("Configuration file could not be found, " + resourceName);
// }
// }
// return null;
// }
//
// private static InputStream loadClassPathResource(String resourceName) {
// ClassLoader classLoader = Target.class.getClassLoader();
// return classLoader.getResourceAsStream(resourceName);
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/Loader.java
// public class Loader {
//
// /*
// Constructor constructor = new Constructor();
// constructor.addTypeDescription(new TypeDescription(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Yaml yaml = new Yaml(constructor);
// yaml.setBeanAccess(BeanAccess.FIELD);
//
// return yaml.loadAs(containers, Container[].class);
// */
// protected Container[] loadContainers(ClassLoader classloader, InputStream containers) throws Exception {
// Class<?> constructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.Constructor");
// Class<?> baseConstructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.BaseConstructor");
//
// Class<?> typeDescriptionClass = classloader.loadClass("org.yaml.snakeyaml.TypeDescription");
// Class<?> yamlClass = classloader.loadClass("org.yaml.snakeyaml.Yaml");
// Class<?> beanAccessClass = classloader.loadClass("org.yaml.snakeyaml.introspector.BeanAccess");
// Constructor<?> typeDescriptionConst =
// typeDescriptionClass.getConstructor(new Class[] {Class.class, String.class});
//
// Method addTypeDescription =
// constructorClass.getMethod("addTypeDescription", new Class<?>[] {typeDescriptionClass});
//
// Method setBeanAccess = yamlClass.getDeclaredMethod("setBeanAccess", new Class<?>[] {beanAccessClass});
// Method loadAs = yamlClass.getDeclaredMethod("loadAs", new Class<?>[] {InputStream.class, Class.class});
//
// Object constructor = constructorClass.newInstance();
//
// // Pre register type to avoid Yaml trying Class.forName on it's own classloader with our class.
// addTypeDescription.invoke(constructor,
// typeDescriptionConst.newInstance(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Object yaml =
// yamlClass.getConstructor(new Class[] {baseConstructorClass}).newInstance(new Object[] {constructor});
//
// Object fieldBeanAccess = null;
// for (Object beanAccess : beanAccessClass.getEnumConstants()) {
// if ("FIELD".equals(beanAccess.toString())) {
// fieldBeanAccess = beanAccess;
// break;
// }
// }
//
// setBeanAccess.invoke(yaml, fieldBeanAccess);
//
// return (Container[]) loadAs.invoke(yaml, new Object[] {containers, Container[].class});
// }
//
// public Container[] loadContainers(InputStream inputStream) throws Exception {
// return this.loadContainers(Target.class.getClassLoader(), inputStream);
// }
// }
| import org.arquillian.container.chameleon.FileUtils;
import org.arquillian.container.chameleon.Loader;
import org.jboss.arquillian.container.spi.ConfigurationException; | if (target.type == null) {
throw new ConfigurationException(
"Unknown target type " + sections[2] + ". Supported " + Target.Type.values());
}
} else {
target.type = Type.Default;
}
return target;
}
public Type getType() {
return type;
}
public String getServer() {
return server;
}
public String getVersion() {
return version;
}
@Override
public String toString() {
return server + ":" + version + ":" + type;
}
public boolean isSupported() throws Exception {
Loader loader = new Loader();
Container[] containers = | // Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/FileUtils.java
// public class FileUtils {
//
// public static InputStream loadConfiguration(String resourceName, boolean isDefault) {
// InputStream stream = loadResource(resourceName);
// if (stream == null) {
// if (isDefault) {
// throw new IllegalStateException(
// "Could not find built-in configuration as file nor classloader resource: " + resourceName + ". " +
// "Make sure that this file exists in classpath resource or in the project folder.");
// } else {
// throw new ConfigurationException(
// "Could not locate configured containerConfigurationFile as file" +
// " nor classloader resource: " + resourceName);
// }
// }
//
// return stream;
// }
//
// private static InputStream loadResource(String resourceName) {
// InputStream stream = loadClassPathResource(resourceName);
// if (stream == null) {
// stream = loadFileResource(resourceName);
// }
// return stream;
// }
//
// private static InputStream loadFileResource(String resourceName) {
// File file = new File(resourceName);
// if (file.exists()) {
// try {
// return new FileInputStream(file);
// } catch (FileNotFoundException e) {
// // should not happen unless file has been deleted since we did
// // file.exists call
// throw new IllegalStateException("Configuration file could not be found, " + resourceName);
// }
// }
// return null;
// }
//
// private static InputStream loadClassPathResource(String resourceName) {
// ClassLoader classLoader = Target.class.getClassLoader();
// return classLoader.getResourceAsStream(resourceName);
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/Loader.java
// public class Loader {
//
// /*
// Constructor constructor = new Constructor();
// constructor.addTypeDescription(new TypeDescription(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Yaml yaml = new Yaml(constructor);
// yaml.setBeanAccess(BeanAccess.FIELD);
//
// return yaml.loadAs(containers, Container[].class);
// */
// protected Container[] loadContainers(ClassLoader classloader, InputStream containers) throws Exception {
// Class<?> constructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.Constructor");
// Class<?> baseConstructorClass = classloader.loadClass("org.yaml.snakeyaml.constructor.BaseConstructor");
//
// Class<?> typeDescriptionClass = classloader.loadClass("org.yaml.snakeyaml.TypeDescription");
// Class<?> yamlClass = classloader.loadClass("org.yaml.snakeyaml.Yaml");
// Class<?> beanAccessClass = classloader.loadClass("org.yaml.snakeyaml.introspector.BeanAccess");
// Constructor<?> typeDescriptionConst =
// typeDescriptionClass.getConstructor(new Class[] {Class.class, String.class});
//
// Method addTypeDescription =
// constructorClass.getMethod("addTypeDescription", new Class<?>[] {typeDescriptionClass});
//
// Method setBeanAccess = yamlClass.getDeclaredMethod("setBeanAccess", new Class<?>[] {beanAccessClass});
// Method loadAs = yamlClass.getDeclaredMethod("loadAs", new Class<?>[] {InputStream.class, Class.class});
//
// Object constructor = constructorClass.newInstance();
//
// // Pre register type to avoid Yaml trying Class.forName on it's own classloader with our class.
// addTypeDescription.invoke(constructor,
// typeDescriptionConst.newInstance(Container[].class, "tag:yaml.org,2002:" + Container[].class.getName()));
//
// Object yaml =
// yamlClass.getConstructor(new Class[] {baseConstructorClass}).newInstance(new Object[] {constructor});
//
// Object fieldBeanAccess = null;
// for (Object beanAccess : beanAccessClass.getEnumConstants()) {
// if ("FIELD".equals(beanAccess.toString())) {
// fieldBeanAccess = beanAccess;
// break;
// }
// }
//
// setBeanAccess.invoke(yaml, fieldBeanAccess);
//
// return (Container[]) loadAs.invoke(yaml, new Object[] {containers, Container[].class});
// }
//
// public Container[] loadContainers(InputStream inputStream) throws Exception {
// return this.loadContainers(Target.class.getClassLoader(), inputStream);
// }
// }
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Target.java
import org.arquillian.container.chameleon.FileUtils;
import org.arquillian.container.chameleon.Loader;
import org.jboss.arquillian.container.spi.ConfigurationException;
if (target.type == null) {
throw new ConfigurationException(
"Unknown target type " + sections[2] + ". Supported " + Target.Type.values());
}
} else {
target.type = Type.Default;
}
return target;
}
public Type getType() {
return type;
}
public String getServer() {
return server;
}
public String getVersion() {
return version;
}
@Override
public String toString() {
return server + ":" + version + ":" + type;
}
public boolean isSupported() throws Exception {
Loader loader = new Loader();
Container[] containers = | loader.loadContainers(FileUtils.loadConfiguration("chameleon/default/containers.yaml", true)); |
arquillian/arquillian-container-chameleon | arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ArquillianChameleon.java | // Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/extension/ChameleonRunnerAppender.java
// public class ChameleonRunnerAppender implements AuxiliaryArchiveAppender {
//
// public static final String CHAMELEON_RUNNER_INCONTAINER_FILE = "chameleonrunner.txt";
//
// @Override
// public Archive<?> createAuxiliaryArchive() {
// return ShrinkWrap.create(JavaArchive.class, "arquillian-chameleon-runner.jar")
// .addPackage(ArquillianChameleon.class.getPackage())
// .addAsResource(new StringAsset("test"), CHAMELEON_RUNNER_INCONTAINER_FILE);
// }
// }
| import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger;
import org.arquillian.container.chameleon.runner.extension.ChameleonRunnerAppender;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.InitializationError; | new ArquillianChameleonConfigurator().setup(testClass, classLoader);
log.info(String.format("Arquillian Configuration created by Chameleon runner is placed at %s.",
arquillianChameleonConfiguration.toFile().getAbsolutePath()));
createChameleonMarkerFile(arquillianChameleonConfiguration.getParent());
addsArquillianFile(arquillianChameleonConfiguration.getParent(),
classLoader);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
super.run(notifier);
}
// We need to create an special file and put it inside classloader. This is because Chameleon runner adds configuration files dynamically inside the classpath.
// When you run your tests from your build tool, some or all of them shares the same classloader. So we need to avoid calling the same logic all the time to not get multiple files placed at classloader
// representing different versions, because then you have uncertainty on which configuration file is really used
private void createChameleonMarkerFile(Path parent) throws IOException {
final Path chameleon = parent.resolve("chameleonrunner");
Files.write(chameleon, "Chameleon Runner was there".getBytes());
}
private boolean isSpecialChameleonFile(ClassLoader parent) {
return parent.getResource("chameleonrunner") != null;
}
private boolean isInClientSide(ClassLoader parent) { | // Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/extension/ChameleonRunnerAppender.java
// public class ChameleonRunnerAppender implements AuxiliaryArchiveAppender {
//
// public static final String CHAMELEON_RUNNER_INCONTAINER_FILE = "chameleonrunner.txt";
//
// @Override
// public Archive<?> createAuxiliaryArchive() {
// return ShrinkWrap.create(JavaArchive.class, "arquillian-chameleon-runner.jar")
// .addPackage(ArquillianChameleon.class.getPackage())
// .addAsResource(new StringAsset("test"), CHAMELEON_RUNNER_INCONTAINER_FILE);
// }
// }
// Path: arquillian-chameleon-runner/runner/src/main/java/org/arquillian/container/chameleon/runner/ArquillianChameleon.java
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger;
import org.arquillian.container.chameleon.runner.extension.ChameleonRunnerAppender;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.InitializationError;
new ArquillianChameleonConfigurator().setup(testClass, classLoader);
log.info(String.format("Arquillian Configuration created by Chameleon runner is placed at %s.",
arquillianChameleonConfiguration.toFile().getAbsolutePath()));
createChameleonMarkerFile(arquillianChameleonConfiguration.getParent());
addsArquillianFile(arquillianChameleonConfiguration.getParent(),
classLoader);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
super.run(notifier);
}
// We need to create an special file and put it inside classloader. This is because Chameleon runner adds configuration files dynamically inside the classpath.
// When you run your tests from your build tool, some or all of them shares the same classloader. So we need to avoid calling the same logic all the time to not get multiple files placed at classloader
// representing different versions, because then you have uncertainty on which configuration file is really used
private void createChameleonMarkerFile(Path parent) throws IOException {
final Path chameleon = parent.resolve("chameleonrunner");
Files.write(chameleon, "Chameleon Runner was there".getBytes());
}
private boolean isSpecialChameleonFile(ClassLoader parent) {
return parent.getResource("chameleonrunner") != null;
}
private boolean isInClientSide(ClassLoader parent) { | return parent.getResourceAsStream(ChameleonRunnerAppender.CHAMELEON_RUNNER_INCONTAINER_FILE) == null; |
arquillian/arquillian-container-chameleon | arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/ContainerLoader.java | // Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/Resolver.java
// public final class Resolver {
//
// public static File[] resolve(File cacheFolder, MavenDependency[] dependencies) {
// String hash = hash(dependencies);
// File[] files;
//
// File cacheFile = getCacheFile(cacheFolder, hash);
// if (cacheFile.exists()) {
// files = readCache(cacheFile);
// } else {
// files = Maven.configureResolver()
// .addDependencies(dependencies)
// .resolve()
// .withTransitivity()
// .asFile();
//
// writeCache(getCacheFile(cacheFolder, hash), files);
// }
// return files;
// }
//
// private static void writeCache(File cacheFile, File[] files) {
// if (!cacheFile.getParentFile().exists()) {
// cacheFile.getParentFile().mkdirs();
// }
// BufferedWriter bw = null;
// try {
// bw = new BufferedWriter(new FileWriter(cacheFile));
// for (File file : files) {
// bw.write(file.getAbsolutePath());
// bw.newLine();
// }
// } catch (Exception e) {
// throw new RuntimeException("Could not write cache file " + cacheFile, e);
// } finally {
// if (bw != null) {
// try {
// bw.close();
// } catch (Exception e) {
// throw new RuntimeException("Could not close written cache file " + cacheFile, e);
// }
// }
// }
// }
//
// private static File[] readCache(File cacheFile) {
// List<File> files = new ArrayList<File>();
// BufferedReader br = null;
// try {
// br = new BufferedReader(new FileReader(cacheFile));
// String line;
// while ((line = br.readLine()) != null) {
// files.add(new File(line));
// }
// } catch (Exception e) {
// throw new RuntimeException("Could not read cache file " + cacheFile + ". Please remove the file and rerun",
// e);
// } finally {
// if (br != null) {
// try {
// br.close();
// } catch (Exception e) {
// throw new RuntimeException("Could not close read cache file " + cacheFile, e);
// }
// }
// }
// return files.toArray(new File[] {});
// }
//
// private static File getCacheFile(File cacheFolder, String hash) {
// return new File(cacheFolder, hash + ".cache");
// }
//
// private static String hash(MavenDependency[] dependencies) {
// try {
// StringBuilder sb = new StringBuilder();
// MessageDigest digest = MessageDigest.getInstance("SHA-256");
// for (MavenDependency dependency : dependencies) {
// sb.append(dependency.toString());
// }
//
// byte[] hash = digest.digest(sb.toString().getBytes());
// StringBuffer hexString = new StringBuffer();
//
// for (int i = 0; i < hash.length; i++) {
// String hex = Integer.toHexString(0xff & hash[i]);
// if (hex.length() == 1) hexString.append('0');
// hexString.append(hex);
// }
//
// return hexString.toString();
// } catch (Exception e) {
// return null;
// }
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Container.java
// public class Container {
//
// private String name;
// private String versionExpression;
// private String defaultProtocol;
//
// private Adapter[] adapters;
// private String defaultType;
//
// private Dist dist;
//
// private String[] exclude;
//
// public String getName() {
// return name;
// }
//
// public Dist getDist() {
// return dist;
// }
//
// public Adapter[] getAdapters() {
// return this.adapters;
// }
//
// public ContainerAdapter matches(Target target) {
// if (target.getServer().equalsIgnoreCase(name)) {
// if (target.getVersion().matches(versionExpression)) {
// Target.Type definedType = target.getType();
// if (target.getType() == Target.Type.Default) {
// if (defaultType != null) {
// definedType = Target.Type.from(defaultType);
// }
// }
// for (Adapter adapter : adapters) {
// if (adapter.isType(definedType)) {
// return new ContainerAdapter(
// target.getVersion(),
// definedType,
// adapter,
// dist,
// exclude,
// defaultProtocol);
// }
// }
// }
// }
// return null;
// }
//
// public boolean isVersionMatches(Target target) {
// return target.getServer().equalsIgnoreCase(name) && target.getVersion().matches(versionExpression);
// }
// }
| import java.io.File;
import java.io.InputStream;
import java.net.URLClassLoader;
import org.arquillian.container.chameleon.controller.Resolver;
import org.arquillian.container.chameleon.spi.model.Container;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon;
public class ContainerLoader extends Loader {
public Container[] load(InputStream containers, File cacheFolder) throws Exception {
MavenDependency[] mavenDependencies = Utils.toMavenDependencies(
new String[] {"org.yaml:snakeyaml:1.24"},
new String[] {});
| // Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/controller/Resolver.java
// public final class Resolver {
//
// public static File[] resolve(File cacheFolder, MavenDependency[] dependencies) {
// String hash = hash(dependencies);
// File[] files;
//
// File cacheFile = getCacheFile(cacheFolder, hash);
// if (cacheFile.exists()) {
// files = readCache(cacheFile);
// } else {
// files = Maven.configureResolver()
// .addDependencies(dependencies)
// .resolve()
// .withTransitivity()
// .asFile();
//
// writeCache(getCacheFile(cacheFolder, hash), files);
// }
// return files;
// }
//
// private static void writeCache(File cacheFile, File[] files) {
// if (!cacheFile.getParentFile().exists()) {
// cacheFile.getParentFile().mkdirs();
// }
// BufferedWriter bw = null;
// try {
// bw = new BufferedWriter(new FileWriter(cacheFile));
// for (File file : files) {
// bw.write(file.getAbsolutePath());
// bw.newLine();
// }
// } catch (Exception e) {
// throw new RuntimeException("Could not write cache file " + cacheFile, e);
// } finally {
// if (bw != null) {
// try {
// bw.close();
// } catch (Exception e) {
// throw new RuntimeException("Could not close written cache file " + cacheFile, e);
// }
// }
// }
// }
//
// private static File[] readCache(File cacheFile) {
// List<File> files = new ArrayList<File>();
// BufferedReader br = null;
// try {
// br = new BufferedReader(new FileReader(cacheFile));
// String line;
// while ((line = br.readLine()) != null) {
// files.add(new File(line));
// }
// } catch (Exception e) {
// throw new RuntimeException("Could not read cache file " + cacheFile + ". Please remove the file and rerun",
// e);
// } finally {
// if (br != null) {
// try {
// br.close();
// } catch (Exception e) {
// throw new RuntimeException("Could not close read cache file " + cacheFile, e);
// }
// }
// }
// return files.toArray(new File[] {});
// }
//
// private static File getCacheFile(File cacheFolder, String hash) {
// return new File(cacheFolder, hash + ".cache");
// }
//
// private static String hash(MavenDependency[] dependencies) {
// try {
// StringBuilder sb = new StringBuilder();
// MessageDigest digest = MessageDigest.getInstance("SHA-256");
// for (MavenDependency dependency : dependencies) {
// sb.append(dependency.toString());
// }
//
// byte[] hash = digest.digest(sb.toString().getBytes());
// StringBuffer hexString = new StringBuffer();
//
// for (int i = 0; i < hash.length; i++) {
// String hex = Integer.toHexString(0xff & hash[i]);
// if (hex.length() == 1) hexString.append('0');
// hexString.append(hex);
// }
//
// return hexString.toString();
// } catch (Exception e) {
// return null;
// }
// }
// }
//
// Path: arquillian-chameleon-container-model/src/main/java/org/arquillian/container/chameleon/spi/model/Container.java
// public class Container {
//
// private String name;
// private String versionExpression;
// private String defaultProtocol;
//
// private Adapter[] adapters;
// private String defaultType;
//
// private Dist dist;
//
// private String[] exclude;
//
// public String getName() {
// return name;
// }
//
// public Dist getDist() {
// return dist;
// }
//
// public Adapter[] getAdapters() {
// return this.adapters;
// }
//
// public ContainerAdapter matches(Target target) {
// if (target.getServer().equalsIgnoreCase(name)) {
// if (target.getVersion().matches(versionExpression)) {
// Target.Type definedType = target.getType();
// if (target.getType() == Target.Type.Default) {
// if (defaultType != null) {
// definedType = Target.Type.from(defaultType);
// }
// }
// for (Adapter adapter : adapters) {
// if (adapter.isType(definedType)) {
// return new ContainerAdapter(
// target.getVersion(),
// definedType,
// adapter,
// dist,
// exclude,
// defaultProtocol);
// }
// }
// }
// }
// return null;
// }
//
// public boolean isVersionMatches(Target target) {
// return target.getServer().equalsIgnoreCase(name) && target.getVersion().matches(versionExpression);
// }
// }
// Path: arquillian-chameleon-extension/src/main/java/org/arquillian/container/chameleon/ContainerLoader.java
import java.io.File;
import java.io.InputStream;
import java.net.URLClassLoader;
import org.arquillian.container.chameleon.controller.Resolver;
import org.arquillian.container.chameleon.spi.model.Container;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016 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.arquillian.container.chameleon;
public class ContainerLoader extends Loader {
public Container[] load(InputStream containers, File cacheFolder) throws Exception {
MavenDependency[] mavenDependencies = Utils.toMavenDependencies(
new String[] {"org.yaml:snakeyaml:1.24"},
new String[] {});
| File[] archives = Resolver.resolve(cacheFolder, mavenDependencies); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/camel/lifecycle/MainLifecycleStrategy.java | // Path: src/main/java/net/technolords/micro/registry/MockRegistry.java
// public class MockRegistry {
// private static final Logger LOGGER = LoggerFactory.getLogger(MockRegistry.class);
// private static final String BEAN_PROPERTIES = "props";
// private static final String BEAN_META_DATA_PROPERTIES = "propsMetaData";
// private static final String BEAN_METRICS = "metrics";
// private static final String BEAN_JETTY_SERVER = "jettyServer";
// private static final String BEAN_CONFIG = "config";
// private static final String BEAN_FILTER_INFO = "infoFilter";
// private static final String BEAN_RESPONSE_PROCESSOR = "responseProcessor";
// private static final String BEAN_RENEWAL_PROCESSOR = "renewalProcessor";
// private static final String BEAN_SERVICE_REGISTRATION = "serviceRegistration";
// private static Main main;
//
// /**
// * Custom constructor with a reference of the main which is used to store the properties.
// *
// * @param mainReference
// * A reference of the Main object.
// */
// public static void registerPropertiesInRegistry(Main mainReference) {
// main = mainReference;
// main.bind(BEAN_META_DATA_PROPERTIES, PropertiesManager.extractMetaData());
// main.bind(BEAN_PROPERTIES, PropertiesManager.extractProperties());
// }
//
// /**
// * Auxiliary method to register beans to the Main component, with the purpose of supporting lookup mechanism
// * in case references of the beans are required. The latter typically occurs at runtime, but also in cases
// * of lazy initialization. Note that this micro service is not using any dependency injection framework.
// *
// * @throws JAXBException
// * When creation the configuration bean fails.
// * @throws IOException
// * When creation the configuration bean fails.
// * @throws SAXException
// * When creation the configuration bean fails.
// */
// public static void registerBeansInRegistryBeforeStart() throws JAXBException, IOException, SAXException {
// main.bind(BEAN_METRICS, new StatisticsHandler());
// main.bind(BEAN_CONFIG, new ConfigurationManager(findConfiguredConfig(), findConfiguredData()));
// main.bind(BEAN_FILTER_INFO, new InfoFilter());
// main.bind(BEAN_RESPONSE_PROCESSOR, new ResponseProcessor());
// main.bind(BEAN_RENEWAL_PROCESSOR, new EurekaRenewalProcessor());
// main.bind(BEAN_SERVICE_REGISTRATION, new ServiceRegistrationManager());
// LOGGER.info("Beans added to the registry...");
// }
//
// /**
// * Auxiliary method to register beans to the Main component, but after the Main has started. Typically the
// * underlying Server is also started and instantiated.
// */
// public static void registerBeansInRegistryAfterStart() {
// StatisticsHandler statisticsHandler = findStatisticsHandler();
// Server server = statisticsHandler.getServer();
// main.bind(BEAN_JETTY_SERVER, server);
// InfoFilter.registerFilterDirectlyWithServer(server);
// }
//
// // -------------------------------
// // Find beans (sorted by alphabet)
// // -------------------------------
//
// public static ConfigurationManager findConfigurationManager() {
// return main.lookup(BEAN_CONFIG, ConfigurationManager.class);
// }
//
// public static EurekaRenewalProcessor findEurekaRenewalProcessor() {
// return main.lookup(BEAN_RENEWAL_PROCESSOR, EurekaRenewalProcessor.class);
// }
//
// public static InfoFilter findInfoFilter() {
// return main.lookup(BEAN_FILTER_INFO, InfoFilter.class);
// }
//
// public static Properties findProperties() {
// return main.lookup(BEAN_PROPERTIES, Properties.class);
// }
//
// public static ResponseProcessor findResponseProcessor() {
// return main.lookup(BEAN_RESPONSE_PROCESSOR, ResponseProcessor.class);
// }
//
// public static Server findJettyServer() {
// return main.lookup(BEAN_JETTY_SERVER, Server.class);
// }
//
// public static ServiceRegistrationManager findRegistrationManager() {
// return main.lookup(BEAN_SERVICE_REGISTRATION, ServiceRegistrationManager.class);
// }
//
// public static StatisticsHandler findStatisticsHandler() {
// return main.lookup(BEAN_METRICS, StatisticsHandler.class);
// }
//
// // -----------------------------------------
// // Find property values (sorted by alphabet)
// // -----------------------------------------
//
// public static String findConfiguredPort() {
// return (String) findProperties().get(PropertiesManager.PROP_PORT);
// }
//
// public static String findConfiguredConfig() {
// return (String) findProperties().get(PropertiesManager.PROP_CONFIG);
// }
//
// public static String findConfiguredData() {
// return (String) findProperties().get(PropertiesManager.PROP_DATA);
// }
//
// public static String findBuildMetaData() {
// Properties properties = main.lookup(BEAN_META_DATA_PROPERTIES, Properties.class);
// StringBuilder buffer = new StringBuilder();
// buffer.append(properties.get(PROP_BUILD_VERSION));
// buffer.append(" ");
// buffer.append(properties.get(PROP_BUILD_DATE));
// return buffer.toString();
// }
//
// }
| import org.apache.camel.CamelContext;
import org.apache.camel.VetoCamelContextStartException;
import org.apache.camel.management.DefaultManagementLifecycleStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.registry.MockRegistry; | package net.technolords.micro.camel.lifecycle;
public class MainLifecycleStrategy extends DefaultManagementLifecycleStrategy {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
public MainLifecycleStrategy(CamelContext camelContext) {
super(camelContext);
}
@Override
public void onContextStart(CamelContext camelContext) throws VetoCamelContextStartException {
LOGGER.debug("onContextStart called..."); | // Path: src/main/java/net/technolords/micro/registry/MockRegistry.java
// public class MockRegistry {
// private static final Logger LOGGER = LoggerFactory.getLogger(MockRegistry.class);
// private static final String BEAN_PROPERTIES = "props";
// private static final String BEAN_META_DATA_PROPERTIES = "propsMetaData";
// private static final String BEAN_METRICS = "metrics";
// private static final String BEAN_JETTY_SERVER = "jettyServer";
// private static final String BEAN_CONFIG = "config";
// private static final String BEAN_FILTER_INFO = "infoFilter";
// private static final String BEAN_RESPONSE_PROCESSOR = "responseProcessor";
// private static final String BEAN_RENEWAL_PROCESSOR = "renewalProcessor";
// private static final String BEAN_SERVICE_REGISTRATION = "serviceRegistration";
// private static Main main;
//
// /**
// * Custom constructor with a reference of the main which is used to store the properties.
// *
// * @param mainReference
// * A reference of the Main object.
// */
// public static void registerPropertiesInRegistry(Main mainReference) {
// main = mainReference;
// main.bind(BEAN_META_DATA_PROPERTIES, PropertiesManager.extractMetaData());
// main.bind(BEAN_PROPERTIES, PropertiesManager.extractProperties());
// }
//
// /**
// * Auxiliary method to register beans to the Main component, with the purpose of supporting lookup mechanism
// * in case references of the beans are required. The latter typically occurs at runtime, but also in cases
// * of lazy initialization. Note that this micro service is not using any dependency injection framework.
// *
// * @throws JAXBException
// * When creation the configuration bean fails.
// * @throws IOException
// * When creation the configuration bean fails.
// * @throws SAXException
// * When creation the configuration bean fails.
// */
// public static void registerBeansInRegistryBeforeStart() throws JAXBException, IOException, SAXException {
// main.bind(BEAN_METRICS, new StatisticsHandler());
// main.bind(BEAN_CONFIG, new ConfigurationManager(findConfiguredConfig(), findConfiguredData()));
// main.bind(BEAN_FILTER_INFO, new InfoFilter());
// main.bind(BEAN_RESPONSE_PROCESSOR, new ResponseProcessor());
// main.bind(BEAN_RENEWAL_PROCESSOR, new EurekaRenewalProcessor());
// main.bind(BEAN_SERVICE_REGISTRATION, new ServiceRegistrationManager());
// LOGGER.info("Beans added to the registry...");
// }
//
// /**
// * Auxiliary method to register beans to the Main component, but after the Main has started. Typically the
// * underlying Server is also started and instantiated.
// */
// public static void registerBeansInRegistryAfterStart() {
// StatisticsHandler statisticsHandler = findStatisticsHandler();
// Server server = statisticsHandler.getServer();
// main.bind(BEAN_JETTY_SERVER, server);
// InfoFilter.registerFilterDirectlyWithServer(server);
// }
//
// // -------------------------------
// // Find beans (sorted by alphabet)
// // -------------------------------
//
// public static ConfigurationManager findConfigurationManager() {
// return main.lookup(BEAN_CONFIG, ConfigurationManager.class);
// }
//
// public static EurekaRenewalProcessor findEurekaRenewalProcessor() {
// return main.lookup(BEAN_RENEWAL_PROCESSOR, EurekaRenewalProcessor.class);
// }
//
// public static InfoFilter findInfoFilter() {
// return main.lookup(BEAN_FILTER_INFO, InfoFilter.class);
// }
//
// public static Properties findProperties() {
// return main.lookup(BEAN_PROPERTIES, Properties.class);
// }
//
// public static ResponseProcessor findResponseProcessor() {
// return main.lookup(BEAN_RESPONSE_PROCESSOR, ResponseProcessor.class);
// }
//
// public static Server findJettyServer() {
// return main.lookup(BEAN_JETTY_SERVER, Server.class);
// }
//
// public static ServiceRegistrationManager findRegistrationManager() {
// return main.lookup(BEAN_SERVICE_REGISTRATION, ServiceRegistrationManager.class);
// }
//
// public static StatisticsHandler findStatisticsHandler() {
// return main.lookup(BEAN_METRICS, StatisticsHandler.class);
// }
//
// // -----------------------------------------
// // Find property values (sorted by alphabet)
// // -----------------------------------------
//
// public static String findConfiguredPort() {
// return (String) findProperties().get(PropertiesManager.PROP_PORT);
// }
//
// public static String findConfiguredConfig() {
// return (String) findProperties().get(PropertiesManager.PROP_CONFIG);
// }
//
// public static String findConfiguredData() {
// return (String) findProperties().get(PropertiesManager.PROP_DATA);
// }
//
// public static String findBuildMetaData() {
// Properties properties = main.lookup(BEAN_META_DATA_PROPERTIES, Properties.class);
// StringBuilder buffer = new StringBuilder();
// buffer.append(properties.get(PROP_BUILD_VERSION));
// buffer.append(" ");
// buffer.append(properties.get(PROP_BUILD_DATE));
// return buffer.toString();
// }
//
// }
// Path: src/main/java/net/technolords/micro/camel/lifecycle/MainLifecycleStrategy.java
import org.apache.camel.CamelContext;
import org.apache.camel.VetoCamelContextStartException;
import org.apache.camel.management.DefaultManagementLifecycleStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.registry.MockRegistry;
package net.technolords.micro.camel.lifecycle;
public class MainLifecycleStrategy extends DefaultManagementLifecycleStrategy {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
public MainLifecycleStrategy(CamelContext camelContext) {
super(camelContext);
}
@Override
public void onContextStart(CamelContext camelContext) throws VetoCamelContextStartException {
LOGGER.debug("onContextStart called..."); | MockRegistry.findRegistrationManager().registerService(); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/input/xml/XpathEvaluator.java | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
| import java.io.IOException;
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import net.technolords.micro.model.jaxb.Configuration; | package net.technolords.micro.input.xml;
public class XpathEvaluator {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private ConfigurationToNamespaceContext configurationToNamespaceContext = null;
private XPathFactory xPathFactory = null;
/**
* Auxiliary method that evaluates the given xpath expression with the given message.
*
* NOTE: currently only 'boolean' xpath expressions are supported. Meaning, any node list
* selection or otherwise will fail. TODO: result typing, to support different xpath queries.
*
* @param xpathExpression
* The xpath expression to evaluate.
* @param xmlMessage
* The xml message associated with the xpath evaluation.
* @param configuration
* The configuration associated with the namespaces.
*
* @return
* The result of the xpath expression, which means it is either a match or not.
*
* @throws XPathExpressionException
* When evaluation the xpath expression fails.
* @throws IOException
* When reading the input source fails.
*/ | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/input/xml/XpathEvaluator.java
import java.io.IOException;
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import net.technolords.micro.model.jaxb.Configuration;
package net.technolords.micro.input.xml;
public class XpathEvaluator {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private ConfigurationToNamespaceContext configurationToNamespaceContext = null;
private XPathFactory xPathFactory = null;
/**
* Auxiliary method that evaluates the given xpath expression with the given message.
*
* NOTE: currently only 'boolean' xpath expressions are supported. Meaning, any node list
* selection or otherwise will fail. TODO: result typing, to support different xpath queries.
*
* @param xpathExpression
* The xpath expression to evaluate.
* @param xmlMessage
* The xml message associated with the xpath evaluation.
* @param configuration
* The configuration associated with the namespaces.
*
* @return
* The result of the xpath expression, which means it is either a match or not.
*
* @throws XPathExpressionException
* When evaluation the xpath expression fails.
* @throws IOException
* When reading the input source fails.
*/ | public boolean evaluateXpathExpression(String xpathExpression, String xmlMessage, Configuration configuration) throws XPathExpressionException, IOException { |
Technolords/microservice-mock | src/test/java/net/technolords/micro/test/factory/ServiceFactory.java | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/HealthCheck.java
// public class HealthCheck {
// private boolean enabled;
// private String interval;
// private String deRegisterAfter;
//
// @XmlAttribute (name = "enabled")
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @XmlAttribute (name = "interval")
// public String getInterval() {
// return interval;
// }
//
// public void setInterval(String interval) {
// this.interval = interval;
// }
//
// @XmlAttribute (name = "deregister-after")
// public String getDeRegisterAfter() {
// return deRegisterAfter;
// }
//
// public void setDeRegisterAfter(String deRegisterAfter) {
// this.deRegisterAfter = deRegisterAfter;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
| import net.technolords.micro.model.jaxb.registration.HealthCheck;
import net.technolords.micro.model.jaxb.registration.Service; | package net.technolords.micro.test.factory;
public class ServiceFactory {
/**
* Create a service like:
*
* <service address="192.168.10.10" port="9090" id="mock-1" name="mock-service" >
* <health-check enabled="true" interval="60s" deregister-after="90m"/>
* </service>
*
* @return
* A service
*/
public static Service createService() {
Service service = new Service();
service.setId("mock-1");
service.setName("mock-service");
service.setAddress("192.168.10.10");
service.setPort(9090); | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/HealthCheck.java
// public class HealthCheck {
// private boolean enabled;
// private String interval;
// private String deRegisterAfter;
//
// @XmlAttribute (name = "enabled")
// public boolean isEnabled() {
// return enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @XmlAttribute (name = "interval")
// public String getInterval() {
// return interval;
// }
//
// public void setInterval(String interval) {
// this.interval = interval;
// }
//
// @XmlAttribute (name = "deregister-after")
// public String getDeRegisterAfter() {
// return deRegisterAfter;
// }
//
// public void setDeRegisterAfter(String deRegisterAfter) {
// this.deRegisterAfter = deRegisterAfter;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
// Path: src/test/java/net/technolords/micro/test/factory/ServiceFactory.java
import net.technolords.micro.model.jaxb.registration.HealthCheck;
import net.technolords.micro.model.jaxb.registration.Service;
package net.technolords.micro.test.factory;
public class ServiceFactory {
/**
* Create a service like:
*
* <service address="192.168.10.10" port="9090" id="mock-1" name="mock-service" >
* <health-check enabled="true" interval="60s" deregister-after="90m"/>
* </service>
*
* @return
* A service
*/
public static Service createService() {
Service service = new Service();
service.setId("mock-1");
service.setName("mock-service");
service.setAddress("192.168.10.10");
service.setPort(9090); | HealthCheck healthCheck = new HealthCheck(); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/command/Command.java | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
| import org.apache.camel.Exchange;
import net.technolords.micro.model.ResponseContext; | package net.technolords.micro.command;
public interface Command {
String CONFIG = "config";
String LOG = "log";
String RESET = "reset";
String STATS = "stats";
String STOP = "stop";
String getId(); | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
// Path: src/main/java/net/technolords/micro/command/Command.java
import org.apache.camel.Exchange;
import net.technolords.micro.model.ResponseContext;
package net.technolords.micro.command;
public interface Command {
String CONFIG = "config";
String LOG = "log";
String RESET = "reset";
String STATS = "stats";
String STOP = "stop";
String getId(); | ResponseContext executeCommand(Exchange exchange); |
Technolords/microservice-mock | src/test/java/net/technolords/micro/log/LogManagerTest.java | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
| import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.ResponseContext; | { "info", Level.INFO, "Log level changed to INFO" },
{ "debug", Level.DEBUG, "Log level changed to DEBUG" },
{ "off", Level.OFF, "Logging switched off" },
{ "oops", Level.INFO, "Log level changed to INFO" },
};
}
/**
* Auxiliary method to reset the log info, in case logging is actually required during development
* of the test.
*/
@BeforeMethod (groups = { GROUP_CHANGE_LEVEL })
public void resetLogLevelToInfo() {
LoggerConfig rootLogger = this.getRootLogger();
rootLogger.setLevel(Level.INFO);
}
/**
* This test asserts the new log level has been set as well as the expected message
* to be returned is correct.
*
* @param newLevel
* The new log level.
* @param expectedLevel
* The expected log level.
* @param expectedMessage
* The expected message.
*/
@Test (dataProvider = DATASET_FOR_CHANGING_LOG_LEVELS, groups = { GROUP_CHANGE_LEVEL} )
public void testChangeLogLevels(final String newLevel, final Level expectedLevel, final String expectedMessage) { | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
// Path: src/test/java/net/technolords/micro/log/LogManagerTest.java
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.ResponseContext;
{ "info", Level.INFO, "Log level changed to INFO" },
{ "debug", Level.DEBUG, "Log level changed to DEBUG" },
{ "off", Level.OFF, "Logging switched off" },
{ "oops", Level.INFO, "Log level changed to INFO" },
};
}
/**
* Auxiliary method to reset the log info, in case logging is actually required during development
* of the test.
*/
@BeforeMethod (groups = { GROUP_CHANGE_LEVEL })
public void resetLogLevelToInfo() {
LoggerConfig rootLogger = this.getRootLogger();
rootLogger.setLevel(Level.INFO);
}
/**
* This test asserts the new log level has been set as well as the expected message
* to be returned is correct.
*
* @param newLevel
* The new log level.
* @param expectedLevel
* The expected log level.
* @param expectedMessage
* The expected message.
*/
@Test (dataProvider = DATASET_FOR_CHANGING_LOG_LEVELS, groups = { GROUP_CHANGE_LEVEL} )
public void testChangeLogLevels(final String newLevel, final Level expectedLevel, final String expectedMessage) { | ResponseContext responseContext = LogManager.changeLogLevel(newLevel); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/model/jaxb/Configurations.java | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/ServiceRegistration.java
// public class ServiceRegistration {
// private List<Registration> registrations;
//
// @XmlElement (name = "registration")
// public List<Registration> getRegistrations() {
// return registrations;
// }
//
// public void setRegistrations(List<Registration> registrations) {
// this.registrations = registrations;
// }
//
// }
| import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import net.technolords.micro.model.jaxb.registration.ServiceRegistration; | package net.technolords.micro.model.jaxb;
@XmlRootElement(name = "configurations", namespace = "http://xsd.technolords.net")
public class Configurations { | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/ServiceRegistration.java
// public class ServiceRegistration {
// private List<Registration> registrations;
//
// @XmlElement (name = "registration")
// public List<Registration> getRegistrations() {
// return registrations;
// }
//
// public void setRegistrations(List<Registration> registrations) {
// this.registrations = registrations;
// }
//
// }
// Path: src/main/java/net/technolords/micro/model/jaxb/Configurations.java
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import net.technolords.micro.model.jaxb.registration.ServiceRegistration;
package net.technolords.micro.model.jaxb;
@XmlRootElement(name = "configurations", namespace = "http://xsd.technolords.net")
public class Configurations { | private ServiceRegistration serviceRegistration; |
Technolords/microservice-mock | src/main/java/net/technolords/micro/model/jaxb/query/QueryGroup.java | // Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
| import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import net.technolords.micro.model.jaxb.resource.SimpleResource; | package net.technolords.micro.model.jaxb.query;
public class QueryGroup {
private List<QueryParameter> queryParameters; | // Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroup.java
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import net.technolords.micro.model.jaxb.resource.SimpleResource;
package net.technolords.micro.model.jaxb.query;
public class QueryGroup {
private List<QueryParameter> queryParameters; | private SimpleResource simpleResource; |
Technolords/microservice-mock | src/test/java/net/technolords/micro/registry/eureka/EurekaRequestFactoryTest.java | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
//
// Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
| import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.jaxb.registration.Registration;
import net.technolords.micro.model.jaxb.registration.Service;
import net.technolords.micro.test.factory.ConfigurationsFactory; | package net.technolords.micro.registry.eureka;
public class EurekaRequestFactoryTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String DATASET_FOR_REGISTER = "dataSetForRegister";
@Test
public void testCreateRegisterRequest() { | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
//
// Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
// Path: src/test/java/net/technolords/micro/registry/eureka/EurekaRequestFactoryTest.java
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.jaxb.registration.Registration;
import net.technolords.micro.model.jaxb.registration.Service;
import net.technolords.micro.test.factory.ConfigurationsFactory;
package net.technolords.micro.registry.eureka;
public class EurekaRequestFactoryTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String DATASET_FOR_REGISTER = "dataSetForRegister";
@Test
public void testCreateRegisterRequest() { | Registration registration = this.createRegistration("mock-service", "mock-1", "localhost", 9090); |
Technolords/microservice-mock | src/test/java/net/technolords/micro/registry/eureka/EurekaRequestFactoryTest.java | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
//
// Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
| import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.jaxb.registration.Registration;
import net.technolords.micro.model.jaxb.registration.Service;
import net.technolords.micro.test.factory.ConfigurationsFactory; | package net.technolords.micro.registry.eureka;
public class EurekaRequestFactoryTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String DATASET_FOR_REGISTER = "dataSetForRegister";
@Test
public void testCreateRegisterRequest() {
Registration registration = this.createRegistration("mock-service", "mock-1", "localhost", 9090); | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
//
// Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
// Path: src/test/java/net/technolords/micro/registry/eureka/EurekaRequestFactoryTest.java
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.jaxb.registration.Registration;
import net.technolords.micro.model.jaxb.registration.Service;
import net.technolords.micro.test.factory.ConfigurationsFactory;
package net.technolords.micro.registry.eureka;
public class EurekaRequestFactoryTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String DATASET_FOR_REGISTER = "dataSetForRegister";
@Test
public void testCreateRegisterRequest() {
Registration registration = this.createRegistration("mock-service", "mock-1", "localhost", 9090); | HttpPost httpPost = (HttpPost) EurekaRequestFactory.createRegisterRequest(registration, ConfigurationsFactory.createConfigurations()); |
Technolords/microservice-mock | src/test/java/net/technolords/micro/registry/eureka/EurekaRequestFactoryTest.java | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
//
// Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
| import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.jaxb.registration.Registration;
import net.technolords.micro.model.jaxb.registration.Service;
import net.technolords.micro.test.factory.ConfigurationsFactory; | package net.technolords.micro.registry.eureka;
public class EurekaRequestFactoryTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String DATASET_FOR_REGISTER = "dataSetForRegister";
@Test
public void testCreateRegisterRequest() {
Registration registration = this.createRegistration("mock-service", "mock-1", "localhost", 9090);
HttpPost httpPost = (HttpPost) EurekaRequestFactory.createRegisterRequest(registration, ConfigurationsFactory.createConfigurations());
Assert.assertNotNull(httpPost);
}
/**
* - service name
* - service instance
* - host
* - port
* - expected
*
* @return
*/
@DataProvider(name = DATASET_FOR_REGISTER)
public Object[][] dataSetMock(){
return new Object[][] {
{ "mock-service", "mock-1", "localhost", 9090, "http://localhost:9090/eureka/v2/apps/mock-service"},
};
}
@Test (dataProvider = DATASET_FOR_REGISTER)
public void testGenerateUrlForRegister(String name, String id, String host, int port, String expected) {
Registration registration = this.createRegistration(name, id, host, port);
String actual = EurekaRequestFactory.generateUrlForRegister(registration);
Assert.assertEquals(expected, actual);
}
protected Registration createRegistration(String name, String id, String host, int port) {
Registration registration = new Registration();
registration.setAddress(host);
registration.setPort(port); | // Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Service.java
// public class Service {
// private String address;
// private int port;
// private String id;
// private String name;
// private HealthCheck healthCheck;
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlAttribute (name = "id")
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// @XmlAttribute (name = "name")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @XmlElement (name = "health-check")
// public HealthCheck getHealthCheck() {
// return healthCheck;
// }
//
// public void setHealthCheck(HealthCheck healthCheck) {
// this.healthCheck = healthCheck;
// }
// }
//
// Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
// Path: src/test/java/net/technolords/micro/registry/eureka/EurekaRequestFactoryTest.java
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import net.technolords.micro.model.jaxb.registration.Registration;
import net.technolords.micro.model.jaxb.registration.Service;
import net.technolords.micro.test.factory.ConfigurationsFactory;
package net.technolords.micro.registry.eureka;
public class EurekaRequestFactoryTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String DATASET_FOR_REGISTER = "dataSetForRegister";
@Test
public void testCreateRegisterRequest() {
Registration registration = this.createRegistration("mock-service", "mock-1", "localhost", 9090);
HttpPost httpPost = (HttpPost) EurekaRequestFactory.createRegisterRequest(registration, ConfigurationsFactory.createConfigurations());
Assert.assertNotNull(httpPost);
}
/**
* - service name
* - service instance
* - host
* - port
* - expected
*
* @return
*/
@DataProvider(name = DATASET_FOR_REGISTER)
public Object[][] dataSetMock(){
return new Object[][] {
{ "mock-service", "mock-1", "localhost", 9090, "http://localhost:9090/eureka/v2/apps/mock-service"},
};
}
@Test (dataProvider = DATASET_FOR_REGISTER)
public void testGenerateUrlForRegister(String name, String id, String host, int port, String expected) {
Registration registration = this.createRegistration(name, id, host, port);
String actual = EurekaRequestFactory.generateUrlForRegister(registration);
Assert.assertEquals(expected, actual);
}
protected Registration createRegistration(String name, String id, String host, int port) {
Registration registration = new Registration();
registration.setAddress(host);
registration.setPort(port); | Service service = new Service(); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/registry/eureka/EurekaRequestFactory.java | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
| import java.util.List;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration; | package net.technolords.micro.registry.eureka;
public class EurekaRequestFactory {
private static final String API_SERVICE_REGISTER = "/eureka/v2/apps/";
private static final String API_SERVICE_DEREGISTER = "/eureka/v2/apps/";
/**
* A factory for a HttpPost method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPost
*
* @return
* The generated httpPost
*/ | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
// Path: src/main/java/net/technolords/micro/registry/eureka/EurekaRequestFactory.java
import java.util.List;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration;
package net.technolords.micro.registry.eureka;
public class EurekaRequestFactory {
private static final String API_SERVICE_REGISTER = "/eureka/v2/apps/";
private static final String API_SERVICE_DEREGISTER = "/eureka/v2/apps/";
/**
* A factory for a HttpPost method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPost
*
* @return
* The generated httpPost
*/ | public static HttpEntityEnclosingRequestBase createRegisterRequest(Registration registration, List<Configuration> configurations) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/registry/eureka/EurekaRequestFactory.java | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
| import java.util.List;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration; | package net.technolords.micro.registry.eureka;
public class EurekaRequestFactory {
private static final String API_SERVICE_REGISTER = "/eureka/v2/apps/";
private static final String API_SERVICE_DEREGISTER = "/eureka/v2/apps/";
/**
* A factory for a HttpPost method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPost
*
* @return
* The generated httpPost
*/ | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
// Path: src/main/java/net/technolords/micro/registry/eureka/EurekaRequestFactory.java
import java.util.List;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration;
package net.technolords.micro.registry.eureka;
public class EurekaRequestFactory {
private static final String API_SERVICE_REGISTER = "/eureka/v2/apps/";
private static final String API_SERVICE_DEREGISTER = "/eureka/v2/apps/";
/**
* A factory for a HttpPost method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPost
*
* @return
* The generated httpPost
*/ | public static HttpEntityEnclosingRequestBase createRegisterRequest(Registration registration, List<Configuration> configurations) { |
Technolords/microservice-mock | src/test/java/net/technolords/micro/registry/util/MetadataHelperTest.java | // Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import net.technolords.micro.test.factory.ConfigurationsFactory; | package net.technolords.micro.registry.util;
public class MetadataHelperTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
@Test (description = "Test creation of the meta data string")
public void testAddMetadataEntries() {
StringBuilder buffer = new StringBuilder(); | // Path: src/test/java/net/technolords/micro/test/factory/ConfigurationsFactory.java
// public class ConfigurationsFactory {
//
// public static List<Configuration> createConfigurations() {
// List<Configuration> configurations = new ArrayList<>();
// // Get
// Configuration configuration = new Configuration();
// configuration.setType("get");
// configuration.setUrl("/mock/get");
// configurations.add(configuration);
// // Post 1
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post1");
// configurations.add(configuration);
// // Post 2
// configuration = new Configuration();
// configuration.setType("post");
// configuration.setUrl("/mock/post2");
// configurations.add(configuration);
// return configurations;
// }
// }
// Path: src/test/java/net/technolords/micro/registry/util/MetadataHelperTest.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import net.technolords.micro.test.factory.ConfigurationsFactory;
package net.technolords.micro.registry.util;
public class MetadataHelperTest {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
@Test (description = "Test creation of the meta data string")
public void testAddMetadataEntries() {
StringBuilder buffer = new StringBuilder(); | MetadataHelper.addMetadataEntries(buffer, ConfigurationsFactory.createConfigurations()); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/output/ResponseContextGenerator.java | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext;
import net.technolords.micro.model.jaxb.resource.SimpleResource; | package net.technolords.micro.output;
public class ResponseContextGenerator {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private Path pathToDataFolder;
/**
* Custom constructor, which caches the path to the data folder. Note that this can be null.
*
* @param pathToDataFolder
* The path to the data folder.
*/
public ResponseContextGenerator(Path pathToDataFolder) {
this.pathToDataFolder = pathToDataFolder;
}
/**
* Auxiliary method that reads the response data as well as updating the internal cache so
* subsequent reads will will served from memory. It also implements the delay and updates
* the ResponseContext with an erroneous status code if the error rate is triggered.
*
* @param resource
* The resource to read and cache.
*
* @return
* The data associated with the resource (i.e. response).
*
* @throws IOException
* When reading the resource fails.
*/ | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/output/ResponseContextGenerator.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext;
import net.technolords.micro.model.jaxb.resource.SimpleResource;
package net.technolords.micro.output;
public class ResponseContextGenerator {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private Path pathToDataFolder;
/**
* Custom constructor, which caches the path to the data folder. Note that this can be null.
*
* @param pathToDataFolder
* The path to the data folder.
*/
public ResponseContextGenerator(Path pathToDataFolder) {
this.pathToDataFolder = pathToDataFolder;
}
/**
* Auxiliary method that reads the response data as well as updating the internal cache so
* subsequent reads will will served from memory. It also implements the delay and updates
* the ResponseContext with an erroneous status code if the error rate is triggered.
*
* @param resource
* The resource to read and cache.
*
* @return
* The data associated with the resource (i.e. response).
*
* @throws IOException
* When reading the resource fails.
*/ | public ResponseContext readResourceCacheOrFile(SimpleResource resource) throws IOException, InterruptedException { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/output/ResponseContextGenerator.java | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext;
import net.technolords.micro.model.jaxb.resource.SimpleResource; | package net.technolords.micro.output;
public class ResponseContextGenerator {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private Path pathToDataFolder;
/**
* Custom constructor, which caches the path to the data folder. Note that this can be null.
*
* @param pathToDataFolder
* The path to the data folder.
*/
public ResponseContextGenerator(Path pathToDataFolder) {
this.pathToDataFolder = pathToDataFolder;
}
/**
* Auxiliary method that reads the response data as well as updating the internal cache so
* subsequent reads will will served from memory. It also implements the delay and updates
* the ResponseContext with an erroneous status code if the error rate is triggered.
*
* @param resource
* The resource to read and cache.
*
* @return
* The data associated with the resource (i.e. response).
*
* @throws IOException
* When reading the resource fails.
*/ | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/output/ResponseContextGenerator.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext;
import net.technolords.micro.model.jaxb.resource.SimpleResource;
package net.technolords.micro.output;
public class ResponseContextGenerator {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private Path pathToDataFolder;
/**
* Custom constructor, which caches the path to the data folder. Note that this can be null.
*
* @param pathToDataFolder
* The path to the data folder.
*/
public ResponseContextGenerator(Path pathToDataFolder) {
this.pathToDataFolder = pathToDataFolder;
}
/**
* Auxiliary method that reads the response data as well as updating the internal cache so
* subsequent reads will will served from memory. It also implements the delay and updates
* the ResponseContext with an erroneous status code if the error rate is triggered.
*
* @param resource
* The resource to read and cache.
*
* @return
* The data associated with the resource (i.e. response).
*
* @throws IOException
* When reading the resource fails.
*/ | public ResponseContext readResourceCacheOrFile(SimpleResource resource) throws IOException, InterruptedException { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/camel/route/EurekaRenewalRoute.java | // Path: src/main/java/net/technolords/micro/registry/MockRegistry.java
// public class MockRegistry {
// private static final Logger LOGGER = LoggerFactory.getLogger(MockRegistry.class);
// private static final String BEAN_PROPERTIES = "props";
// private static final String BEAN_META_DATA_PROPERTIES = "propsMetaData";
// private static final String BEAN_METRICS = "metrics";
// private static final String BEAN_JETTY_SERVER = "jettyServer";
// private static final String BEAN_CONFIG = "config";
// private static final String BEAN_FILTER_INFO = "infoFilter";
// private static final String BEAN_RESPONSE_PROCESSOR = "responseProcessor";
// private static final String BEAN_RENEWAL_PROCESSOR = "renewalProcessor";
// private static final String BEAN_SERVICE_REGISTRATION = "serviceRegistration";
// private static Main main;
//
// /**
// * Custom constructor with a reference of the main which is used to store the properties.
// *
// * @param mainReference
// * A reference of the Main object.
// */
// public static void registerPropertiesInRegistry(Main mainReference) {
// main = mainReference;
// main.bind(BEAN_META_DATA_PROPERTIES, PropertiesManager.extractMetaData());
// main.bind(BEAN_PROPERTIES, PropertiesManager.extractProperties());
// }
//
// /**
// * Auxiliary method to register beans to the Main component, with the purpose of supporting lookup mechanism
// * in case references of the beans are required. The latter typically occurs at runtime, but also in cases
// * of lazy initialization. Note that this micro service is not using any dependency injection framework.
// *
// * @throws JAXBException
// * When creation the configuration bean fails.
// * @throws IOException
// * When creation the configuration bean fails.
// * @throws SAXException
// * When creation the configuration bean fails.
// */
// public static void registerBeansInRegistryBeforeStart() throws JAXBException, IOException, SAXException {
// main.bind(BEAN_METRICS, new StatisticsHandler());
// main.bind(BEAN_CONFIG, new ConfigurationManager(findConfiguredConfig(), findConfiguredData()));
// main.bind(BEAN_FILTER_INFO, new InfoFilter());
// main.bind(BEAN_RESPONSE_PROCESSOR, new ResponseProcessor());
// main.bind(BEAN_RENEWAL_PROCESSOR, new EurekaRenewalProcessor());
// main.bind(BEAN_SERVICE_REGISTRATION, new ServiceRegistrationManager());
// LOGGER.info("Beans added to the registry...");
// }
//
// /**
// * Auxiliary method to register beans to the Main component, but after the Main has started. Typically the
// * underlying Server is also started and instantiated.
// */
// public static void registerBeansInRegistryAfterStart() {
// StatisticsHandler statisticsHandler = findStatisticsHandler();
// Server server = statisticsHandler.getServer();
// main.bind(BEAN_JETTY_SERVER, server);
// InfoFilter.registerFilterDirectlyWithServer(server);
// }
//
// // -------------------------------
// // Find beans (sorted by alphabet)
// // -------------------------------
//
// public static ConfigurationManager findConfigurationManager() {
// return main.lookup(BEAN_CONFIG, ConfigurationManager.class);
// }
//
// public static EurekaRenewalProcessor findEurekaRenewalProcessor() {
// return main.lookup(BEAN_RENEWAL_PROCESSOR, EurekaRenewalProcessor.class);
// }
//
// public static InfoFilter findInfoFilter() {
// return main.lookup(BEAN_FILTER_INFO, InfoFilter.class);
// }
//
// public static Properties findProperties() {
// return main.lookup(BEAN_PROPERTIES, Properties.class);
// }
//
// public static ResponseProcessor findResponseProcessor() {
// return main.lookup(BEAN_RESPONSE_PROCESSOR, ResponseProcessor.class);
// }
//
// public static Server findJettyServer() {
// return main.lookup(BEAN_JETTY_SERVER, Server.class);
// }
//
// public static ServiceRegistrationManager findRegistrationManager() {
// return main.lookup(BEAN_SERVICE_REGISTRATION, ServiceRegistrationManager.class);
// }
//
// public static StatisticsHandler findStatisticsHandler() {
// return main.lookup(BEAN_METRICS, StatisticsHandler.class);
// }
//
// // -----------------------------------------
// // Find property values (sorted by alphabet)
// // -----------------------------------------
//
// public static String findConfiguredPort() {
// return (String) findProperties().get(PropertiesManager.PROP_PORT);
// }
//
// public static String findConfiguredConfig() {
// return (String) findProperties().get(PropertiesManager.PROP_CONFIG);
// }
//
// public static String findConfiguredData() {
// return (String) findProperties().get(PropertiesManager.PROP_DATA);
// }
//
// public static String findBuildMetaData() {
// Properties properties = main.lookup(BEAN_META_DATA_PROPERTIES, Properties.class);
// StringBuilder buffer = new StringBuilder();
// buffer.append(properties.get(PROP_BUILD_VERSION));
// buffer.append(" ");
// buffer.append(properties.get(PROP_BUILD_DATE));
// return buffer.toString();
// }
//
// }
| import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.registry.MockRegistry; | package net.technolords.micro.camel.route;
public class EurekaRenewalRoute extends RouteBuilder {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String ROUTE_ID_RENEWAL = "RouteRenewal";
private Processor renewalProcessor = null;
public EurekaRenewalRoute() { | // Path: src/main/java/net/technolords/micro/registry/MockRegistry.java
// public class MockRegistry {
// private static final Logger LOGGER = LoggerFactory.getLogger(MockRegistry.class);
// private static final String BEAN_PROPERTIES = "props";
// private static final String BEAN_META_DATA_PROPERTIES = "propsMetaData";
// private static final String BEAN_METRICS = "metrics";
// private static final String BEAN_JETTY_SERVER = "jettyServer";
// private static final String BEAN_CONFIG = "config";
// private static final String BEAN_FILTER_INFO = "infoFilter";
// private static final String BEAN_RESPONSE_PROCESSOR = "responseProcessor";
// private static final String BEAN_RENEWAL_PROCESSOR = "renewalProcessor";
// private static final String BEAN_SERVICE_REGISTRATION = "serviceRegistration";
// private static Main main;
//
// /**
// * Custom constructor with a reference of the main which is used to store the properties.
// *
// * @param mainReference
// * A reference of the Main object.
// */
// public static void registerPropertiesInRegistry(Main mainReference) {
// main = mainReference;
// main.bind(BEAN_META_DATA_PROPERTIES, PropertiesManager.extractMetaData());
// main.bind(BEAN_PROPERTIES, PropertiesManager.extractProperties());
// }
//
// /**
// * Auxiliary method to register beans to the Main component, with the purpose of supporting lookup mechanism
// * in case references of the beans are required. The latter typically occurs at runtime, but also in cases
// * of lazy initialization. Note that this micro service is not using any dependency injection framework.
// *
// * @throws JAXBException
// * When creation the configuration bean fails.
// * @throws IOException
// * When creation the configuration bean fails.
// * @throws SAXException
// * When creation the configuration bean fails.
// */
// public static void registerBeansInRegistryBeforeStart() throws JAXBException, IOException, SAXException {
// main.bind(BEAN_METRICS, new StatisticsHandler());
// main.bind(BEAN_CONFIG, new ConfigurationManager(findConfiguredConfig(), findConfiguredData()));
// main.bind(BEAN_FILTER_INFO, new InfoFilter());
// main.bind(BEAN_RESPONSE_PROCESSOR, new ResponseProcessor());
// main.bind(BEAN_RENEWAL_PROCESSOR, new EurekaRenewalProcessor());
// main.bind(BEAN_SERVICE_REGISTRATION, new ServiceRegistrationManager());
// LOGGER.info("Beans added to the registry...");
// }
//
// /**
// * Auxiliary method to register beans to the Main component, but after the Main has started. Typically the
// * underlying Server is also started and instantiated.
// */
// public static void registerBeansInRegistryAfterStart() {
// StatisticsHandler statisticsHandler = findStatisticsHandler();
// Server server = statisticsHandler.getServer();
// main.bind(BEAN_JETTY_SERVER, server);
// InfoFilter.registerFilterDirectlyWithServer(server);
// }
//
// // -------------------------------
// // Find beans (sorted by alphabet)
// // -------------------------------
//
// public static ConfigurationManager findConfigurationManager() {
// return main.lookup(BEAN_CONFIG, ConfigurationManager.class);
// }
//
// public static EurekaRenewalProcessor findEurekaRenewalProcessor() {
// return main.lookup(BEAN_RENEWAL_PROCESSOR, EurekaRenewalProcessor.class);
// }
//
// public static InfoFilter findInfoFilter() {
// return main.lookup(BEAN_FILTER_INFO, InfoFilter.class);
// }
//
// public static Properties findProperties() {
// return main.lookup(BEAN_PROPERTIES, Properties.class);
// }
//
// public static ResponseProcessor findResponseProcessor() {
// return main.lookup(BEAN_RESPONSE_PROCESSOR, ResponseProcessor.class);
// }
//
// public static Server findJettyServer() {
// return main.lookup(BEAN_JETTY_SERVER, Server.class);
// }
//
// public static ServiceRegistrationManager findRegistrationManager() {
// return main.lookup(BEAN_SERVICE_REGISTRATION, ServiceRegistrationManager.class);
// }
//
// public static StatisticsHandler findStatisticsHandler() {
// return main.lookup(BEAN_METRICS, StatisticsHandler.class);
// }
//
// // -----------------------------------------
// // Find property values (sorted by alphabet)
// // -----------------------------------------
//
// public static String findConfiguredPort() {
// return (String) findProperties().get(PropertiesManager.PROP_PORT);
// }
//
// public static String findConfiguredConfig() {
// return (String) findProperties().get(PropertiesManager.PROP_CONFIG);
// }
//
// public static String findConfiguredData() {
// return (String) findProperties().get(PropertiesManager.PROP_DATA);
// }
//
// public static String findBuildMetaData() {
// Properties properties = main.lookup(BEAN_META_DATA_PROPERTIES, Properties.class);
// StringBuilder buffer = new StringBuilder();
// buffer.append(properties.get(PROP_BUILD_VERSION));
// buffer.append(" ");
// buffer.append(properties.get(PROP_BUILD_DATE));
// return buffer.toString();
// }
//
// }
// Path: src/main/java/net/technolords/micro/camel/route/EurekaRenewalRoute.java
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.registry.MockRegistry;
package net.technolords.micro.camel.route;
public class EurekaRenewalRoute extends RouteBuilder {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String ROUTE_ID_RENEWAL = "RouteRenewal";
private Processor renewalProcessor = null;
public EurekaRenewalRoute() { | this.renewalProcessor = MockRegistry.findEurekaRenewalProcessor(); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/input/json/JsonPathEvaluator.java | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
| import java.util.List;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import net.technolords.micro.model.jaxb.Configuration; | package net.technolords.micro.input.json;
public class JsonPathEvaluator {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonPathEvaluator.class);
| // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/input/json/JsonPathEvaluator.java
import java.util.List;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import net.technolords.micro.model.jaxb.Configuration;
package net.technolords.micro.input.json;
public class JsonPathEvaluator {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonPathEvaluator.class);
| public boolean evaluateXpathExpression(String jsonpathAsString, String message, Configuration configuration) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/command/CommandManager.java | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
| import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext; | package net.technolords.micro.command;
public class CommandManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CommandManager.class);
private static List<Command> supportedCommands = Arrays.asList(
new ConfigCommand(),
new LogCommand(),
new ResetCommand(),
new StatsCommand(),
new StopCommand()
);
/**
* Auxiliary method that executes a command by delegation (provided the command is supported).
*
* @param exchange
* The exchange associated with the command.
*
* @return
* The result of the command execution.
*/ | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
// Path: src/main/java/net/technolords/micro/command/CommandManager.java
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext;
package net.technolords.micro.command;
public class CommandManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CommandManager.class);
private static List<Command> supportedCommands = Arrays.asList(
new ConfigCommand(),
new LogCommand(),
new ResetCommand(),
new StatsCommand(),
new StopCommand()
);
/**
* Auxiliary method that executes a command by delegation (provided the command is supported).
*
* @param exchange
* The exchange associated with the command.
*
* @return
* The result of the command execution.
*/ | public static ResponseContext executeCommand(Exchange exchange) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/input/ConfigurationSelector.java | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.jaxb.Configuration; | package net.technolords.micro.input;
public class ConfigurationSelector {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String WILD_CARD = "\\*";
/**
* Auxiliary method to find the Configuration associated with a path and a map of configurations. Since wild cards
* are supported, multiple matches can be found. If so, a decision is forced to return one match.
*
* @param path
* The path associated with the Configuration.
* @param configurations
* A sub section of the entire map of Configurations. For example all GET related configurations. The smaller the
* map size, the quicker the matching is done. Note that no match means a null reference is returned (which will
* lead to a 404 not found).
*
* @return
* A matching configuration (or null when none was found).
*/ | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/input/ConfigurationSelector.java
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.jaxb.Configuration;
package net.technolords.micro.input;
public class ConfigurationSelector {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final String WILD_CARD = "\\*";
/**
* Auxiliary method to find the Configuration associated with a path and a map of configurations. Since wild cards
* are supported, multiple matches can be found. If so, a decision is forced to return one match.
*
* @param path
* The path associated with the Configuration.
* @param configurations
* A sub section of the entire map of Configurations. For example all GET related configurations. The smaller the
* map size, the quicker the matching is done. Note that no match means a null reference is returned (which will
* lead to a 404 not found).
*
* @return
* A matching configuration (or null when none was found).
*/ | public Configuration findMatchingConfiguration(String path, Map<String, Configuration> configurations) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/camel/route/MockRoute.java | // Path: src/main/java/net/technolords/micro/registry/MockRegistry.java
// public class MockRegistry {
// private static final Logger LOGGER = LoggerFactory.getLogger(MockRegistry.class);
// private static final String BEAN_PROPERTIES = "props";
// private static final String BEAN_META_DATA_PROPERTIES = "propsMetaData";
// private static final String BEAN_METRICS = "metrics";
// private static final String BEAN_JETTY_SERVER = "jettyServer";
// private static final String BEAN_CONFIG = "config";
// private static final String BEAN_FILTER_INFO = "infoFilter";
// private static final String BEAN_RESPONSE_PROCESSOR = "responseProcessor";
// private static final String BEAN_RENEWAL_PROCESSOR = "renewalProcessor";
// private static final String BEAN_SERVICE_REGISTRATION = "serviceRegistration";
// private static Main main;
//
// /**
// * Custom constructor with a reference of the main which is used to store the properties.
// *
// * @param mainReference
// * A reference of the Main object.
// */
// public static void registerPropertiesInRegistry(Main mainReference) {
// main = mainReference;
// main.bind(BEAN_META_DATA_PROPERTIES, PropertiesManager.extractMetaData());
// main.bind(BEAN_PROPERTIES, PropertiesManager.extractProperties());
// }
//
// /**
// * Auxiliary method to register beans to the Main component, with the purpose of supporting lookup mechanism
// * in case references of the beans are required. The latter typically occurs at runtime, but also in cases
// * of lazy initialization. Note that this micro service is not using any dependency injection framework.
// *
// * @throws JAXBException
// * When creation the configuration bean fails.
// * @throws IOException
// * When creation the configuration bean fails.
// * @throws SAXException
// * When creation the configuration bean fails.
// */
// public static void registerBeansInRegistryBeforeStart() throws JAXBException, IOException, SAXException {
// main.bind(BEAN_METRICS, new StatisticsHandler());
// main.bind(BEAN_CONFIG, new ConfigurationManager(findConfiguredConfig(), findConfiguredData()));
// main.bind(BEAN_FILTER_INFO, new InfoFilter());
// main.bind(BEAN_RESPONSE_PROCESSOR, new ResponseProcessor());
// main.bind(BEAN_RENEWAL_PROCESSOR, new EurekaRenewalProcessor());
// main.bind(BEAN_SERVICE_REGISTRATION, new ServiceRegistrationManager());
// LOGGER.info("Beans added to the registry...");
// }
//
// /**
// * Auxiliary method to register beans to the Main component, but after the Main has started. Typically the
// * underlying Server is also started and instantiated.
// */
// public static void registerBeansInRegistryAfterStart() {
// StatisticsHandler statisticsHandler = findStatisticsHandler();
// Server server = statisticsHandler.getServer();
// main.bind(BEAN_JETTY_SERVER, server);
// InfoFilter.registerFilterDirectlyWithServer(server);
// }
//
// // -------------------------------
// // Find beans (sorted by alphabet)
// // -------------------------------
//
// public static ConfigurationManager findConfigurationManager() {
// return main.lookup(BEAN_CONFIG, ConfigurationManager.class);
// }
//
// public static EurekaRenewalProcessor findEurekaRenewalProcessor() {
// return main.lookup(BEAN_RENEWAL_PROCESSOR, EurekaRenewalProcessor.class);
// }
//
// public static InfoFilter findInfoFilter() {
// return main.lookup(BEAN_FILTER_INFO, InfoFilter.class);
// }
//
// public static Properties findProperties() {
// return main.lookup(BEAN_PROPERTIES, Properties.class);
// }
//
// public static ResponseProcessor findResponseProcessor() {
// return main.lookup(BEAN_RESPONSE_PROCESSOR, ResponseProcessor.class);
// }
//
// public static Server findJettyServer() {
// return main.lookup(BEAN_JETTY_SERVER, Server.class);
// }
//
// public static ServiceRegistrationManager findRegistrationManager() {
// return main.lookup(BEAN_SERVICE_REGISTRATION, ServiceRegistrationManager.class);
// }
//
// public static StatisticsHandler findStatisticsHandler() {
// return main.lookup(BEAN_METRICS, StatisticsHandler.class);
// }
//
// // -----------------------------------------
// // Find property values (sorted by alphabet)
// // -----------------------------------------
//
// public static String findConfiguredPort() {
// return (String) findProperties().get(PropertiesManager.PROP_PORT);
// }
//
// public static String findConfiguredConfig() {
// return (String) findProperties().get(PropertiesManager.PROP_CONFIG);
// }
//
// public static String findConfiguredData() {
// return (String) findProperties().get(PropertiesManager.PROP_DATA);
// }
//
// public static String findBuildMetaData() {
// Properties properties = main.lookup(BEAN_META_DATA_PROPERTIES, Properties.class);
// StringBuilder buffer = new StringBuilder();
// buffer.append(properties.get(PROP_BUILD_VERSION));
// buffer.append(" ");
// buffer.append(properties.get(PROP_BUILD_DATE));
// return buffer.toString();
// }
//
// }
| import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.registry.MockRegistry; | package net.technolords.micro.camel.route;
public class MockRoute extends RouteBuilder {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
public static final String ROUTE_ID_JETTY = "RouteJetty";
public static final String ROUTE_ID_MAIN = "RouteMain";
private static final String DIRECT_MAIN = "direct:main";
private static final String JETTY_MAIN = "jetty:http://";
private static final String JETTY_BINDING_ADDRESS = "0.0.0.0";
private static final String JETTY_BINDING_PATH = "/";
private static final String QUESTION_SIGN = "?";
private static final String AND_SIGN = "&";
private static final String EQUAL_SIGN = "=";
private static final String TRUE_VALUE = "true";
private String port = null;
private Processor responseProcessor = null;
public MockRoute() { | // Path: src/main/java/net/technolords/micro/registry/MockRegistry.java
// public class MockRegistry {
// private static final Logger LOGGER = LoggerFactory.getLogger(MockRegistry.class);
// private static final String BEAN_PROPERTIES = "props";
// private static final String BEAN_META_DATA_PROPERTIES = "propsMetaData";
// private static final String BEAN_METRICS = "metrics";
// private static final String BEAN_JETTY_SERVER = "jettyServer";
// private static final String BEAN_CONFIG = "config";
// private static final String BEAN_FILTER_INFO = "infoFilter";
// private static final String BEAN_RESPONSE_PROCESSOR = "responseProcessor";
// private static final String BEAN_RENEWAL_PROCESSOR = "renewalProcessor";
// private static final String BEAN_SERVICE_REGISTRATION = "serviceRegistration";
// private static Main main;
//
// /**
// * Custom constructor with a reference of the main which is used to store the properties.
// *
// * @param mainReference
// * A reference of the Main object.
// */
// public static void registerPropertiesInRegistry(Main mainReference) {
// main = mainReference;
// main.bind(BEAN_META_DATA_PROPERTIES, PropertiesManager.extractMetaData());
// main.bind(BEAN_PROPERTIES, PropertiesManager.extractProperties());
// }
//
// /**
// * Auxiliary method to register beans to the Main component, with the purpose of supporting lookup mechanism
// * in case references of the beans are required. The latter typically occurs at runtime, but also in cases
// * of lazy initialization. Note that this micro service is not using any dependency injection framework.
// *
// * @throws JAXBException
// * When creation the configuration bean fails.
// * @throws IOException
// * When creation the configuration bean fails.
// * @throws SAXException
// * When creation the configuration bean fails.
// */
// public static void registerBeansInRegistryBeforeStart() throws JAXBException, IOException, SAXException {
// main.bind(BEAN_METRICS, new StatisticsHandler());
// main.bind(BEAN_CONFIG, new ConfigurationManager(findConfiguredConfig(), findConfiguredData()));
// main.bind(BEAN_FILTER_INFO, new InfoFilter());
// main.bind(BEAN_RESPONSE_PROCESSOR, new ResponseProcessor());
// main.bind(BEAN_RENEWAL_PROCESSOR, new EurekaRenewalProcessor());
// main.bind(BEAN_SERVICE_REGISTRATION, new ServiceRegistrationManager());
// LOGGER.info("Beans added to the registry...");
// }
//
// /**
// * Auxiliary method to register beans to the Main component, but after the Main has started. Typically the
// * underlying Server is also started and instantiated.
// */
// public static void registerBeansInRegistryAfterStart() {
// StatisticsHandler statisticsHandler = findStatisticsHandler();
// Server server = statisticsHandler.getServer();
// main.bind(BEAN_JETTY_SERVER, server);
// InfoFilter.registerFilterDirectlyWithServer(server);
// }
//
// // -------------------------------
// // Find beans (sorted by alphabet)
// // -------------------------------
//
// public static ConfigurationManager findConfigurationManager() {
// return main.lookup(BEAN_CONFIG, ConfigurationManager.class);
// }
//
// public static EurekaRenewalProcessor findEurekaRenewalProcessor() {
// return main.lookup(BEAN_RENEWAL_PROCESSOR, EurekaRenewalProcessor.class);
// }
//
// public static InfoFilter findInfoFilter() {
// return main.lookup(BEAN_FILTER_INFO, InfoFilter.class);
// }
//
// public static Properties findProperties() {
// return main.lookup(BEAN_PROPERTIES, Properties.class);
// }
//
// public static ResponseProcessor findResponseProcessor() {
// return main.lookup(BEAN_RESPONSE_PROCESSOR, ResponseProcessor.class);
// }
//
// public static Server findJettyServer() {
// return main.lookup(BEAN_JETTY_SERVER, Server.class);
// }
//
// public static ServiceRegistrationManager findRegistrationManager() {
// return main.lookup(BEAN_SERVICE_REGISTRATION, ServiceRegistrationManager.class);
// }
//
// public static StatisticsHandler findStatisticsHandler() {
// return main.lookup(BEAN_METRICS, StatisticsHandler.class);
// }
//
// // -----------------------------------------
// // Find property values (sorted by alphabet)
// // -----------------------------------------
//
// public static String findConfiguredPort() {
// return (String) findProperties().get(PropertiesManager.PROP_PORT);
// }
//
// public static String findConfiguredConfig() {
// return (String) findProperties().get(PropertiesManager.PROP_CONFIG);
// }
//
// public static String findConfiguredData() {
// return (String) findProperties().get(PropertiesManager.PROP_DATA);
// }
//
// public static String findBuildMetaData() {
// Properties properties = main.lookup(BEAN_META_DATA_PROPERTIES, Properties.class);
// StringBuilder buffer = new StringBuilder();
// buffer.append(properties.get(PROP_BUILD_VERSION));
// buffer.append(" ");
// buffer.append(properties.get(PROP_BUILD_DATE));
// return buffer.toString();
// }
//
// }
// Path: src/main/java/net/technolords/micro/camel/route/MockRoute.java
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.registry.MockRegistry;
package net.technolords.micro.camel.route;
public class MockRoute extends RouteBuilder {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
public static final String ROUTE_ID_JETTY = "RouteJetty";
public static final String ROUTE_ID_MAIN = "RouteMain";
private static final String DIRECT_MAIN = "direct:main";
private static final String JETTY_MAIN = "jetty:http://";
private static final String JETTY_BINDING_ADDRESS = "0.0.0.0";
private static final String JETTY_BINDING_PATH = "/";
private static final String QUESTION_SIGN = "?";
private static final String AND_SIGN = "&";
private static final String EQUAL_SIGN = "=";
private static final String TRUE_VALUE = "true";
private String port = null;
private Processor responseProcessor = null;
public MockRoute() { | this.port = MockRegistry.findConfiguredPort(); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/command/LogCommand.java | // Path: src/main/java/net/technolords/micro/log/LogManager.java
// public class LogManager {
// private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
//
// /**
// * Auxiliary method to (re)initialize the logging. This method is typically called from
// * the PropertiesManager when a external log4j2 configuration is provided, while at the
// * same time no CLI parameter was given.
// *
// * Setting the new config location is enough, as it will trigger a reconfigure
// * automatically.
// *
// * @param pathToLogConfiguration
// * A path to the external log configuration file.
// */
// public static void initializeLogging(String pathToLogConfiguration) {
// Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
// LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
// LoggerContext loggerContext = LoggerContext.getContext(false);
// loggerContext.setConfigLocation(path.toUri());
// }
//
// /**
// * Auxiliary method to change the log level.
// *
// * @param logLevel
// * The log level to set.
// *
// * @return
// * A ResponseContext containing the result of the command.
// */
// public static ResponseContext changeLogLevel(String logLevel) {
// ResponseContext responseContext = new ResponseContext();
// responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
// LoggerContext loggerContext = LoggerContext.getContext(false);
// Configuration configuration = loggerContext.getConfiguration();
// LoggerConfig rootLogger = configuration.getRootLogger();
// if (rootLogger != null) {
// switch (StandardLevel.getStandardLevel(Level.toLevel(logLevel, Level.INFO).intLevel())) {
// case ERROR:
// rootLogger.setLevel(Level.ERROR);
// responseContext.setResponse("Log level changed to ERROR");
// break;
// case WARN:
// rootLogger.setLevel(Level.WARN);
// responseContext.setResponse("Log level changed to WARN");
// break;
// case INFO:
// rootLogger.setLevel(Level.INFO);
// responseContext.setResponse("Log level changed to INFO");
// break;
// case DEBUG:
// rootLogger.setLevel(Level.DEBUG);
// responseContext.setResponse("Log level changed to DEBUG");
// break;
// case OFF:
// rootLogger.setLevel(Level.OFF);
// responseContext.setResponse("Logging switched off");
// break;
// default:
// responseContext.setResponse("Log level unchanged, unsupported level: " + logLevel);
// }
// loggerContext.updateLoggers();
// } else {
// responseContext.setResponse("Unable to change log level, no ROOT logger found...");
// responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_INTERNAL_ERROR));
// }
// return responseContext;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
| import java.util.Map;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.log.LogManager;
import net.technolords.micro.model.ResponseContext; | package net.technolords.micro.command;
public class LogCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(LogCommand.class);
/**
* Auxiliary method to get the id associated with this command.
*
* @return
* The id associated with the command.
*/
@Override
public String getId() {
return Command.LOG;
}
/**
* Auxiliary method that executes the log command. For consistency this class is kept, but in reality it
* is delegated to the LogManager which consolidates all logic (as well as the required classes) with the
* underlying logging framework (other than the logging facade, i.e. SLF4J).
*
* @param exchange
* The Camel Exchange associated with the log command.
*
* @return
* The result of the log command.
*/
@Override | // Path: src/main/java/net/technolords/micro/log/LogManager.java
// public class LogManager {
// private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
//
// /**
// * Auxiliary method to (re)initialize the logging. This method is typically called from
// * the PropertiesManager when a external log4j2 configuration is provided, while at the
// * same time no CLI parameter was given.
// *
// * Setting the new config location is enough, as it will trigger a reconfigure
// * automatically.
// *
// * @param pathToLogConfiguration
// * A path to the external log configuration file.
// */
// public static void initializeLogging(String pathToLogConfiguration) {
// Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
// LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
// LoggerContext loggerContext = LoggerContext.getContext(false);
// loggerContext.setConfigLocation(path.toUri());
// }
//
// /**
// * Auxiliary method to change the log level.
// *
// * @param logLevel
// * The log level to set.
// *
// * @return
// * A ResponseContext containing the result of the command.
// */
// public static ResponseContext changeLogLevel(String logLevel) {
// ResponseContext responseContext = new ResponseContext();
// responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
// LoggerContext loggerContext = LoggerContext.getContext(false);
// Configuration configuration = loggerContext.getConfiguration();
// LoggerConfig rootLogger = configuration.getRootLogger();
// if (rootLogger != null) {
// switch (StandardLevel.getStandardLevel(Level.toLevel(logLevel, Level.INFO).intLevel())) {
// case ERROR:
// rootLogger.setLevel(Level.ERROR);
// responseContext.setResponse("Log level changed to ERROR");
// break;
// case WARN:
// rootLogger.setLevel(Level.WARN);
// responseContext.setResponse("Log level changed to WARN");
// break;
// case INFO:
// rootLogger.setLevel(Level.INFO);
// responseContext.setResponse("Log level changed to INFO");
// break;
// case DEBUG:
// rootLogger.setLevel(Level.DEBUG);
// responseContext.setResponse("Log level changed to DEBUG");
// break;
// case OFF:
// rootLogger.setLevel(Level.OFF);
// responseContext.setResponse("Logging switched off");
// break;
// default:
// responseContext.setResponse("Log level unchanged, unsupported level: " + logLevel);
// }
// loggerContext.updateLoggers();
// } else {
// responseContext.setResponse("Unable to change log level, no ROOT logger found...");
// responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_INTERNAL_ERROR));
// }
// return responseContext;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
// Path: src/main/java/net/technolords/micro/command/LogCommand.java
import java.util.Map;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.log.LogManager;
import net.technolords.micro.model.ResponseContext;
package net.technolords.micro.command;
public class LogCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(LogCommand.class);
/**
* Auxiliary method to get the id associated with this command.
*
* @return
* The id associated with the command.
*/
@Override
public String getId() {
return Command.LOG;
}
/**
* Auxiliary method that executes the log command. For consistency this class is kept, but in reality it
* is delegated to the LogManager which consolidates all logic (as well as the required classes) with the
* underlying logging framework (other than the logging facade, i.e. SLF4J).
*
* @param exchange
* The Camel Exchange associated with the log command.
*
* @return
* The result of the log command.
*/
@Override | public ResponseContext executeCommand(Exchange exchange) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/command/LogCommand.java | // Path: src/main/java/net/technolords/micro/log/LogManager.java
// public class LogManager {
// private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
//
// /**
// * Auxiliary method to (re)initialize the logging. This method is typically called from
// * the PropertiesManager when a external log4j2 configuration is provided, while at the
// * same time no CLI parameter was given.
// *
// * Setting the new config location is enough, as it will trigger a reconfigure
// * automatically.
// *
// * @param pathToLogConfiguration
// * A path to the external log configuration file.
// */
// public static void initializeLogging(String pathToLogConfiguration) {
// Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
// LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
// LoggerContext loggerContext = LoggerContext.getContext(false);
// loggerContext.setConfigLocation(path.toUri());
// }
//
// /**
// * Auxiliary method to change the log level.
// *
// * @param logLevel
// * The log level to set.
// *
// * @return
// * A ResponseContext containing the result of the command.
// */
// public static ResponseContext changeLogLevel(String logLevel) {
// ResponseContext responseContext = new ResponseContext();
// responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
// LoggerContext loggerContext = LoggerContext.getContext(false);
// Configuration configuration = loggerContext.getConfiguration();
// LoggerConfig rootLogger = configuration.getRootLogger();
// if (rootLogger != null) {
// switch (StandardLevel.getStandardLevel(Level.toLevel(logLevel, Level.INFO).intLevel())) {
// case ERROR:
// rootLogger.setLevel(Level.ERROR);
// responseContext.setResponse("Log level changed to ERROR");
// break;
// case WARN:
// rootLogger.setLevel(Level.WARN);
// responseContext.setResponse("Log level changed to WARN");
// break;
// case INFO:
// rootLogger.setLevel(Level.INFO);
// responseContext.setResponse("Log level changed to INFO");
// break;
// case DEBUG:
// rootLogger.setLevel(Level.DEBUG);
// responseContext.setResponse("Log level changed to DEBUG");
// break;
// case OFF:
// rootLogger.setLevel(Level.OFF);
// responseContext.setResponse("Logging switched off");
// break;
// default:
// responseContext.setResponse("Log level unchanged, unsupported level: " + logLevel);
// }
// loggerContext.updateLoggers();
// } else {
// responseContext.setResponse("Unable to change log level, no ROOT logger found...");
// responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_INTERNAL_ERROR));
// }
// return responseContext;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
| import java.util.Map;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.log.LogManager;
import net.technolords.micro.model.ResponseContext; | package net.technolords.micro.command;
public class LogCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(LogCommand.class);
/**
* Auxiliary method to get the id associated with this command.
*
* @return
* The id associated with the command.
*/
@Override
public String getId() {
return Command.LOG;
}
/**
* Auxiliary method that executes the log command. For consistency this class is kept, but in reality it
* is delegated to the LogManager which consolidates all logic (as well as the required classes) with the
* underlying logging framework (other than the logging facade, i.e. SLF4J).
*
* @param exchange
* The Camel Exchange associated with the log command.
*
* @return
* The result of the log command.
*/
@Override
public ResponseContext executeCommand(Exchange exchange) {
Map<String, Object> commands = exchange.getIn().getHeaders();
String logLevel = (String) commands.get(Command.LOG);
LOGGER.debug("Log command called, with log level {}", logLevel); | // Path: src/main/java/net/technolords/micro/log/LogManager.java
// public class LogManager {
// private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
//
// /**
// * Auxiliary method to (re)initialize the logging. This method is typically called from
// * the PropertiesManager when a external log4j2 configuration is provided, while at the
// * same time no CLI parameter was given.
// *
// * Setting the new config location is enough, as it will trigger a reconfigure
// * automatically.
// *
// * @param pathToLogConfiguration
// * A path to the external log configuration file.
// */
// public static void initializeLogging(String pathToLogConfiguration) {
// Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
// LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
// LoggerContext loggerContext = LoggerContext.getContext(false);
// loggerContext.setConfigLocation(path.toUri());
// }
//
// /**
// * Auxiliary method to change the log level.
// *
// * @param logLevel
// * The log level to set.
// *
// * @return
// * A ResponseContext containing the result of the command.
// */
// public static ResponseContext changeLogLevel(String logLevel) {
// ResponseContext responseContext = new ResponseContext();
// responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
// LoggerContext loggerContext = LoggerContext.getContext(false);
// Configuration configuration = loggerContext.getConfiguration();
// LoggerConfig rootLogger = configuration.getRootLogger();
// if (rootLogger != null) {
// switch (StandardLevel.getStandardLevel(Level.toLevel(logLevel, Level.INFO).intLevel())) {
// case ERROR:
// rootLogger.setLevel(Level.ERROR);
// responseContext.setResponse("Log level changed to ERROR");
// break;
// case WARN:
// rootLogger.setLevel(Level.WARN);
// responseContext.setResponse("Log level changed to WARN");
// break;
// case INFO:
// rootLogger.setLevel(Level.INFO);
// responseContext.setResponse("Log level changed to INFO");
// break;
// case DEBUG:
// rootLogger.setLevel(Level.DEBUG);
// responseContext.setResponse("Log level changed to DEBUG");
// break;
// case OFF:
// rootLogger.setLevel(Level.OFF);
// responseContext.setResponse("Logging switched off");
// break;
// default:
// responseContext.setResponse("Log level unchanged, unsupported level: " + logLevel);
// }
// loggerContext.updateLoggers();
// } else {
// responseContext.setResponse("Unable to change log level, no ROOT logger found...");
// responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_INTERNAL_ERROR));
// }
// return responseContext;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
// Path: src/main/java/net/technolords/micro/command/LogCommand.java
import java.util.Map;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.log.LogManager;
import net.technolords.micro.model.ResponseContext;
package net.technolords.micro.command;
public class LogCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(LogCommand.class);
/**
* Auxiliary method to get the id associated with this command.
*
* @return
* The id associated with the command.
*/
@Override
public String getId() {
return Command.LOG;
}
/**
* Auxiliary method that executes the log command. For consistency this class is kept, but in reality it
* is delegated to the LogManager which consolidates all logic (as well as the required classes) with the
* underlying logging framework (other than the logging facade, i.e. SLF4J).
*
* @param exchange
* The Camel Exchange associated with the log command.
*
* @return
* The result of the log command.
*/
@Override
public ResponseContext executeCommand(Exchange exchange) {
Map<String, Object> commands = exchange.getIn().getHeaders();
String logLevel = (String) commands.get(Command.LOG);
LOGGER.debug("Log command called, with log level {}", logLevel); | return LogManager.changeLogLevel(logLevel); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/log/LogManager.java | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
| import java.net.HttpURLConnection;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.spi.StandardLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext; | package net.technolords.micro.log;
/**
* This class has the responsibility to interface with the logging library, which is currently
* log4j-2. All log4j-2 dependencies and classes are used here solely, which limits the impact in
* case things change.
*
* This class supports operations from two angles:
* - startup time, where end user overrides default configuration (caller class: PropertiesManager)
* - run time, where end-user changes log level (caller class: LogCommand)
*/
public class LogManager {
private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
/**
* Auxiliary method to (re)initialize the logging. This method is typically called from
* the PropertiesManager when a external log4j2 configuration is provided, while at the
* same time no CLI parameter was given.
*
* Setting the new config location is enough, as it will trigger a reconfigure
* automatically.
*
* @param pathToLogConfiguration
* A path to the external log configuration file.
*/
public static void initializeLogging(String pathToLogConfiguration) {
Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
LoggerContext loggerContext = LoggerContext.getContext(false);
loggerContext.setConfigLocation(path.toUri());
}
/**
* Auxiliary method to change the log level.
*
* @param logLevel
* The log level to set.
*
* @return
* A ResponseContext containing the result of the command.
*/ | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
// Path: src/main/java/net/technolords/micro/log/LogManager.java
import java.net.HttpURLConnection;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.spi.StandardLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext;
package net.technolords.micro.log;
/**
* This class has the responsibility to interface with the logging library, which is currently
* log4j-2. All log4j-2 dependencies and classes are used here solely, which limits the impact in
* case things change.
*
* This class supports operations from two angles:
* - startup time, where end user overrides default configuration (caller class: PropertiesManager)
* - run time, where end-user changes log level (caller class: LogCommand)
*/
public class LogManager {
private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
/**
* Auxiliary method to (re)initialize the logging. This method is typically called from
* the PropertiesManager when a external log4j2 configuration is provided, while at the
* same time no CLI parameter was given.
*
* Setting the new config location is enough, as it will trigger a reconfigure
* automatically.
*
* @param pathToLogConfiguration
* A path to the external log configuration file.
*/
public static void initializeLogging(String pathToLogConfiguration) {
Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
LoggerContext loggerContext = LoggerContext.getContext(false);
loggerContext.setConfigLocation(path.toUri());
}
/**
* Auxiliary method to change the log level.
*
* @param logLevel
* The log level to set.
*
* @return
* A ResponseContext containing the result of the command.
*/ | public static ResponseContext changeLogLevel(String logLevel) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/registry/consul/ConsulRequestFactory.java | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
| import java.util.List;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration; | package net.technolords.micro.registry.consul;
public class ConsulRequestFactory {
private static final String API_SERVICE_REGISTER = "/v1/agent/service/register";
private static final String API_SERVICE_DEREGISTER = "/v1/agent/service/deregister/";
/**
* A factory for a HttpPut method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPut
*
* @return
* The generated HttpPut
*/ | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
// Path: src/main/java/net/technolords/micro/registry/consul/ConsulRequestFactory.java
import java.util.List;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration;
package net.technolords.micro.registry.consul;
public class ConsulRequestFactory {
private static final String API_SERVICE_REGISTER = "/v1/agent/service/register";
private static final String API_SERVICE_DEREGISTER = "/v1/agent/service/deregister/";
/**
* A factory for a HttpPut method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPut
*
* @return
* The generated HttpPut
*/ | public static HttpEntityEnclosingRequestBase createRegisterRequest(Registration registration, List<Configuration> configurations) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/registry/consul/ConsulRequestFactory.java | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
| import java.util.List;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration; | package net.technolords.micro.registry.consul;
public class ConsulRequestFactory {
private static final String API_SERVICE_REGISTER = "/v1/agent/service/register";
private static final String API_SERVICE_DEREGISTER = "/v1/agent/service/deregister/";
/**
* A factory for a HttpPut method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPut
*
* @return
* The generated HttpPut
*/ | // Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
// public class Configuration {
// private String type;
// private String url;
// private QueryGroups queryGroups;
// private SimpleResource simpleResource;
// private ResourceGroups resourceGroups;
// private NamespaceList namespaceList;
// private Map<String, String> cachedNamespaceMapping;
// private Pattern pattern;
//
// @XmlAttribute(name = "type")
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// @XmlAttribute(name = "url")
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @XmlElement (name = "query-groups")
// public QueryGroups getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(QueryGroups queryGroups) {
// this.queryGroups = queryGroups;
// }
//
// @XmlElement(name = "resource")
// public SimpleResource getSimpleResource() {
// return simpleResource;
// }
//
// public void setSimpleResource(SimpleResource simpleResource) {
// this.simpleResource = simpleResource;
// }
//
// @XmlElement(name = "resource-groups")
// public ResourceGroups getResourceGroups() {
// return resourceGroups;
// }
//
// public void setResourceGroups(ResourceGroups resourceGroups) {
// this.resourceGroups = resourceGroups;
// }
//
// @XmlElement(name = "namespaces")
// public NamespaceList getNamespaceList() {
// return namespaceList;
// }
//
// public void setNamespaceList(NamespaceList namespaceList) {
// this.namespaceList = namespaceList;
// }
//
// @XmlTransient
// public Map<String, String> getCachedNamespaceMapping() {
// return cachedNamespaceMapping;
// }
//
// public void setCachedNamespaceMapping(Map<String, String> cachedNamespaceMapping) {
// this.cachedNamespaceMapping = cachedNamespaceMapping;
// }
//
// @XmlTransient
// public Pattern getPattern() {
// return pattern;
// }
//
// public void setPattern(Pattern pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null) {
// return false;
// }
// if(!(obj instanceof Configuration)) {
// return false;
// }
// Configuration ref = (Configuration) obj;
// return (Objects.equals(this.getUrl(), ref.getUrl())
// && Objects.equals(this.getType(), ref.getType())
// && Objects.equals(this.getSimpleResource(), ref.getSimpleResource())
// );
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/registration/Registration.java
// public class Registration {
// private Registrar registrar;
// private String address;
// private int port;
// private Service service;
//
// @XmlEnum
// public enum Registrar { CONSUL, EUREKA }
//
// @XmlAttribute (name = "registrar", required = true)
// public Registrar getRegistrar() {
// return registrar;
// }
//
// public void setRegistrar(Registrar registrar) {
// this.registrar = registrar;
// }
//
// @XmlAttribute (name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @XmlAttribute (name = "port")
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// @XmlElement (name = "service")
// public Service getService() {
// return service;
// }
//
// public void setService(Service service) {
// this.service = service;
// }
// }
// Path: src/main/java/net/technolords/micro/registry/consul/ConsulRequestFactory.java
import java.util.List;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import net.technolords.micro.model.jaxb.Configuration;
import net.technolords.micro.model.jaxb.registration.Registration;
package net.technolords.micro.registry.consul;
public class ConsulRequestFactory {
private static final String API_SERVICE_REGISTER = "/v1/agent/service/register";
private static final String API_SERVICE_DEREGISTER = "/v1/agent/service/deregister/";
/**
* A factory for a HttpPut method, suitable to register the service.
*
* @param registration
* The Registration reference associated with the HttpPut
*
* @return
* The generated HttpPut
*/ | public static HttpEntityEnclosingRequestBase createRegisterRequest(Registration registration, List<Configuration> configurations) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/model/jaxb/Configuration.java | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
| import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource; | package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url; | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource;
package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url; | private QueryGroups queryGroups; |
Technolords/microservice-mock | src/main/java/net/technolords/micro/model/jaxb/Configuration.java | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
| import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource; | package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url;
private QueryGroups queryGroups; | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource;
package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url;
private QueryGroups queryGroups; | private SimpleResource simpleResource; |
Technolords/microservice-mock | src/main/java/net/technolords/micro/model/jaxb/Configuration.java | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
| import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource; | package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url;
private QueryGroups queryGroups;
private SimpleResource simpleResource; | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource;
package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url;
private QueryGroups queryGroups;
private SimpleResource simpleResource; | private ResourceGroups resourceGroups; |
Technolords/microservice-mock | src/main/java/net/technolords/micro/model/jaxb/Configuration.java | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
| import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource; | package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url;
private QueryGroups queryGroups;
private SimpleResource simpleResource;
private ResourceGroups resourceGroups; | // Path: src/main/java/net/technolords/micro/model/jaxb/namespace/NamespaceList.java
// public class NamespaceList {
// private List<NamespaceConfig> namespaces;
//
// @XmlElement(name = "namespace")
// public List<NamespaceConfig> getNamespaces() {
// return namespaces;
// }
//
// public void setNamespaces(List<NamespaceConfig> namespaces) {
// this.namespaces = namespaces;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/query/QueryGroups.java
// public class QueryGroups {
// private List<QueryGroup> queryGroups;
//
// public QueryGroups() {
// this.queryGroups = new ArrayList<>();
// }
//
// @XmlElement (name = "query-group")
// public List<QueryGroup> getQueryGroups() {
// return queryGroups;
// }
//
// public void setQueryGroups(List<QueryGroup> queryGroups) {
// this.queryGroups = queryGroups;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/ResourceGroups.java
// public class ResourceGroups {
// private List<ResourceGroup> resourceGroup;
//
// public ResourceGroups() {
// this.resourceGroup = new ArrayList<>();
// }
//
// @XmlElement(name = "resource-group")
// public List<ResourceGroup> getResourceGroup() {
// return resourceGroup;
// }
//
// public void setResourceGroup(List<ResourceGroup> resourceGroup) {
// this.resourceGroup = resourceGroup;
// }
// }
//
// Path: src/main/java/net/technolords/micro/model/jaxb/resource/SimpleResource.java
// public class SimpleResource {
// private String resource;
// private String cachedData;
// private int delay;
// private String errorCode;
// private int errorRate;
// private String contentType;
//
// @XmlValue
// public String getResource() {
// return resource;
// }
//
// public void setResource(String resource) {
// this.resource = resource;
// }
//
// @XmlTransient
// public String getCachedData() {
// return cachedData;
// }
//
// public void setCachedData(String cachedData) {
// this.cachedData = cachedData;
// }
//
// @XmlAttribute(name = "delay")
// public int getDelay() {
// return delay;
// }
//
// public void setDelay(int delay) {
// this.delay = delay;
// }
//
// @XmlAttribute(name = "error-code")
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// @XmlAttribute(name = "error-rate")
// public int getErrorRate() {
// return errorRate;
// }
//
// public void setErrorRate(int errorRate) {
// this.errorRate = errorRate;
// }
//
// @XmlAttribute(name = "content-type")
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (!(obj instanceof SimpleResource)) {
// return false;
// }
// SimpleResource ref = (SimpleResource) obj;
// return (Objects.equals(this.getContentType(), ref.getContentType())
// && Objects.equals(this.getErrorCode(), ref.getErrorCode())
// && Objects.equals(this.getResource(), ref.getResource())
// );
// }
// }
// Path: src/main/java/net/technolords/micro/model/jaxb/Configuration.java
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import net.technolords.micro.model.jaxb.namespace.NamespaceList;
import net.technolords.micro.model.jaxb.query.QueryGroups;
import net.technolords.micro.model.jaxb.resource.ResourceGroups;
import net.technolords.micro.model.jaxb.resource.SimpleResource;
package net.technolords.micro.model.jaxb;
public class Configuration {
private String type;
private String url;
private QueryGroups queryGroups;
private SimpleResource simpleResource;
private ResourceGroups resourceGroups; | private NamespaceList namespaceList; |
Technolords/microservice-mock | src/main/java/net/technolords/micro/camel/listener/MockMainListener.java | // Path: src/main/java/net/technolords/micro/camel/lifecycle/MainLifecycleStrategy.java
// public class MainLifecycleStrategy extends DefaultManagementLifecycleStrategy {
// private final Logger LOGGER = LoggerFactory.getLogger(getClass());
//
// public MainLifecycleStrategy(CamelContext camelContext) {
// super(camelContext);
// }
//
// @Override
// public void onContextStart(CamelContext camelContext) throws VetoCamelContextStartException {
// LOGGER.debug("onContextStart called...");
// MockRegistry.findRegistrationManager().registerService();
// super.onContextStart(camelContext);
// }
//
// @Override
// public void onContextStop(CamelContext context) {
// LOGGER.debug("onContextStop called...");
// MockRegistry.findRegistrationManager().deregisterService();
// super.onContextStop(getCamelContext());
// }
// }
| import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.main.MainListenerSupport;
import org.apache.camel.spi.ShutdownStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.camel.lifecycle.MainLifecycleStrategy; | package net.technolords.micro.camel.listener;
public class MockMainListener extends MainListenerSupport {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
@Override
public void configure(CamelContext camelContext) {
LOGGER.debug("Configure called...");
this.updateShutdownStrategy(camelContext); | // Path: src/main/java/net/technolords/micro/camel/lifecycle/MainLifecycleStrategy.java
// public class MainLifecycleStrategy extends DefaultManagementLifecycleStrategy {
// private final Logger LOGGER = LoggerFactory.getLogger(getClass());
//
// public MainLifecycleStrategy(CamelContext camelContext) {
// super(camelContext);
// }
//
// @Override
// public void onContextStart(CamelContext camelContext) throws VetoCamelContextStartException {
// LOGGER.debug("onContextStart called...");
// MockRegistry.findRegistrationManager().registerService();
// super.onContextStart(camelContext);
// }
//
// @Override
// public void onContextStop(CamelContext context) {
// LOGGER.debug("onContextStop called...");
// MockRegistry.findRegistrationManager().deregisterService();
// super.onContextStop(getCamelContext());
// }
// }
// Path: src/main/java/net/technolords/micro/camel/listener/MockMainListener.java
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.main.MainListenerSupport;
import org.apache.camel.spi.ShutdownStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.camel.lifecycle.MainLifecycleStrategy;
package net.technolords.micro.camel.listener;
public class MockMainListener extends MainListenerSupport {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
@Override
public void configure(CamelContext camelContext) {
LOGGER.debug("Configure called...");
this.updateShutdownStrategy(camelContext); | camelContext.addLifecycleStrategy(new MainLifecycleStrategy(camelContext)); |
Technolords/microservice-mock | src/main/java/net/technolords/micro/command/StopCommand.java | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
| import java.net.HttpURLConnection;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext; | package net.technolords.micro.command;
public class StopCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(StopCommand.class);
/**
* Auxiliary method to get the id associated with this command.
*
* @return
* The id associated with the command.
*/
@Override
public String getId() {
return Command.STOP;
}
/**
* Auxiliary method that stops the Main execution. This is achieved by calling stop on the CamelContext
* which is associated with the Main.
*
* @param exchange
* The exchange associated with the stop command.
*
* @return
* The result of the stop command (unlikely to be received, as the execution is terminating).
*/
@Override | // Path: src/main/java/net/technolords/micro/model/ResponseContext.java
// public class ResponseContext {
// public static final String JSON_CONTENT_TYPE = "application/json";
// public static final String XML_CONTENT_TYPE = "application/xml";
// public static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain";
// public static final String HTML_CONTENT_TYPE = "text/html";
// public static final String DEFAULT_CONTENT_TYPE = JSON_CONTENT_TYPE;
// private String response;
// private String errorCode;
// private String contentType = DEFAULT_CONTENT_TYPE;
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
//
// public String getErrorCode() {
// return errorCode;
// }
//
// public void setErrorCode(String errorCode) {
// this.errorCode = errorCode;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public void setContentType(String contentType) {
// this.contentType = contentType;
// }
// }
// Path: src/main/java/net/technolords/micro/command/StopCommand.java
import java.net.HttpURLConnection;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.model.ResponseContext;
package net.technolords.micro.command;
public class StopCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(StopCommand.class);
/**
* Auxiliary method to get the id associated with this command.
*
* @return
* The id associated with the command.
*/
@Override
public String getId() {
return Command.STOP;
}
/**
* Auxiliary method that stops the Main execution. This is achieved by calling stop on the CamelContext
* which is associated with the Main.
*
* @param exchange
* The exchange associated with the stop command.
*
* @return
* The result of the stop command (unlikely to be received, as the execution is terminating).
*/
@Override | public ResponseContext executeCommand(Exchange exchange) { |
Technolords/microservice-mock | src/main/java/net/technolords/micro/config/PropertiesManager.java | // Path: src/main/java/net/technolords/micro/log/LogManager.java
// public class LogManager {
// private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
//
// /**
// * Auxiliary method to (re)initialize the logging. This method is typically called from
// * the PropertiesManager when a external log4j2 configuration is provided, while at the
// * same time no CLI parameter was given.
// *
// * Setting the new config location is enough, as it will trigger a reconfigure
// * automatically.
// *
// * @param pathToLogConfiguration
// * A path to the external log configuration file.
// */
// public static void initializeLogging(String pathToLogConfiguration) {
// Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
// LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
// LoggerContext loggerContext = LoggerContext.getContext(false);
// loggerContext.setConfigLocation(path.toUri());
// }
//
// /**
// * Auxiliary method to change the log level.
// *
// * @param logLevel
// * The log level to set.
// *
// * @return
// * A ResponseContext containing the result of the command.
// */
// public static ResponseContext changeLogLevel(String logLevel) {
// ResponseContext responseContext = new ResponseContext();
// responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
// LoggerContext loggerContext = LoggerContext.getContext(false);
// Configuration configuration = loggerContext.getConfiguration();
// LoggerConfig rootLogger = configuration.getRootLogger();
// if (rootLogger != null) {
// switch (StandardLevel.getStandardLevel(Level.toLevel(logLevel, Level.INFO).intLevel())) {
// case ERROR:
// rootLogger.setLevel(Level.ERROR);
// responseContext.setResponse("Log level changed to ERROR");
// break;
// case WARN:
// rootLogger.setLevel(Level.WARN);
// responseContext.setResponse("Log level changed to WARN");
// break;
// case INFO:
// rootLogger.setLevel(Level.INFO);
// responseContext.setResponse("Log level changed to INFO");
// break;
// case DEBUG:
// rootLogger.setLevel(Level.DEBUG);
// responseContext.setResponse("Log level changed to DEBUG");
// break;
// case OFF:
// rootLogger.setLevel(Level.OFF);
// responseContext.setResponse("Logging switched off");
// break;
// default:
// responseContext.setResponse("Log level unchanged, unsupported level: " + logLevel);
// }
// loggerContext.updateLoggers();
// } else {
// responseContext.setResponse("Unable to change log level, no ROOT logger found...");
// responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_INTERNAL_ERROR));
// }
// return responseContext;
// }
// }
| import static java.nio.file.StandardOpenOption.READ;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.log.LogManager; | }
for (Object key : properties.keySet()) {
LOGGER.debug("Property: {} -> value: {}", key, properties.get(key));
}
return properties;
}
/**
* Auxiliary method to load the properties.
*
* @param pathToPropertiesFile
* The path to the properties file.
*
* @return
* The properties.
*/
private static Properties loadProperties(String pathToPropertiesFile) {
Properties properties = new Properties();
try {
if (pathToPropertiesFile == null) {
return properties;
}
Path path = FileSystems.getDefault().getPath(pathToPropertiesFile);
properties.load(Files.newInputStream(path, READ));
if (properties.get(PROP_LOG_CONFIG) != null) {
// Note that at this point, putting this property back as system property is pointless,
// as the JVM is already started. When there is no CLI property defined proceed by
// delegation towards the LogManager.
if (System.getProperty(PROP_LOG_CONFIG) == null) {
LOGGER.trace("log4j not as system property, do invoke builder"); | // Path: src/main/java/net/technolords/micro/log/LogManager.java
// public class LogManager {
// private static final Logger LOGGER = LoggerFactory.getLogger(LogManager.class);
//
// /**
// * Auxiliary method to (re)initialize the logging. This method is typically called from
// * the PropertiesManager when a external log4j2 configuration is provided, while at the
// * same time no CLI parameter was given.
// *
// * Setting the new config location is enough, as it will trigger a reconfigure
// * automatically.
// *
// * @param pathToLogConfiguration
// * A path to the external log configuration file.
// */
// public static void initializeLogging(String pathToLogConfiguration) {
// Path path = FileSystems.getDefault().getPath(pathToLogConfiguration);
// LOGGER.trace("Path to log configuration: {} -> file exists: {}", pathToLogConfiguration, Files.exists(path));
// LoggerContext loggerContext = LoggerContext.getContext(false);
// loggerContext.setConfigLocation(path.toUri());
// }
//
// /**
// * Auxiliary method to change the log level.
// *
// * @param logLevel
// * The log level to set.
// *
// * @return
// * A ResponseContext containing the result of the command.
// */
// public static ResponseContext changeLogLevel(String logLevel) {
// ResponseContext responseContext = new ResponseContext();
// responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
// LoggerContext loggerContext = LoggerContext.getContext(false);
// Configuration configuration = loggerContext.getConfiguration();
// LoggerConfig rootLogger = configuration.getRootLogger();
// if (rootLogger != null) {
// switch (StandardLevel.getStandardLevel(Level.toLevel(logLevel, Level.INFO).intLevel())) {
// case ERROR:
// rootLogger.setLevel(Level.ERROR);
// responseContext.setResponse("Log level changed to ERROR");
// break;
// case WARN:
// rootLogger.setLevel(Level.WARN);
// responseContext.setResponse("Log level changed to WARN");
// break;
// case INFO:
// rootLogger.setLevel(Level.INFO);
// responseContext.setResponse("Log level changed to INFO");
// break;
// case DEBUG:
// rootLogger.setLevel(Level.DEBUG);
// responseContext.setResponse("Log level changed to DEBUG");
// break;
// case OFF:
// rootLogger.setLevel(Level.OFF);
// responseContext.setResponse("Logging switched off");
// break;
// default:
// responseContext.setResponse("Log level unchanged, unsupported level: " + logLevel);
// }
// loggerContext.updateLoggers();
// } else {
// responseContext.setResponse("Unable to change log level, no ROOT logger found...");
// responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_INTERNAL_ERROR));
// }
// return responseContext;
// }
// }
// Path: src/main/java/net/technolords/micro/config/PropertiesManager.java
import static java.nio.file.StandardOpenOption.READ;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.log.LogManager;
}
for (Object key : properties.keySet()) {
LOGGER.debug("Property: {} -> value: {}", key, properties.get(key));
}
return properties;
}
/**
* Auxiliary method to load the properties.
*
* @param pathToPropertiesFile
* The path to the properties file.
*
* @return
* The properties.
*/
private static Properties loadProperties(String pathToPropertiesFile) {
Properties properties = new Properties();
try {
if (pathToPropertiesFile == null) {
return properties;
}
Path path = FileSystems.getDefault().getPath(pathToPropertiesFile);
properties.load(Files.newInputStream(path, READ));
if (properties.get(PROP_LOG_CONFIG) != null) {
// Note that at this point, putting this property back as system property is pointless,
// as the JVM is already started. When there is no CLI property defined proceed by
// delegation towards the LogManager.
if (System.getProperty(PROP_LOG_CONFIG) == null) {
LOGGER.trace("log4j not as system property, do invoke builder"); | LogManager.initializeLogging((String) properties.get(PROP_LOG_CONFIG)); |
javasoze/clue | src/main/java/io/dashbase/clue/commands/HelpCommand.java | // Path: src/main/java/io/dashbase/clue/ClueContext.java
// public class ClueContext {
// protected final CommandRegistry registry = new CommandRegistry();
//
// private final boolean interactiveMode;
//
// public ClueContext(CommandRegistrar commandRegistrar, boolean interactiveMode) {
// commandRegistrar.registerCommands(this);
// this.interactiveMode = interactiveMode;
// }
//
// public void registerCommand(ClueCommand cmd){
// String cmdName = cmd.getName();
// if (registry.exists(cmdName)){
// throw new IllegalArgumentException(cmdName+" exists!");
// }
// registry.registerCommand(cmd);
// }
//
// public boolean isReadOnlyMode() {
// return registry.isReadonly();
// }
//
// public boolean isInteractiveMode(){
// return interactiveMode;
// }
//
// public Optional<ClueCommand> getCommand(String cmd){
// return registry.getCommand(cmd);
// }
//
// public CommandRegistry getCommandRegistry(){
// return registry;
// }
//
// public void shutdown() throws Exception{
// }
// }
| import java.io.PrintStream;
import java.util.Collection;
import io.dashbase.clue.ClueContext;
import net.sourceforge.argparse4j.inf.Namespace; | package io.dashbase.clue.commands;
@Readonly
public class HelpCommand extends ClueCommand {
public static final String CMD_NAME = "help"; | // Path: src/main/java/io/dashbase/clue/ClueContext.java
// public class ClueContext {
// protected final CommandRegistry registry = new CommandRegistry();
//
// private final boolean interactiveMode;
//
// public ClueContext(CommandRegistrar commandRegistrar, boolean interactiveMode) {
// commandRegistrar.registerCommands(this);
// this.interactiveMode = interactiveMode;
// }
//
// public void registerCommand(ClueCommand cmd){
// String cmdName = cmd.getName();
// if (registry.exists(cmdName)){
// throw new IllegalArgumentException(cmdName+" exists!");
// }
// registry.registerCommand(cmd);
// }
//
// public boolean isReadOnlyMode() {
// return registry.isReadonly();
// }
//
// public boolean isInteractiveMode(){
// return interactiveMode;
// }
//
// public Optional<ClueCommand> getCommand(String cmd){
// return registry.getCommand(cmd);
// }
//
// public CommandRegistry getCommandRegistry(){
// return registry;
// }
//
// public void shutdown() throws Exception{
// }
// }
// Path: src/main/java/io/dashbase/clue/commands/HelpCommand.java
import java.io.PrintStream;
import java.util.Collection;
import io.dashbase.clue.ClueContext;
import net.sourceforge.argparse4j.inf.Namespace;
package io.dashbase.clue.commands;
@Readonly
public class HelpCommand extends ClueCommand {
public static final String CMD_NAME = "help"; | public HelpCommand(ClueContext ctx) { |
javasoze/clue | src/main/java/io/dashbase/clue/commands/NormsCommand.java | // Path: src/main/java/io/dashbase/clue/LuceneContext.java
// public class LuceneContext extends ClueContext {
// private final IndexReaderFactory readerFactory;
//
// private IndexWriter writer;
// private final Directory directory;
// private final IndexWriterConfig writerConfig;
// private final QueryBuilder queryBuilder;
// private final AnalyzerFactory analyzerFactory;
// private final BytesRefDisplay termBytesRefDisplay;
// private final BytesRefDisplay payloadBytesRefDisplay;
//
// public LuceneContext(String dir, ClueAppConfiguration config, boolean interactiveMode)
// throws Exception {
// super(config.commandRegistrar, interactiveMode);
// this.directory = config.dirBuilder.build(dir);
// this.analyzerFactory = config.analyzerFactory;
// this.readerFactory = config.indexReaderFactory;
// this.readerFactory.initialize(directory);
// this.queryBuilder = config.queryBuilder;
// this.queryBuilder.initialize("contents", analyzerFactory.forQuery());
// this.writerConfig = new IndexWriterConfig(new StandardAnalyzer());
// this.termBytesRefDisplay = new StringBytesRefDisplay();
// this.payloadBytesRefDisplay = new StringBytesRefDisplay();
// this.writer = null;
// }
//
//
// public IndexReader getIndexReader(){
// return readerFactory.getIndexReader();
// }
//
// public IndexSearcher getIndexSearcher() {
// return new IndexSearcher(getIndexReader());
// }
//
// public IndexWriter getIndexWriter(){
// if (registry.isReadonly()) return null;
// if (writer == null) {
// try {
// writer = new IndexWriter(directory, writerConfig);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return writer;
// }
//
// Collection<String> fieldNames() {
// LinkedList<String> fieldNames = new LinkedList<>();
// for (LeafReaderContext context : getIndexReader().leaves()) {
// LeafReader reader = context.reader();
// for(FieldInfo info : reader.getFieldInfos()) {
// fieldNames.add(info.name);
// }
// }
// return fieldNames;
// }
//
// public QueryBuilder getQueryBuilder() {
// return queryBuilder;
// }
//
// public Analyzer getAnalyzerQuery() {
// return analyzerFactory.forQuery();
// }
//
// public BytesRefDisplay getTermBytesRefDisplay() {
// return termBytesRefDisplay;
// }
//
// public BytesRefDisplay getPayloadBytesRefDisplay() {
// return payloadBytesRefDisplay;
// }
//
// public Directory getDirectory() {
// return directory;
// }
//
// public void setReadOnlyMode(boolean readOnlyMode) {
// this.registry.setReadonly(readOnlyMode);
// if (writer != null) {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// writer = null;
// }
// }
//
// public void refreshReader() throws Exception {
// readerFactory.refreshReader();
// }
//
// @Override
// public void shutdown() throws Exception{
// try {
// readerFactory.shutdown();
// }
// finally{
// directory.close();
// if (writer != null) {
// writer.close();
// }
// }
// }
// }
| import io.dashbase.clue.LuceneContext;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.lucene.index.*;
import java.io.PrintStream;
import java.util.List; | package io.dashbase.clue.commands;
@Readonly
public class NormsCommand extends ClueCommand {
| // Path: src/main/java/io/dashbase/clue/LuceneContext.java
// public class LuceneContext extends ClueContext {
// private final IndexReaderFactory readerFactory;
//
// private IndexWriter writer;
// private final Directory directory;
// private final IndexWriterConfig writerConfig;
// private final QueryBuilder queryBuilder;
// private final AnalyzerFactory analyzerFactory;
// private final BytesRefDisplay termBytesRefDisplay;
// private final BytesRefDisplay payloadBytesRefDisplay;
//
// public LuceneContext(String dir, ClueAppConfiguration config, boolean interactiveMode)
// throws Exception {
// super(config.commandRegistrar, interactiveMode);
// this.directory = config.dirBuilder.build(dir);
// this.analyzerFactory = config.analyzerFactory;
// this.readerFactory = config.indexReaderFactory;
// this.readerFactory.initialize(directory);
// this.queryBuilder = config.queryBuilder;
// this.queryBuilder.initialize("contents", analyzerFactory.forQuery());
// this.writerConfig = new IndexWriterConfig(new StandardAnalyzer());
// this.termBytesRefDisplay = new StringBytesRefDisplay();
// this.payloadBytesRefDisplay = new StringBytesRefDisplay();
// this.writer = null;
// }
//
//
// public IndexReader getIndexReader(){
// return readerFactory.getIndexReader();
// }
//
// public IndexSearcher getIndexSearcher() {
// return new IndexSearcher(getIndexReader());
// }
//
// public IndexWriter getIndexWriter(){
// if (registry.isReadonly()) return null;
// if (writer == null) {
// try {
// writer = new IndexWriter(directory, writerConfig);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return writer;
// }
//
// Collection<String> fieldNames() {
// LinkedList<String> fieldNames = new LinkedList<>();
// for (LeafReaderContext context : getIndexReader().leaves()) {
// LeafReader reader = context.reader();
// for(FieldInfo info : reader.getFieldInfos()) {
// fieldNames.add(info.name);
// }
// }
// return fieldNames;
// }
//
// public QueryBuilder getQueryBuilder() {
// return queryBuilder;
// }
//
// public Analyzer getAnalyzerQuery() {
// return analyzerFactory.forQuery();
// }
//
// public BytesRefDisplay getTermBytesRefDisplay() {
// return termBytesRefDisplay;
// }
//
// public BytesRefDisplay getPayloadBytesRefDisplay() {
// return payloadBytesRefDisplay;
// }
//
// public Directory getDirectory() {
// return directory;
// }
//
// public void setReadOnlyMode(boolean readOnlyMode) {
// this.registry.setReadonly(readOnlyMode);
// if (writer != null) {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// writer = null;
// }
// }
//
// public void refreshReader() throws Exception {
// readerFactory.refreshReader();
// }
//
// @Override
// public void shutdown() throws Exception{
// try {
// readerFactory.shutdown();
// }
// finally{
// directory.close();
// if (writer != null) {
// writer.close();
// }
// }
// }
// }
// Path: src/main/java/io/dashbase/clue/commands/NormsCommand.java
import io.dashbase.clue.LuceneContext;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.lucene.index.*;
import java.io.PrintStream;
import java.util.List;
package io.dashbase.clue.commands;
@Readonly
public class NormsCommand extends ClueCommand {
| private final LuceneContext ctx; |
javasoze/clue | src/main/java/io/dashbase/clue/server/ClueWebConfiguration.java | // Path: src/main/java/io/dashbase/clue/ClueAppConfiguration.java
// public class ClueAppConfiguration {
// public QueryBuilder queryBuilder = new DefaultQueryBuilder();
// public DirectoryBuilder dirBuilder = new DefaultDirectoryBuilder();
// public IndexReaderFactory indexReaderFactory = new DefaultIndexReaderFactory();
// public AnalyzerFactory analyzerFactory = new DefaultAnalyzerFactory();
// public CommandRegistrar commandRegistrar = new DefaultCommandRegistrar();
//
// private static final String CLUE_CONF_FILE = "clue.yml";
// private static final ObjectMapper MAPPER = new ObjectMapper(new YAMLFactory());
//
// public static ClueAppConfiguration load() throws IOException {
// String confDirPath = System.getProperty("config.dir");
// if (confDirPath == null) {
// confDirPath = "config";
// }
// File confFile = new File(confDirPath, CLUE_CONF_FILE);
// if (confFile.exists() && confFile.isFile()) {
//
// System.out.println("using configuration file found at: " + confFile.getAbsolutePath());
// try (FileReader freader = new FileReader(confFile)) {
// return MAPPER.readValue(freader, ClueAppConfiguration.class);
// }
// } else {
// // use default
// System.out.println("no configuration found, using default configuration");
// return new ClueAppConfiguration();
// }
// }
// }
| import io.dashbase.clue.ClueAppConfiguration;
import io.dropwizard.Configuration;
import javax.validation.constraints.NotNull; | package io.dashbase.clue.server;
public class ClueWebConfiguration extends Configuration {
@NotNull
public String dir = null; | // Path: src/main/java/io/dashbase/clue/ClueAppConfiguration.java
// public class ClueAppConfiguration {
// public QueryBuilder queryBuilder = new DefaultQueryBuilder();
// public DirectoryBuilder dirBuilder = new DefaultDirectoryBuilder();
// public IndexReaderFactory indexReaderFactory = new DefaultIndexReaderFactory();
// public AnalyzerFactory analyzerFactory = new DefaultAnalyzerFactory();
// public CommandRegistrar commandRegistrar = new DefaultCommandRegistrar();
//
// private static final String CLUE_CONF_FILE = "clue.yml";
// private static final ObjectMapper MAPPER = new ObjectMapper(new YAMLFactory());
//
// public static ClueAppConfiguration load() throws IOException {
// String confDirPath = System.getProperty("config.dir");
// if (confDirPath == null) {
// confDirPath = "config";
// }
// File confFile = new File(confDirPath, CLUE_CONF_FILE);
// if (confFile.exists() && confFile.isFile()) {
//
// System.out.println("using configuration file found at: " + confFile.getAbsolutePath());
// try (FileReader freader = new FileReader(confFile)) {
// return MAPPER.readValue(freader, ClueAppConfiguration.class);
// }
// } else {
// // use default
// System.out.println("no configuration found, using default configuration");
// return new ClueAppConfiguration();
// }
// }
// }
// Path: src/main/java/io/dashbase/clue/server/ClueWebConfiguration.java
import io.dashbase.clue.ClueAppConfiguration;
import io.dropwizard.Configuration;
import javax.validation.constraints.NotNull;
package io.dashbase.clue.server;
public class ClueWebConfiguration extends Configuration {
@NotNull
public String dir = null; | public ClueAppConfiguration clue = new ClueAppConfiguration(); |
javasoze/clue | src/main/java/io/dashbase/clue/commands/PostingsCommand.java | // Path: src/main/java/io/dashbase/clue/LuceneContext.java
// public class LuceneContext extends ClueContext {
// private final IndexReaderFactory readerFactory;
//
// private IndexWriter writer;
// private final Directory directory;
// private final IndexWriterConfig writerConfig;
// private final QueryBuilder queryBuilder;
// private final AnalyzerFactory analyzerFactory;
// private final BytesRefDisplay termBytesRefDisplay;
// private final BytesRefDisplay payloadBytesRefDisplay;
//
// public LuceneContext(String dir, ClueAppConfiguration config, boolean interactiveMode)
// throws Exception {
// super(config.commandRegistrar, interactiveMode);
// this.directory = config.dirBuilder.build(dir);
// this.analyzerFactory = config.analyzerFactory;
// this.readerFactory = config.indexReaderFactory;
// this.readerFactory.initialize(directory);
// this.queryBuilder = config.queryBuilder;
// this.queryBuilder.initialize("contents", analyzerFactory.forQuery());
// this.writerConfig = new IndexWriterConfig(new StandardAnalyzer());
// this.termBytesRefDisplay = new StringBytesRefDisplay();
// this.payloadBytesRefDisplay = new StringBytesRefDisplay();
// this.writer = null;
// }
//
//
// public IndexReader getIndexReader(){
// return readerFactory.getIndexReader();
// }
//
// public IndexSearcher getIndexSearcher() {
// return new IndexSearcher(getIndexReader());
// }
//
// public IndexWriter getIndexWriter(){
// if (registry.isReadonly()) return null;
// if (writer == null) {
// try {
// writer = new IndexWriter(directory, writerConfig);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return writer;
// }
//
// Collection<String> fieldNames() {
// LinkedList<String> fieldNames = new LinkedList<>();
// for (LeafReaderContext context : getIndexReader().leaves()) {
// LeafReader reader = context.reader();
// for(FieldInfo info : reader.getFieldInfos()) {
// fieldNames.add(info.name);
// }
// }
// return fieldNames;
// }
//
// public QueryBuilder getQueryBuilder() {
// return queryBuilder;
// }
//
// public Analyzer getAnalyzerQuery() {
// return analyzerFactory.forQuery();
// }
//
// public BytesRefDisplay getTermBytesRefDisplay() {
// return termBytesRefDisplay;
// }
//
// public BytesRefDisplay getPayloadBytesRefDisplay() {
// return payloadBytesRefDisplay;
// }
//
// public Directory getDirectory() {
// return directory;
// }
//
// public void setReadOnlyMode(boolean readOnlyMode) {
// this.registry.setReadonly(readOnlyMode);
// if (writer != null) {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// writer = null;
// }
// }
//
// public void refreshReader() throws Exception {
// readerFactory.refreshReader();
// }
//
// @Override
// public void shutdown() throws Exception{
// try {
// readerFactory.shutdown();
// }
// finally{
// directory.close();
// if (writer != null) {
// writer.close();
// }
// }
// }
// }
//
// Path: src/main/java/io/dashbase/clue/api/BytesRefPrinter.java
// public interface BytesRefPrinter {
// String print(BytesRef bytesRef);
//
// public static BytesRefPrinter UTFPrinter = new BytesRefPrinter() {
//
// @Override
// public String print(BytesRef bytesRef) {
// return bytesRef.utf8ToString();
// }
//
// };
//
// public static BytesRefPrinter RawBytesPrinter = new BytesRefPrinter() {
//
// @Override
// public String print(BytesRef bytesRef) {
// return bytesRef.toString();
// }
//
// };
// }
//
// Path: src/main/java/io/dashbase/clue/ClueContext.java
// public class ClueContext {
// protected final CommandRegistry registry = new CommandRegistry();
//
// private final boolean interactiveMode;
//
// public ClueContext(CommandRegistrar commandRegistrar, boolean interactiveMode) {
// commandRegistrar.registerCommands(this);
// this.interactiveMode = interactiveMode;
// }
//
// public void registerCommand(ClueCommand cmd){
// String cmdName = cmd.getName();
// if (registry.exists(cmdName)){
// throw new IllegalArgumentException(cmdName+" exists!");
// }
// registry.registerCommand(cmd);
// }
//
// public boolean isReadOnlyMode() {
// return registry.isReadonly();
// }
//
// public boolean isInteractiveMode(){
// return interactiveMode;
// }
//
// public Optional<ClueCommand> getCommand(String cmd){
// return registry.getCommand(cmd);
// }
//
// public CommandRegistry getCommandRegistry(){
// return registry;
// }
//
// public void shutdown() throws Exception{
// }
// }
| import java.io.PrintStream;
import java.util.List;
import io.dashbase.clue.LuceneContext;
import io.dashbase.clue.api.BytesRefPrinter;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BytesRef;
import io.dashbase.clue.ClueContext; | package io.dashbase.clue.commands;
@Readonly
public class PostingsCommand extends ClueCommand {
| // Path: src/main/java/io/dashbase/clue/LuceneContext.java
// public class LuceneContext extends ClueContext {
// private final IndexReaderFactory readerFactory;
//
// private IndexWriter writer;
// private final Directory directory;
// private final IndexWriterConfig writerConfig;
// private final QueryBuilder queryBuilder;
// private final AnalyzerFactory analyzerFactory;
// private final BytesRefDisplay termBytesRefDisplay;
// private final BytesRefDisplay payloadBytesRefDisplay;
//
// public LuceneContext(String dir, ClueAppConfiguration config, boolean interactiveMode)
// throws Exception {
// super(config.commandRegistrar, interactiveMode);
// this.directory = config.dirBuilder.build(dir);
// this.analyzerFactory = config.analyzerFactory;
// this.readerFactory = config.indexReaderFactory;
// this.readerFactory.initialize(directory);
// this.queryBuilder = config.queryBuilder;
// this.queryBuilder.initialize("contents", analyzerFactory.forQuery());
// this.writerConfig = new IndexWriterConfig(new StandardAnalyzer());
// this.termBytesRefDisplay = new StringBytesRefDisplay();
// this.payloadBytesRefDisplay = new StringBytesRefDisplay();
// this.writer = null;
// }
//
//
// public IndexReader getIndexReader(){
// return readerFactory.getIndexReader();
// }
//
// public IndexSearcher getIndexSearcher() {
// return new IndexSearcher(getIndexReader());
// }
//
// public IndexWriter getIndexWriter(){
// if (registry.isReadonly()) return null;
// if (writer == null) {
// try {
// writer = new IndexWriter(directory, writerConfig);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return writer;
// }
//
// Collection<String> fieldNames() {
// LinkedList<String> fieldNames = new LinkedList<>();
// for (LeafReaderContext context : getIndexReader().leaves()) {
// LeafReader reader = context.reader();
// for(FieldInfo info : reader.getFieldInfos()) {
// fieldNames.add(info.name);
// }
// }
// return fieldNames;
// }
//
// public QueryBuilder getQueryBuilder() {
// return queryBuilder;
// }
//
// public Analyzer getAnalyzerQuery() {
// return analyzerFactory.forQuery();
// }
//
// public BytesRefDisplay getTermBytesRefDisplay() {
// return termBytesRefDisplay;
// }
//
// public BytesRefDisplay getPayloadBytesRefDisplay() {
// return payloadBytesRefDisplay;
// }
//
// public Directory getDirectory() {
// return directory;
// }
//
// public void setReadOnlyMode(boolean readOnlyMode) {
// this.registry.setReadonly(readOnlyMode);
// if (writer != null) {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// writer = null;
// }
// }
//
// public void refreshReader() throws Exception {
// readerFactory.refreshReader();
// }
//
// @Override
// public void shutdown() throws Exception{
// try {
// readerFactory.shutdown();
// }
// finally{
// directory.close();
// if (writer != null) {
// writer.close();
// }
// }
// }
// }
//
// Path: src/main/java/io/dashbase/clue/api/BytesRefPrinter.java
// public interface BytesRefPrinter {
// String print(BytesRef bytesRef);
//
// public static BytesRefPrinter UTFPrinter = new BytesRefPrinter() {
//
// @Override
// public String print(BytesRef bytesRef) {
// return bytesRef.utf8ToString();
// }
//
// };
//
// public static BytesRefPrinter RawBytesPrinter = new BytesRefPrinter() {
//
// @Override
// public String print(BytesRef bytesRef) {
// return bytesRef.toString();
// }
//
// };
// }
//
// Path: src/main/java/io/dashbase/clue/ClueContext.java
// public class ClueContext {
// protected final CommandRegistry registry = new CommandRegistry();
//
// private final boolean interactiveMode;
//
// public ClueContext(CommandRegistrar commandRegistrar, boolean interactiveMode) {
// commandRegistrar.registerCommands(this);
// this.interactiveMode = interactiveMode;
// }
//
// public void registerCommand(ClueCommand cmd){
// String cmdName = cmd.getName();
// if (registry.exists(cmdName)){
// throw new IllegalArgumentException(cmdName+" exists!");
// }
// registry.registerCommand(cmd);
// }
//
// public boolean isReadOnlyMode() {
// return registry.isReadonly();
// }
//
// public boolean isInteractiveMode(){
// return interactiveMode;
// }
//
// public Optional<ClueCommand> getCommand(String cmd){
// return registry.getCommand(cmd);
// }
//
// public CommandRegistry getCommandRegistry(){
// return registry;
// }
//
// public void shutdown() throws Exception{
// }
// }
// Path: src/main/java/io/dashbase/clue/commands/PostingsCommand.java
import java.io.PrintStream;
import java.util.List;
import io.dashbase.clue.LuceneContext;
import io.dashbase.clue.api.BytesRefPrinter;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BytesRef;
import io.dashbase.clue.ClueContext;
package io.dashbase.clue.commands;
@Readonly
public class PostingsCommand extends ClueCommand {
| private final LuceneContext ctx; |
javasoze/clue | src/main/java/io/dashbase/clue/ClueAppConfiguration.java | // Path: src/main/java/io/dashbase/clue/commands/CommandRegistrar.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DefaultCommandRegistrar.class)
// @JsonSubTypes({
// @JsonSubTypes.Type(name = "default", value = DefaultCommandRegistrar.class)
// })
// public interface CommandRegistrar {
// void registerCommands(ClueContext ctx);
// }
//
// Path: src/main/java/io/dashbase/clue/commands/DefaultCommandRegistrar.java
// public class DefaultCommandRegistrar implements CommandRegistrar {
// @Override
// public void registerCommands(ClueContext clueCtx) {
// LuceneContext ctx = (LuceneContext)clueCtx;
// // registers all the commands we currently support
// new HelpCommand(ctx);
// new InfoCommand(ctx);
// new DocValCommand(ctx);
// new SearchCommand(ctx);
// new CountCommand(ctx);
// new TermsCommand(ctx);
// new PostingsCommand(ctx);
// new DocSetInfoCommand(ctx);
// new MergeCommand(ctx);
// new DeleteCommand(ctx);
// new ReadonlyCommand(ctx);
// new DirectoryCommand(ctx);
// new ExplainCommand(ctx);
// new NormsCommand(ctx);
// new TermVectorCommand(ctx);
// new StoredFieldCommand(ctx);
// new ReconstructCommand(ctx);
// new ExportCommand(ctx);
// new IndexTrimCommand(ctx);
// new GetUserCommitDataCommand(ctx);
// new SaveUserCommitData(ctx);
// new DeleteUserCommitData(ctx);
// new DumpDocCommand(ctx);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.dashbase.clue.api.*;
import io.dashbase.clue.commands.CommandRegistrar;
import io.dashbase.clue.commands.DefaultCommandRegistrar;
import java.io.File;
import java.io.FileReader;
import java.io.IOException; | package io.dashbase.clue;
public class ClueAppConfiguration {
public QueryBuilder queryBuilder = new DefaultQueryBuilder();
public DirectoryBuilder dirBuilder = new DefaultDirectoryBuilder();
public IndexReaderFactory indexReaderFactory = new DefaultIndexReaderFactory();
public AnalyzerFactory analyzerFactory = new DefaultAnalyzerFactory(); | // Path: src/main/java/io/dashbase/clue/commands/CommandRegistrar.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DefaultCommandRegistrar.class)
// @JsonSubTypes({
// @JsonSubTypes.Type(name = "default", value = DefaultCommandRegistrar.class)
// })
// public interface CommandRegistrar {
// void registerCommands(ClueContext ctx);
// }
//
// Path: src/main/java/io/dashbase/clue/commands/DefaultCommandRegistrar.java
// public class DefaultCommandRegistrar implements CommandRegistrar {
// @Override
// public void registerCommands(ClueContext clueCtx) {
// LuceneContext ctx = (LuceneContext)clueCtx;
// // registers all the commands we currently support
// new HelpCommand(ctx);
// new InfoCommand(ctx);
// new DocValCommand(ctx);
// new SearchCommand(ctx);
// new CountCommand(ctx);
// new TermsCommand(ctx);
// new PostingsCommand(ctx);
// new DocSetInfoCommand(ctx);
// new MergeCommand(ctx);
// new DeleteCommand(ctx);
// new ReadonlyCommand(ctx);
// new DirectoryCommand(ctx);
// new ExplainCommand(ctx);
// new NormsCommand(ctx);
// new TermVectorCommand(ctx);
// new StoredFieldCommand(ctx);
// new ReconstructCommand(ctx);
// new ExportCommand(ctx);
// new IndexTrimCommand(ctx);
// new GetUserCommitDataCommand(ctx);
// new SaveUserCommitData(ctx);
// new DeleteUserCommitData(ctx);
// new DumpDocCommand(ctx);
// }
// }
// Path: src/main/java/io/dashbase/clue/ClueAppConfiguration.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.dashbase.clue.api.*;
import io.dashbase.clue.commands.CommandRegistrar;
import io.dashbase.clue.commands.DefaultCommandRegistrar;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
package io.dashbase.clue;
public class ClueAppConfiguration {
public QueryBuilder queryBuilder = new DefaultQueryBuilder();
public DirectoryBuilder dirBuilder = new DefaultDirectoryBuilder();
public IndexReaderFactory indexReaderFactory = new DefaultIndexReaderFactory();
public AnalyzerFactory analyzerFactory = new DefaultAnalyzerFactory(); | public CommandRegistrar commandRegistrar = new DefaultCommandRegistrar(); |
javasoze/clue | src/main/java/io/dashbase/clue/ClueAppConfiguration.java | // Path: src/main/java/io/dashbase/clue/commands/CommandRegistrar.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DefaultCommandRegistrar.class)
// @JsonSubTypes({
// @JsonSubTypes.Type(name = "default", value = DefaultCommandRegistrar.class)
// })
// public interface CommandRegistrar {
// void registerCommands(ClueContext ctx);
// }
//
// Path: src/main/java/io/dashbase/clue/commands/DefaultCommandRegistrar.java
// public class DefaultCommandRegistrar implements CommandRegistrar {
// @Override
// public void registerCommands(ClueContext clueCtx) {
// LuceneContext ctx = (LuceneContext)clueCtx;
// // registers all the commands we currently support
// new HelpCommand(ctx);
// new InfoCommand(ctx);
// new DocValCommand(ctx);
// new SearchCommand(ctx);
// new CountCommand(ctx);
// new TermsCommand(ctx);
// new PostingsCommand(ctx);
// new DocSetInfoCommand(ctx);
// new MergeCommand(ctx);
// new DeleteCommand(ctx);
// new ReadonlyCommand(ctx);
// new DirectoryCommand(ctx);
// new ExplainCommand(ctx);
// new NormsCommand(ctx);
// new TermVectorCommand(ctx);
// new StoredFieldCommand(ctx);
// new ReconstructCommand(ctx);
// new ExportCommand(ctx);
// new IndexTrimCommand(ctx);
// new GetUserCommitDataCommand(ctx);
// new SaveUserCommitData(ctx);
// new DeleteUserCommitData(ctx);
// new DumpDocCommand(ctx);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.dashbase.clue.api.*;
import io.dashbase.clue.commands.CommandRegistrar;
import io.dashbase.clue.commands.DefaultCommandRegistrar;
import java.io.File;
import java.io.FileReader;
import java.io.IOException; | package io.dashbase.clue;
public class ClueAppConfiguration {
public QueryBuilder queryBuilder = new DefaultQueryBuilder();
public DirectoryBuilder dirBuilder = new DefaultDirectoryBuilder();
public IndexReaderFactory indexReaderFactory = new DefaultIndexReaderFactory();
public AnalyzerFactory analyzerFactory = new DefaultAnalyzerFactory(); | // Path: src/main/java/io/dashbase/clue/commands/CommandRegistrar.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DefaultCommandRegistrar.class)
// @JsonSubTypes({
// @JsonSubTypes.Type(name = "default", value = DefaultCommandRegistrar.class)
// })
// public interface CommandRegistrar {
// void registerCommands(ClueContext ctx);
// }
//
// Path: src/main/java/io/dashbase/clue/commands/DefaultCommandRegistrar.java
// public class DefaultCommandRegistrar implements CommandRegistrar {
// @Override
// public void registerCommands(ClueContext clueCtx) {
// LuceneContext ctx = (LuceneContext)clueCtx;
// // registers all the commands we currently support
// new HelpCommand(ctx);
// new InfoCommand(ctx);
// new DocValCommand(ctx);
// new SearchCommand(ctx);
// new CountCommand(ctx);
// new TermsCommand(ctx);
// new PostingsCommand(ctx);
// new DocSetInfoCommand(ctx);
// new MergeCommand(ctx);
// new DeleteCommand(ctx);
// new ReadonlyCommand(ctx);
// new DirectoryCommand(ctx);
// new ExplainCommand(ctx);
// new NormsCommand(ctx);
// new TermVectorCommand(ctx);
// new StoredFieldCommand(ctx);
// new ReconstructCommand(ctx);
// new ExportCommand(ctx);
// new IndexTrimCommand(ctx);
// new GetUserCommitDataCommand(ctx);
// new SaveUserCommitData(ctx);
// new DeleteUserCommitData(ctx);
// new DumpDocCommand(ctx);
// }
// }
// Path: src/main/java/io/dashbase/clue/ClueAppConfiguration.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.dashbase.clue.api.*;
import io.dashbase.clue.commands.CommandRegistrar;
import io.dashbase.clue.commands.DefaultCommandRegistrar;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
package io.dashbase.clue;
public class ClueAppConfiguration {
public QueryBuilder queryBuilder = new DefaultQueryBuilder();
public DirectoryBuilder dirBuilder = new DefaultDirectoryBuilder();
public IndexReaderFactory indexReaderFactory = new DefaultIndexReaderFactory();
public AnalyzerFactory analyzerFactory = new DefaultAnalyzerFactory(); | public CommandRegistrar commandRegistrar = new DefaultCommandRegistrar(); |
javasoze/clue | src/main/java/io/dashbase/clue/commands/SearchCommand.java | // Path: src/main/java/io/dashbase/clue/LuceneContext.java
// public class LuceneContext extends ClueContext {
// private final IndexReaderFactory readerFactory;
//
// private IndexWriter writer;
// private final Directory directory;
// private final IndexWriterConfig writerConfig;
// private final QueryBuilder queryBuilder;
// private final AnalyzerFactory analyzerFactory;
// private final BytesRefDisplay termBytesRefDisplay;
// private final BytesRefDisplay payloadBytesRefDisplay;
//
// public LuceneContext(String dir, ClueAppConfiguration config, boolean interactiveMode)
// throws Exception {
// super(config.commandRegistrar, interactiveMode);
// this.directory = config.dirBuilder.build(dir);
// this.analyzerFactory = config.analyzerFactory;
// this.readerFactory = config.indexReaderFactory;
// this.readerFactory.initialize(directory);
// this.queryBuilder = config.queryBuilder;
// this.queryBuilder.initialize("contents", analyzerFactory.forQuery());
// this.writerConfig = new IndexWriterConfig(new StandardAnalyzer());
// this.termBytesRefDisplay = new StringBytesRefDisplay();
// this.payloadBytesRefDisplay = new StringBytesRefDisplay();
// this.writer = null;
// }
//
//
// public IndexReader getIndexReader(){
// return readerFactory.getIndexReader();
// }
//
// public IndexSearcher getIndexSearcher() {
// return new IndexSearcher(getIndexReader());
// }
//
// public IndexWriter getIndexWriter(){
// if (registry.isReadonly()) return null;
// if (writer == null) {
// try {
// writer = new IndexWriter(directory, writerConfig);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return writer;
// }
//
// Collection<String> fieldNames() {
// LinkedList<String> fieldNames = new LinkedList<>();
// for (LeafReaderContext context : getIndexReader().leaves()) {
// LeafReader reader = context.reader();
// for(FieldInfo info : reader.getFieldInfos()) {
// fieldNames.add(info.name);
// }
// }
// return fieldNames;
// }
//
// public QueryBuilder getQueryBuilder() {
// return queryBuilder;
// }
//
// public Analyzer getAnalyzerQuery() {
// return analyzerFactory.forQuery();
// }
//
// public BytesRefDisplay getTermBytesRefDisplay() {
// return termBytesRefDisplay;
// }
//
// public BytesRefDisplay getPayloadBytesRefDisplay() {
// return payloadBytesRefDisplay;
// }
//
// public Directory getDirectory() {
// return directory;
// }
//
// public void setReadOnlyMode(boolean readOnlyMode) {
// this.registry.setReadonly(readOnlyMode);
// if (writer != null) {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// writer = null;
// }
// }
//
// public void refreshReader() throws Exception {
// readerFactory.refreshReader();
// }
//
// @Override
// public void shutdown() throws Exception{
// try {
// readerFactory.shutdown();
// }
// finally{
// directory.close();
// if (writer != null) {
// writer.close();
// }
// }
// }
// }
//
// Path: src/main/java/io/dashbase/clue/client/CmdlineHelper.java
// public class CmdlineHelper {
// private final ConsoleReader consoleReader;
//
// public CmdlineHelper(Supplier<Collection<String>> commandNameSupplier,
// Supplier<Collection<String>> fieldNameSupplier) throws IOException {
// consoleReader = new ConsoleReader();
// consoleReader.setBellEnabled(false);
//
// Collection<String> commands = commandNameSupplier != null
// ? commandNameSupplier.get() : Collections.emptyList();
//
// Collection<String> fields = fieldNameSupplier != null
// ? fieldNameSupplier.get() : Collections.emptyList();
//
// LinkedList<Completer> completors = new LinkedList<Completer>();
// completors.add(new StringsCompleter(commands));
// completors.add(new StringsCompleter(fields));
// completors.add(new FileNameCompleter());
// consoleReader.addCompleter(new ArgumentCompleter(completors));
// }
//
// public String readCommand() {
// try {
// return consoleReader.readLine("> ");
// } catch (IOException e) {
// System.err.println("Error! Clue is unable to read line from stdin: " + e.getMessage());
// throw new IllegalStateException("Unable to read command line!", e);
// }
// }
//
// public static String toString(List<String> list) {
// StringBuilder buf = new StringBuilder();
// for (String s : list) {
// buf.append(s).append(" ");
// }
// return buf.toString().trim();
// }
//
// public static Query toQuery(List<String> list, QueryBuilder queryBuilder) throws Exception {
// String qstring = toString(list);
// Query q = null;
// if (qstring == null || qstring.isEmpty() || qstring.equals("*")){
// q = new MatchAllDocsQuery();
// }
// else{
// q = queryBuilder.build(qstring);
// }
// return q;
// }
// }
| import java.io.PrintStream;
import java.util.List;
import io.dashbase.clue.LuceneContext;
import io.dashbase.clue.client.CmdlineHelper;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs; | package io.dashbase.clue.commands;
@Readonly
public class SearchCommand extends ClueCommand {
| // Path: src/main/java/io/dashbase/clue/LuceneContext.java
// public class LuceneContext extends ClueContext {
// private final IndexReaderFactory readerFactory;
//
// private IndexWriter writer;
// private final Directory directory;
// private final IndexWriterConfig writerConfig;
// private final QueryBuilder queryBuilder;
// private final AnalyzerFactory analyzerFactory;
// private final BytesRefDisplay termBytesRefDisplay;
// private final BytesRefDisplay payloadBytesRefDisplay;
//
// public LuceneContext(String dir, ClueAppConfiguration config, boolean interactiveMode)
// throws Exception {
// super(config.commandRegistrar, interactiveMode);
// this.directory = config.dirBuilder.build(dir);
// this.analyzerFactory = config.analyzerFactory;
// this.readerFactory = config.indexReaderFactory;
// this.readerFactory.initialize(directory);
// this.queryBuilder = config.queryBuilder;
// this.queryBuilder.initialize("contents", analyzerFactory.forQuery());
// this.writerConfig = new IndexWriterConfig(new StandardAnalyzer());
// this.termBytesRefDisplay = new StringBytesRefDisplay();
// this.payloadBytesRefDisplay = new StringBytesRefDisplay();
// this.writer = null;
// }
//
//
// public IndexReader getIndexReader(){
// return readerFactory.getIndexReader();
// }
//
// public IndexSearcher getIndexSearcher() {
// return new IndexSearcher(getIndexReader());
// }
//
// public IndexWriter getIndexWriter(){
// if (registry.isReadonly()) return null;
// if (writer == null) {
// try {
// writer = new IndexWriter(directory, writerConfig);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return writer;
// }
//
// Collection<String> fieldNames() {
// LinkedList<String> fieldNames = new LinkedList<>();
// for (LeafReaderContext context : getIndexReader().leaves()) {
// LeafReader reader = context.reader();
// for(FieldInfo info : reader.getFieldInfos()) {
// fieldNames.add(info.name);
// }
// }
// return fieldNames;
// }
//
// public QueryBuilder getQueryBuilder() {
// return queryBuilder;
// }
//
// public Analyzer getAnalyzerQuery() {
// return analyzerFactory.forQuery();
// }
//
// public BytesRefDisplay getTermBytesRefDisplay() {
// return termBytesRefDisplay;
// }
//
// public BytesRefDisplay getPayloadBytesRefDisplay() {
// return payloadBytesRefDisplay;
// }
//
// public Directory getDirectory() {
// return directory;
// }
//
// public void setReadOnlyMode(boolean readOnlyMode) {
// this.registry.setReadonly(readOnlyMode);
// if (writer != null) {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// writer = null;
// }
// }
//
// public void refreshReader() throws Exception {
// readerFactory.refreshReader();
// }
//
// @Override
// public void shutdown() throws Exception{
// try {
// readerFactory.shutdown();
// }
// finally{
// directory.close();
// if (writer != null) {
// writer.close();
// }
// }
// }
// }
//
// Path: src/main/java/io/dashbase/clue/client/CmdlineHelper.java
// public class CmdlineHelper {
// private final ConsoleReader consoleReader;
//
// public CmdlineHelper(Supplier<Collection<String>> commandNameSupplier,
// Supplier<Collection<String>> fieldNameSupplier) throws IOException {
// consoleReader = new ConsoleReader();
// consoleReader.setBellEnabled(false);
//
// Collection<String> commands = commandNameSupplier != null
// ? commandNameSupplier.get() : Collections.emptyList();
//
// Collection<String> fields = fieldNameSupplier != null
// ? fieldNameSupplier.get() : Collections.emptyList();
//
// LinkedList<Completer> completors = new LinkedList<Completer>();
// completors.add(new StringsCompleter(commands));
// completors.add(new StringsCompleter(fields));
// completors.add(new FileNameCompleter());
// consoleReader.addCompleter(new ArgumentCompleter(completors));
// }
//
// public String readCommand() {
// try {
// return consoleReader.readLine("> ");
// } catch (IOException e) {
// System.err.println("Error! Clue is unable to read line from stdin: " + e.getMessage());
// throw new IllegalStateException("Unable to read command line!", e);
// }
// }
//
// public static String toString(List<String> list) {
// StringBuilder buf = new StringBuilder();
// for (String s : list) {
// buf.append(s).append(" ");
// }
// return buf.toString().trim();
// }
//
// public static Query toQuery(List<String> list, QueryBuilder queryBuilder) throws Exception {
// String qstring = toString(list);
// Query q = null;
// if (qstring == null || qstring.isEmpty() || qstring.equals("*")){
// q = new MatchAllDocsQuery();
// }
// else{
// q = queryBuilder.build(qstring);
// }
// return q;
// }
// }
// Path: src/main/java/io/dashbase/clue/commands/SearchCommand.java
import java.io.PrintStream;
import java.util.List;
import io.dashbase.clue.LuceneContext;
import io.dashbase.clue.client.CmdlineHelper;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
package io.dashbase.clue.commands;
@Readonly
public class SearchCommand extends ClueCommand {
| private final LuceneContext ctx; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.