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
robneild/pocket-query-creator
app/src/main/java/org/pquery/util/IOUtils.java
// Path: app/src/main/java/org/pquery/webdriver/CancelledListener.java // public interface CancelledListener { // void ifCancelledThrow() throws InterruptedException; // } // // Path: app/src/main/java/org/pquery/webdriver/HttpClientFactory.java // public class HttpClientFactory { // // // public static DefaultHttpClient createHttpClient() { // // // // // Set timeout // // // I have seen some random failures where the network access just seems to lock-up for over a minute // // // I can't reproduce it but hopefully this will make it error and allow user to manually retry // // final HttpParams httpParams = new BasicHttpParams(); // // HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // // HttpConnectionParams.setSoTimeout(httpParams, 10000); // // // // return new DefaultHttpClient(httpParams); // // } // // public static HttpURLConnection createURLConnection(URL url) throws IOException { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // // // Set timeout // // I have seen some random failures where the network access just seems to lock-up // // ... for minutes // // I can't reproduce it but hopefully this will make it error out and allow user to manually // // retry // conn.setReadTimeout(20000); // 20 seconds // conn.setConnectTimeout(20000); // 20 seconds // // conn.setRequestProperty("Accept-Encoding", "gzip"); // conn.setRequestProperty("Host", "www.geocaching.com"); // // // Makes our job a bit easier trying to work out what is going on with login problems etc. // conn.setInstanceFollowRedirects(false); // // return conn; // } // }
import android.content.Context; import android.util.Pair; import org.pquery.webdriver.CancelledListener; import org.pquery.webdriver.HttpClientFactory; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream;
cancelledListener.ifCancelledThrow(); } Logger.d("toByteArray expectedLength=" + expectedLength + ", actualLength=" + total); return byteOut.toByteArray(); } public static String httpGet(Context cxt, String path, CancelledListener cancelledListener, Listener listener) throws IOException, InterruptedException { FileDetails fileDetails = httpGetBytes(cxt, path, cancelledListener, listener); // Convert data into string. Geocaching.com uses utf-8 pages? String ret = new String(fileDetails.contents, "utf-8"); Logger.d(ret); return ret; } /** * Read a html string from HttpResponse * Doesn't follow redirects and throws exception if http status code isn't good * * @throws InterruptedException */ public static FileDetails httpGetBytes(Context cxt, String path, CancelledListener cancelledListener, Listener listener) throws IOException, InterruptedException { Logger.d("enter [path=" + getSecureHost() + path + "]"); URL url = new URL(getSecureHost() + path);
// Path: app/src/main/java/org/pquery/webdriver/CancelledListener.java // public interface CancelledListener { // void ifCancelledThrow() throws InterruptedException; // } // // Path: app/src/main/java/org/pquery/webdriver/HttpClientFactory.java // public class HttpClientFactory { // // // public static DefaultHttpClient createHttpClient() { // // // // // Set timeout // // // I have seen some random failures where the network access just seems to lock-up for over a minute // // // I can't reproduce it but hopefully this will make it error and allow user to manually retry // // final HttpParams httpParams = new BasicHttpParams(); // // HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // // HttpConnectionParams.setSoTimeout(httpParams, 10000); // // // // return new DefaultHttpClient(httpParams); // // } // // public static HttpURLConnection createURLConnection(URL url) throws IOException { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // // // Set timeout // // I have seen some random failures where the network access just seems to lock-up // // ... for minutes // // I can't reproduce it but hopefully this will make it error out and allow user to manually // // retry // conn.setReadTimeout(20000); // 20 seconds // conn.setConnectTimeout(20000); // 20 seconds // // conn.setRequestProperty("Accept-Encoding", "gzip"); // conn.setRequestProperty("Host", "www.geocaching.com"); // // // Makes our job a bit easier trying to work out what is going on with login problems etc. // conn.setInstanceFollowRedirects(false); // // return conn; // } // } // Path: app/src/main/java/org/pquery/util/IOUtils.java import android.content.Context; import android.util.Pair; import org.pquery.webdriver.CancelledListener; import org.pquery.webdriver.HttpClientFactory; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; cancelledListener.ifCancelledThrow(); } Logger.d("toByteArray expectedLength=" + expectedLength + ", actualLength=" + total); return byteOut.toByteArray(); } public static String httpGet(Context cxt, String path, CancelledListener cancelledListener, Listener listener) throws IOException, InterruptedException { FileDetails fileDetails = httpGetBytes(cxt, path, cancelledListener, listener); // Convert data into string. Geocaching.com uses utf-8 pages? String ret = new String(fileDetails.contents, "utf-8"); Logger.d(ret); return ret; } /** * Read a html string from HttpResponse * Doesn't follow redirects and throws exception if http status code isn't good * * @throws InterruptedException */ public static FileDetails httpGetBytes(Context cxt, String path, CancelledListener cancelledListener, Listener listener) throws IOException, InterruptedException { Logger.d("enter [path=" + getSecureHost() + path + "]"); URL url = new URL(getSecureHost() + path);
HttpURLConnection client = HttpClientFactory.createURLConnection(url);
robneild/pocket-query-creator
app/src/main/java/org/pquery/filter/CacheTypeList.java
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // }
import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList;
package org.pquery.filter; /** * Represents a list of CacheTypes * Used as a creation filter */ public class CacheTypeList implements Iterable<CacheType> { /** * wrapped list */ private LinkedList<CacheType> inner = new LinkedList<CacheType>(); public CacheTypeList() { } /** * Construct from a string of comma separated string * Used to retrieve from preferences */ public CacheTypeList(String s) { Asserts.checkNotNull(s); String[] cacheList = s.split(","); for (String cache : cacheList) { if (cache.length() > 0) inner.add(CacheType.valueOf(cache)); } if (inner.size() == 0) { setAll(); } } /** * Create list from an array * Expect array to contain a boolean for each CacheType */ public CacheTypeList(boolean[] selection) {
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // } // Path: app/src/main/java/org/pquery/filter/CacheTypeList.java import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList; package org.pquery.filter; /** * Represents a list of CacheTypes * Used as a creation filter */ public class CacheTypeList implements Iterable<CacheType> { /** * wrapped list */ private LinkedList<CacheType> inner = new LinkedList<CacheType>(); public CacheTypeList() { } /** * Construct from a string of comma separated string * Used to retrieve from preferences */ public CacheTypeList(String s) { Asserts.checkNotNull(s); String[] cacheList = s.split(","); for (String cache : cacheList) { if (cache.length() > 0) inner.add(CacheType.valueOf(cache)); } if (inner.size() == 0) { setAll(); } } /** * Create list from an array * Expect array to contain a boolean for each CacheType */ public CacheTypeList(boolean[] selection) {
Assert.assertEquals(CacheType.values().length, selection.length);
robneild/pocket-query-creator
app/src/main/java/org/pquery/filter/CacheTypeList.java
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // }
import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList;
for (int i = 0; i < selection.length; i++) { if (selection[i]) { inner.add(CacheType.values()[i]); } } if (CacheType.values().length == inner.size()) inner.clear(); } /** * Convert to comma seperated string. Uses enum type name */ public String toString() { String ret = ""; for (CacheType cache : inner) { ret += cache.toString() + ","; } return ret; } /** * A nice, comma separated, localized, HTML list for presentation to user * Enum value converted into display string */ public String toLocalisedString(Resources res) { if (isAll())
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // } // Path: app/src/main/java/org/pquery/filter/CacheTypeList.java import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList; for (int i = 0; i < selection.length; i++) { if (selection[i]) { inner.add(CacheType.values()[i]); } } if (CacheType.values().length == inner.size()) inner.clear(); } /** * Convert to comma seperated string. Uses enum type name */ public String toString() { String ret = ""; for (CacheType cache : inner) { ret += cache.toString() + ","; } return ret; } /** * A nice, comma separated, localized, HTML list for presentation to user * Enum value converted into display string */ public String toLocalisedString(Resources res) { if (isAll())
return "<font color='" + MyColors.LIME + "'>" + res.getString(R.string.any) + "</font>";
robneild/pocket-query-creator
app/src/main/java/org/pquery/filter/OneToFiveFilter.java
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // }
import android.content.Context; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors;
package org.pquery.filter; public class OneToFiveFilter { public int value; public boolean up; public OneToFiveFilter() { value = 5; up = false; } public OneToFiveFilter(String s) { if (s.equals("1")) { value = 1; up = false; } else if (s.equals("5")) { value = 5; up = true; } else if (s.equals("All")) { value = 1; up = true; } else { String[] a = s.split(" - "); if (a == null)
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // } // Path: app/src/main/java/org/pquery/filter/OneToFiveFilter.java import android.content.Context; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; package org.pquery.filter; public class OneToFiveFilter { public int value; public boolean up; public OneToFiveFilter() { value = 5; up = false; } public OneToFiveFilter(String s) { if (s.equals("1")) { value = 1; up = false; } else if (s.equals("5")) { value = 5; up = true; } else if (s.equals("All")) { value = 1; up = true; } else { String[] a = s.split(" - "); if (a == null)
Assert.fail();
robneild/pocket-query-creator
app/src/main/java/org/pquery/filter/OneToFiveFilter.java
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // }
import android.content.Context; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors;
value = v1; } else Assert.fail(); } } @Override public String toString() { if (value == 5 && up) return "5"; if (value == 1 && !up) return "1"; if ((value == 1 && up) || (value == 5 && !up)) return "All"; if (up) return "" + value + " - 5"; return "1 - " + value; } /** * Display a colorized summary of this filter * @param cxt * @return html */ public String toLocalisedString(Context cxt) { String ret = ""; if (isAll())
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // } // Path: app/src/main/java/org/pquery/filter/OneToFiveFilter.java import android.content.Context; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; value = v1; } else Assert.fail(); } } @Override public String toString() { if (value == 5 && up) return "5"; if (value == 1 && !up) return "1"; if ((value == 1 && up) || (value == 5 && !up)) return "All"; if (up) return "" + value + " - 5"; return "1 - " + value; } /** * Display a colorized summary of this filter * @param cxt * @return html */ public String toLocalisedString(Context cxt) { String ret = ""; if (isAll())
ret ="<font color='" + MyColors.LIME + "'>"; // Lime
robneild/pocket-query-creator
app/src/androidTest/java/org/pquery/webdriver/parser/GeocachingPageTest.java
// Path: app/src/main/java/org/pquery/util/Util.java // public class Util { // // /** // * Produce a human download progress string given bytes downloaded and total // * e.g 14/100 KiB // */ // public static String humanDownloadCounter(int bytesDownloaded, int expected) { // StringBuffer ret = new StringBuffer(); // // ret.append(bytesDownloaded / 1024); // if (expected > 0) // ret.append("/" + expected / 1024); // ret.append(" KiB"); // // return ret.toString(); // } // // private static final String reservedCharsRegExp = "[|\\\\?*<\":>+\\[\\]/']"; // // /** // * Try to create a legal filename from what user entered // * <p/> // * Strip illegal characters. // * If that ends up with an empty filename, use a default // */ // public static String sanitizeFileName(String name) { // name = name.replaceAll(reservedCharsRegExp, ""); // if (name.length() == 0) // name = "pocketquery"; // return name; // } // // /** // * Create a sane, unique file // * Strips illegal characters and adds numbers on end to make unique (if necessary) // */ // public static File getUniqueFile(String path, String name, String extension) { // // name = sanitizeFileName(name); // // int i = 0; // File file = new File(path, name + "." + extension); // while (file.exists()) { // // Try to add a number at end to make unique // i++; // file = new File(path, name + "(" + i + ")." + extension); // } // return file; // } // // /** // * Create a sane, unique file // * Strips illegal characters and adds numbers on end to make unique (if necessary) // */ // public static File getUniqueFile(String path, String name) { // return getUniqueFile(path, removeExtension(name), "zip"); // } // // /** // * Extract extension from a file // */ // public static String removeExtension(String s) { // String ret = s; // int i = s.lastIndexOf('.'); // // if (i > 0 && i < s.length() - 1) { // ret = s.substring(0, i); // } // return ret; // } // // public static String getDefaultDownloadDirectory(Context cxt) { // // String dir; // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ) { // // Old behaviour that I am not changing // dir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download"; // } else { // // New android 6 // // Default to the (pretty rubbish) directory we will always be able to write to // // without asking for more permissions // dir = cxt.getFilesDir().getAbsolutePath(); // } // // return dir; // } // // /** // * Read a 'Reader' (e.g. FileReader), into a String // */ // public static String readerIntoString(Reader read) throws IOException { // StringBuffer out = new StringBuffer(); // BufferedReader buffreader = new BufferedReader(read); // // String line = buffreader.readLine(); // while (line != null) { // out.append(line); // out.append("\r\n"); // 'readLine' strips newlines so have to put back on // line = buffreader.readLine(); // } // return out.toString(); // } // // public static String inputStreamIntoString(InputStream streamIn) throws IOException { // return readerIntoString(new InputStreamReader(streamIn, "utf8")); // } // // // public static Drawable toGrey(Resources res, int resource) { // // Drawable draw = res.getDrawable(resource); // // Bitmap b = ((BitmapDrawable) draw).getBitmap().copy(Config.ARGB_8888, true); // // //Bitmap copy = src.copy(Config.ARGB_8888, true); // // for (int x = 0; x < b.getWidth(); x++) // for (int y = 0; y < b.getHeight(); y++) { // int color = b.getPixel(x, y); // int newColor = Color.argb(Color.alpha(color) / 3, Color.red(color), Color.green(color), Color.blue(color)); // b.setPixel(x, y, newColor); // // } // // Drawable greyDrawable = new BitmapDrawable(res, b); // // return greyDrawable; // } // }
import android.test.AndroidTestCase; import net.htmlparser.jericho.FormFields; import org.pquery.util.Util; import org.pquery.webdriver.parser.GeocachingPage.ParseException; import java.io.IOException; import java.io.InputStream;
package org.pquery.webdriver.parser; public class GeocachingPageTest extends AndroidTestCase { private GeocachingPage simple; private GeocachingPage createNewPocketQuery; private GeocachingPage createNewPocketQueryLoggedOut; private GeocachingPage createNewPocketQueryNonPremium; @Override protected void setUp() throws Exception { simple = new GeocachingPage(loadFromResource("simple_form.htm")); createNewPocketQuery = new GeocachingPage(loadFromResource("create_new_pocket_query.htm")); createNewPocketQueryLoggedOut = new GeocachingPage(loadFromResource("create_new_pocket_query_logged_out.htm")); createNewPocketQueryNonPremium = new GeocachingPage(loadFromResource("create_new_pocket_query_non_premium.htm")); } private String loadFromResource(String name) throws IOException { InputStream in = getClass().getClassLoader().getResourceAsStream("res/raw/" + name); assertNotNull(in);
// Path: app/src/main/java/org/pquery/util/Util.java // public class Util { // // /** // * Produce a human download progress string given bytes downloaded and total // * e.g 14/100 KiB // */ // public static String humanDownloadCounter(int bytesDownloaded, int expected) { // StringBuffer ret = new StringBuffer(); // // ret.append(bytesDownloaded / 1024); // if (expected > 0) // ret.append("/" + expected / 1024); // ret.append(" KiB"); // // return ret.toString(); // } // // private static final String reservedCharsRegExp = "[|\\\\?*<\":>+\\[\\]/']"; // // /** // * Try to create a legal filename from what user entered // * <p/> // * Strip illegal characters. // * If that ends up with an empty filename, use a default // */ // public static String sanitizeFileName(String name) { // name = name.replaceAll(reservedCharsRegExp, ""); // if (name.length() == 0) // name = "pocketquery"; // return name; // } // // /** // * Create a sane, unique file // * Strips illegal characters and adds numbers on end to make unique (if necessary) // */ // public static File getUniqueFile(String path, String name, String extension) { // // name = sanitizeFileName(name); // // int i = 0; // File file = new File(path, name + "." + extension); // while (file.exists()) { // // Try to add a number at end to make unique // i++; // file = new File(path, name + "(" + i + ")." + extension); // } // return file; // } // // /** // * Create a sane, unique file // * Strips illegal characters and adds numbers on end to make unique (if necessary) // */ // public static File getUniqueFile(String path, String name) { // return getUniqueFile(path, removeExtension(name), "zip"); // } // // /** // * Extract extension from a file // */ // public static String removeExtension(String s) { // String ret = s; // int i = s.lastIndexOf('.'); // // if (i > 0 && i < s.length() - 1) { // ret = s.substring(0, i); // } // return ret; // } // // public static String getDefaultDownloadDirectory(Context cxt) { // // String dir; // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ) { // // Old behaviour that I am not changing // dir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download"; // } else { // // New android 6 // // Default to the (pretty rubbish) directory we will always be able to write to // // without asking for more permissions // dir = cxt.getFilesDir().getAbsolutePath(); // } // // return dir; // } // // /** // * Read a 'Reader' (e.g. FileReader), into a String // */ // public static String readerIntoString(Reader read) throws IOException { // StringBuffer out = new StringBuffer(); // BufferedReader buffreader = new BufferedReader(read); // // String line = buffreader.readLine(); // while (line != null) { // out.append(line); // out.append("\r\n"); // 'readLine' strips newlines so have to put back on // line = buffreader.readLine(); // } // return out.toString(); // } // // public static String inputStreamIntoString(InputStream streamIn) throws IOException { // return readerIntoString(new InputStreamReader(streamIn, "utf8")); // } // // // public static Drawable toGrey(Resources res, int resource) { // // Drawable draw = res.getDrawable(resource); // // Bitmap b = ((BitmapDrawable) draw).getBitmap().copy(Config.ARGB_8888, true); // // //Bitmap copy = src.copy(Config.ARGB_8888, true); // // for (int x = 0; x < b.getWidth(); x++) // for (int y = 0; y < b.getHeight(); y++) { // int color = b.getPixel(x, y); // int newColor = Color.argb(Color.alpha(color) / 3, Color.red(color), Color.green(color), Color.blue(color)); // b.setPixel(x, y, newColor); // // } // // Drawable greyDrawable = new BitmapDrawable(res, b); // // return greyDrawable; // } // } // Path: app/src/androidTest/java/org/pquery/webdriver/parser/GeocachingPageTest.java import android.test.AndroidTestCase; import net.htmlparser.jericho.FormFields; import org.pquery.util.Util; import org.pquery.webdriver.parser.GeocachingPage.ParseException; import java.io.IOException; import java.io.InputStream; package org.pquery.webdriver.parser; public class GeocachingPageTest extends AndroidTestCase { private GeocachingPage simple; private GeocachingPage createNewPocketQuery; private GeocachingPage createNewPocketQueryLoggedOut; private GeocachingPage createNewPocketQueryNonPremium; @Override protected void setUp() throws Exception { simple = new GeocachingPage(loadFromResource("simple_form.htm")); createNewPocketQuery = new GeocachingPage(loadFromResource("create_new_pocket_query.htm")); createNewPocketQueryLoggedOut = new GeocachingPage(loadFromResource("create_new_pocket_query_logged_out.htm")); createNewPocketQueryNonPremium = new GeocachingPage(loadFromResource("create_new_pocket_query_non_premium.htm")); } private String loadFromResource(String name) throws IOException { InputStream in = getClass().getClassLoader().getResourceAsStream("res/raw/" + name); assertNotNull(in);
String ret = Util.inputStreamIntoString(in);
robneild/pocket-query-creator
app/src/main/java/com/gisgraphy/gishraphoid/AndroidAddressBuilder.java
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/GeoNamesAddressDto.java // public class GeoNamesAddressDto { // // public String countryName; // public String toponymName; // public String name; // // } // // Path: app/src/main/java/com/gisgraphy/domain/valueobject/Street.java // public class Street { // // public String name; // public String isIn; // }
import android.location.Address; import com.gisgraphy.domain.valueobject.GeoNamesAddressDto; import com.gisgraphy.domain.valueobject.Street; import java.util.ArrayList; import java.util.List; import java.util.Locale;
package com.gisgraphy.gishraphoid; public class AndroidAddressBuilder { public AndroidAddressBuilder(Locale locale) { } public AndroidAddressBuilder() { }
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/GeoNamesAddressDto.java // public class GeoNamesAddressDto { // // public String countryName; // public String toponymName; // public String name; // // } // // Path: app/src/main/java/com/gisgraphy/domain/valueobject/Street.java // public class Street { // // public String name; // public String isIn; // } // Path: app/src/main/java/com/gisgraphy/gishraphoid/AndroidAddressBuilder.java import android.location.Address; import com.gisgraphy.domain.valueobject.GeoNamesAddressDto; import com.gisgraphy.domain.valueobject.Street; import java.util.ArrayList; import java.util.List; import java.util.Locale; package com.gisgraphy.gishraphoid; public class AndroidAddressBuilder { public AndroidAddressBuilder(Locale locale) { } public AndroidAddressBuilder() { }
public List<Address> transformStreetsToAndroidAddresses(Street[] result) {
robneild/pocket-query-creator
app/src/main/java/com/gisgraphy/gishraphoid/AndroidAddressBuilder.java
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/GeoNamesAddressDto.java // public class GeoNamesAddressDto { // // public String countryName; // public String toponymName; // public String name; // // } // // Path: app/src/main/java/com/gisgraphy/domain/valueobject/Street.java // public class Street { // // public String name; // public String isIn; // }
import android.location.Address; import com.gisgraphy.domain.valueobject.GeoNamesAddressDto; import com.gisgraphy.domain.valueobject.Street; import java.util.ArrayList; import java.util.List; import java.util.Locale;
package com.gisgraphy.gishraphoid; public class AndroidAddressBuilder { public AndroidAddressBuilder(Locale locale) { } public AndroidAddressBuilder() { } public List<Address> transformStreetsToAndroidAddresses(Street[] result) { ArrayList<Address> ret = new ArrayList<Address>(); for (Street street : result) { Address address = new Address(Locale.getDefault()); if (street.name != null) address.setAddressLine(0, street.name); if (street.isIn != null) address.setLocality(street.isIn); ret.add(address); } return ret; }
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/GeoNamesAddressDto.java // public class GeoNamesAddressDto { // // public String countryName; // public String toponymName; // public String name; // // } // // Path: app/src/main/java/com/gisgraphy/domain/valueobject/Street.java // public class Street { // // public String name; // public String isIn; // } // Path: app/src/main/java/com/gisgraphy/gishraphoid/AndroidAddressBuilder.java import android.location.Address; import com.gisgraphy.domain.valueobject.GeoNamesAddressDto; import com.gisgraphy.domain.valueobject.Street; import java.util.ArrayList; import java.util.List; import java.util.Locale; package com.gisgraphy.gishraphoid; public class AndroidAddressBuilder { public AndroidAddressBuilder(Locale locale) { } public AndroidAddressBuilder() { } public List<Address> transformStreetsToAndroidAddresses(Street[] result) { ArrayList<Address> ret = new ArrayList<Address>(); for (Street street : result) { Address address = new Address(Locale.getDefault()); if (street.name != null) address.setAddressLine(0, street.name); if (street.isIn != null) address.setLocality(street.isIn); ret.add(address); } return ret; }
public List<Address> transformStreetsToAndroidAddresses(GeoNamesAddressDto[] result) {
robneild/pocket-query-creator
app/src/main/java/com/gisgraphy/gishraphoid/GeoNamesGeocoder.java
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/GeoNamesDto.java // public class GeoNamesDto { // // public GeoNamesAddressDto[] geonames; // // public GeoNamesAddressDto[] getResult() { // return geonames; // } // }
import android.content.Context; import android.location.Address; import com.gisgraphy.domain.valueobject.GeoNamesDto; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map;
* @param maxResults max number of addresses to return. Smaller numbers (1 to 5) * are recommended * @return a list of Address objects. Returns empty list if no matches were * found or there is no backend service available. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 * @throws IOException if the network is unavailable or any other I/O problem occurs */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { if (maxResults < 0) { throw new IllegalArgumentException("maxResults should be positive"); } if (maxResults == 0) { // shortcut filtering return new ArrayList<Address>(); } List<Address> androidAddresses = new ArrayList<Address>(); try { RestClient webService = createRestClient(); // Pass the parameters if needed , if not then pass dummy one as // follows Map<String, String> params = new HashMap<String, String>(); // params.put(COUNTRY_PARAMETER_NAME, iso2countryCode); params.put(LATITUDE_PARAMETER_NAME, latitude + ""); params.put(LONGITUDE_PARAMETER_NAME, longitude + ""); params.put(USERNAME_PARAMETER_NAME, "subvii");
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/GeoNamesDto.java // public class GeoNamesDto { // // public GeoNamesAddressDto[] geonames; // // public GeoNamesAddressDto[] getResult() { // return geonames; // } // } // Path: app/src/main/java/com/gisgraphy/gishraphoid/GeoNamesGeocoder.java import android.content.Context; import android.location.Address; import com.gisgraphy.domain.valueobject.GeoNamesDto; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; * @param maxResults max number of addresses to return. Smaller numbers (1 to 5) * are recommended * @return a list of Address objects. Returns empty list if no matches were * found or there is no backend service available. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 * @throws IOException if the network is unavailable or any other I/O problem occurs */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { if (maxResults < 0) { throw new IllegalArgumentException("maxResults should be positive"); } if (maxResults == 0) { // shortcut filtering return new ArrayList<Address>(); } List<Address> androidAddresses = new ArrayList<Address>(); try { RestClient webService = createRestClient(); // Pass the parameters if needed , if not then pass dummy one as // follows Map<String, String> params = new HashMap<String, String>(); // params.put(COUNTRY_PARAMETER_NAME, iso2countryCode); params.put(LATITUDE_PARAMETER_NAME, latitude + ""); params.put(LONGITUDE_PARAMETER_NAME, longitude + ""); params.put(USERNAME_PARAMETER_NAME, "subvii");
GeoNamesDto response = webService.get(REVERSE_GEOCODING_URI, GeoNamesDto.class, params);
ForeverWJY/CoolQ_Java_Plugin
src/main/java/com/wjyup/coolq/event/PrivateMsgEvent.java
// Path: src/main/java/com/wjyup/coolq/entity/RequestData.java // @Getter // @Setter // public class RequestData implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * <pre> // 代码(Type) 说明 含有的子消息类型(SubType) // 1 私聊信息 11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组 // 2 群消息 1/普通消息 2/匿名消息 3/系统消息 // 4 讨论组信息 目前固定为1 // 11 上传群文件 目前固定为1 // 101 群管理员变动 1/被取消管理员 2/被设置管理员 // 102 群成员减少 1/群员离开 2/群员被踢 3/自己(即登录号)被踢 // 103 群成员增加 1/管理员已同意 2/管理员邀请 // 201 好友已添加 目前固定为1 // 301 请求添加好友 目前固定为1 // 302 请求添加群 1/他人申请入群 2/自己(即登录号)受邀入群 // </pre> // */ // private Integer Type; // /** // * 消息子类型,一般为1 // */ // private Integer SubType; // /** // * 消息来源的QQ/操作者QQ // */ // private Long QQ; // /** // * 消息来源的群号 // */ // private Long Group; // /** // * 消息来源的讨论组号 // */ // private Long Discuss; // /** // * 消息内容,或加群/加好友事件的请求理由 // */ // private String Msg; // /** // * 未转义的字体代码 // */ // private Integer Font; // /** // * 操作的QQ,比如加群时是哪个QQ申请的加群 // */ // private Long beingOperateQQ; // //key token相关校验 // private Long authTime; // private String authToken; // // public RequestData() { // } // } // // Path: src/main/java/com/wjyup/coolq/eventbus/XEvent.java // public interface XEvent { // // }
import com.wjyup.coolq.entity.RequestData; import com.wjyup.coolq.eventbus.XEvent; import lombok.Data;
package com.wjyup.coolq.event; /** * 私聊事件 */ @Data public class PrivateMsgEvent implements XEvent {
// Path: src/main/java/com/wjyup/coolq/entity/RequestData.java // @Getter // @Setter // public class RequestData implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * <pre> // 代码(Type) 说明 含有的子消息类型(SubType) // 1 私聊信息 11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组 // 2 群消息 1/普通消息 2/匿名消息 3/系统消息 // 4 讨论组信息 目前固定为1 // 11 上传群文件 目前固定为1 // 101 群管理员变动 1/被取消管理员 2/被设置管理员 // 102 群成员减少 1/群员离开 2/群员被踢 3/自己(即登录号)被踢 // 103 群成员增加 1/管理员已同意 2/管理员邀请 // 201 好友已添加 目前固定为1 // 301 请求添加好友 目前固定为1 // 302 请求添加群 1/他人申请入群 2/自己(即登录号)受邀入群 // </pre> // */ // private Integer Type; // /** // * 消息子类型,一般为1 // */ // private Integer SubType; // /** // * 消息来源的QQ/操作者QQ // */ // private Long QQ; // /** // * 消息来源的群号 // */ // private Long Group; // /** // * 消息来源的讨论组号 // */ // private Long Discuss; // /** // * 消息内容,或加群/加好友事件的请求理由 // */ // private String Msg; // /** // * 未转义的字体代码 // */ // private Integer Font; // /** // * 操作的QQ,比如加群时是哪个QQ申请的加群 // */ // private Long beingOperateQQ; // //key token相关校验 // private Long authTime; // private String authToken; // // public RequestData() { // } // } // // Path: src/main/java/com/wjyup/coolq/eventbus/XEvent.java // public interface XEvent { // // } // Path: src/main/java/com/wjyup/coolq/event/PrivateMsgEvent.java import com.wjyup.coolq.entity.RequestData; import com.wjyup.coolq.eventbus.XEvent; import lombok.Data; package com.wjyup.coolq.event; /** * 私聊事件 */ @Data public class PrivateMsgEvent implements XEvent {
private RequestData requestData;
ForeverWJY/CoolQ_Java_Plugin
src/main/java/com/wjyup/coolq/util/ConfigCache.java
// Path: src/main/java/com/wjyup/coolq/service/ResolveMessageService.java // public abstract class ResolveMessageService { // public final static Logger log = LogManager.getLogger(ResolveMessageService.class); // // /** // * 用于主动回复消息 // * @param data 收到的消息 // * @param message 回复的消息 // */ // protected void reply(RequestData data, String message){ // switch (data.getType()) { // //私聊消息 // case 1: // CQSDK.sendPrivateMsg(data.getQQ().toString(), message); // break; // //群消息 // case 2: // CQSDK.sendGroupMsg(data.getGroup().toString(), message); // break; // //讨论组信息 // case 4: // CQSDK.sendDiscussMsg(data.getGroup().toString(), message); // break; // } // } // }
import com.wjyup.coolq.service.ResolveMessageService; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List;
package com.wjyup.coolq.util; /** * 静态配置 * * @author WJY */ @Component @Data @Configuration @PropertySource(value = "classpath:data.properties") public class ConfigCache implements InitializingBean { private Logger log = LogManager.getLogger(ConfigCache.class); // 使用Websocket方式推送消息,访问插件的Websocket的Host和Port @Value("${ws.host}") private String WSHost;// websocket的host @Value("${ws.port}") private String WSPort;// websocket的port // 使用HTTP方式推送消息时,访问插件的HTTP地址 @Value("${http.host}") private String HTTP_HOST;// http的host @Value("${http.port}") private String HTTP_PORT;// http的port // 选择推送消息的方式:websocket http @Value("${msg.send.type}") private String MSG_SEND_TYPE; /** * 根据是否设置key的值自动判断 */ private boolean USE_TOKEN;//使用TOKEN // 插件端的设置:扩展功能->数据设置->key @Value("${key}") private String KEY;//key /** * 处理包含CQ码的消息吗? */ @Value("${msg.cq}") private String CQ_MSG; private boolean DO_CQ_MSG; @Value("${coolq.image.path}") private String COOLQ_IMAGE_PATH;//CoolQ 图片文件夹 @Value("${manager.qq}") private String MANAGER_QQ;//管理员QQ,使用逗号分隔 // 管理员QQ列表 private List<Long> ManagerQQList; public boolean ISDEBUG = false;//是否开启debug模式 /** * 存储插件列表 */
// Path: src/main/java/com/wjyup/coolq/service/ResolveMessageService.java // public abstract class ResolveMessageService { // public final static Logger log = LogManager.getLogger(ResolveMessageService.class); // // /** // * 用于主动回复消息 // * @param data 收到的消息 // * @param message 回复的消息 // */ // protected void reply(RequestData data, String message){ // switch (data.getType()) { // //私聊消息 // case 1: // CQSDK.sendPrivateMsg(data.getQQ().toString(), message); // break; // //群消息 // case 2: // CQSDK.sendGroupMsg(data.getGroup().toString(), message); // break; // //讨论组信息 // case 4: // CQSDK.sendDiscussMsg(data.getGroup().toString(), message); // break; // } // } // } // Path: src/main/java/com/wjyup/coolq/util/ConfigCache.java import com.wjyup.coolq.service.ResolveMessageService; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; package com.wjyup.coolq.util; /** * 静态配置 * * @author WJY */ @Component @Data @Configuration @PropertySource(value = "classpath:data.properties") public class ConfigCache implements InitializingBean { private Logger log = LogManager.getLogger(ConfigCache.class); // 使用Websocket方式推送消息,访问插件的Websocket的Host和Port @Value("${ws.host}") private String WSHost;// websocket的host @Value("${ws.port}") private String WSPort;// websocket的port // 使用HTTP方式推送消息时,访问插件的HTTP地址 @Value("${http.host}") private String HTTP_HOST;// http的host @Value("${http.port}") private String HTTP_PORT;// http的port // 选择推送消息的方式:websocket http @Value("${msg.send.type}") private String MSG_SEND_TYPE; /** * 根据是否设置key的值自动判断 */ private boolean USE_TOKEN;//使用TOKEN // 插件端的设置:扩展功能->数据设置->key @Value("${key}") private String KEY;//key /** * 处理包含CQ码的消息吗? */ @Value("${msg.cq}") private String CQ_MSG; private boolean DO_CQ_MSG; @Value("${coolq.image.path}") private String COOLQ_IMAGE_PATH;//CoolQ 图片文件夹 @Value("${manager.qq}") private String MANAGER_QQ;//管理员QQ,使用逗号分隔 // 管理员QQ列表 private List<Long> ManagerQQList; public boolean ISDEBUG = false;//是否开启debug模式 /** * 存储插件列表 */
public static final List<ResolveMessageService> MSG_PLUGIN_LIST = new ArrayList<>();
ForeverWJY/CoolQ_Java_Plugin
src/main/java/com/wjyup/coolq/event/GroupMsgEvent.java
// Path: src/main/java/com/wjyup/coolq/entity/RequestData.java // @Getter // @Setter // public class RequestData implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * <pre> // 代码(Type) 说明 含有的子消息类型(SubType) // 1 私聊信息 11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组 // 2 群消息 1/普通消息 2/匿名消息 3/系统消息 // 4 讨论组信息 目前固定为1 // 11 上传群文件 目前固定为1 // 101 群管理员变动 1/被取消管理员 2/被设置管理员 // 102 群成员减少 1/群员离开 2/群员被踢 3/自己(即登录号)被踢 // 103 群成员增加 1/管理员已同意 2/管理员邀请 // 201 好友已添加 目前固定为1 // 301 请求添加好友 目前固定为1 // 302 请求添加群 1/他人申请入群 2/自己(即登录号)受邀入群 // </pre> // */ // private Integer Type; // /** // * 消息子类型,一般为1 // */ // private Integer SubType; // /** // * 消息来源的QQ/操作者QQ // */ // private Long QQ; // /** // * 消息来源的群号 // */ // private Long Group; // /** // * 消息来源的讨论组号 // */ // private Long Discuss; // /** // * 消息内容,或加群/加好友事件的请求理由 // */ // private String Msg; // /** // * 未转义的字体代码 // */ // private Integer Font; // /** // * 操作的QQ,比如加群时是哪个QQ申请的加群 // */ // private Long beingOperateQQ; // //key token相关校验 // private Long authTime; // private String authToken; // // public RequestData() { // } // } // // Path: src/main/java/com/wjyup/coolq/eventbus/XEvent.java // public interface XEvent { // // }
import com.wjyup.coolq.entity.RequestData; import com.wjyup.coolq.eventbus.XEvent; import lombok.Data;
package com.wjyup.coolq.event; /** * 群聊事件 */ @Data public class GroupMsgEvent implements XEvent {
// Path: src/main/java/com/wjyup/coolq/entity/RequestData.java // @Getter // @Setter // public class RequestData implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * <pre> // 代码(Type) 说明 含有的子消息类型(SubType) // 1 私聊信息 11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组 // 2 群消息 1/普通消息 2/匿名消息 3/系统消息 // 4 讨论组信息 目前固定为1 // 11 上传群文件 目前固定为1 // 101 群管理员变动 1/被取消管理员 2/被设置管理员 // 102 群成员减少 1/群员离开 2/群员被踢 3/自己(即登录号)被踢 // 103 群成员增加 1/管理员已同意 2/管理员邀请 // 201 好友已添加 目前固定为1 // 301 请求添加好友 目前固定为1 // 302 请求添加群 1/他人申请入群 2/自己(即登录号)受邀入群 // </pre> // */ // private Integer Type; // /** // * 消息子类型,一般为1 // */ // private Integer SubType; // /** // * 消息来源的QQ/操作者QQ // */ // private Long QQ; // /** // * 消息来源的群号 // */ // private Long Group; // /** // * 消息来源的讨论组号 // */ // private Long Discuss; // /** // * 消息内容,或加群/加好友事件的请求理由 // */ // private String Msg; // /** // * 未转义的字体代码 // */ // private Integer Font; // /** // * 操作的QQ,比如加群时是哪个QQ申请的加群 // */ // private Long beingOperateQQ; // //key token相关校验 // private Long authTime; // private String authToken; // // public RequestData() { // } // } // // Path: src/main/java/com/wjyup/coolq/eventbus/XEvent.java // public interface XEvent { // // } // Path: src/main/java/com/wjyup/coolq/event/GroupMsgEvent.java import com.wjyup.coolq.entity.RequestData; import com.wjyup.coolq.eventbus.XEvent; import lombok.Data; package com.wjyup.coolq.event; /** * 群聊事件 */ @Data public class GroupMsgEvent implements XEvent {
private RequestData requestData;
ForeverWJY/CoolQ_Java_Plugin
src/main/java/com/wjyup/coolq/util/Predicates.java
// Path: src/main/java/com/wjyup/coolq/exception/PredicateException.java // public class PredicateException extends RuntimeException{ // private static final long serialVersionUID = 1L; // // public PredicateException(String message) { // super(message); // } // } // // Path: src/main/java/com/wjyup/coolq/exception/UnexpectedException.java // public class UnexpectedException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public UnexpectedException(String message) { // super(message); // } // // public UnexpectedException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedException(Throwable cause) { // super(cause); // } // }
import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.collect.Iterables; import com.wjyup.coolq.exception.PredicateException; import com.wjyup.coolq.exception.UnexpectedException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.wjyup.coolq.util; public class Predicates { private static final Pattern IP_PATTERN = Pattern .compile("^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$"); /** * 检查数值范围 * * @param number 数值 * @param min 最小值 * @param max 最大值 * @param msg 消息 * @throws PredicateException */
// Path: src/main/java/com/wjyup/coolq/exception/PredicateException.java // public class PredicateException extends RuntimeException{ // private static final long serialVersionUID = 1L; // // public PredicateException(String message) { // super(message); // } // } // // Path: src/main/java/com/wjyup/coolq/exception/UnexpectedException.java // public class UnexpectedException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public UnexpectedException(String message) { // super(message); // } // // public UnexpectedException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/wjyup/coolq/util/Predicates.java import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.collect.Iterables; import com.wjyup.coolq.exception.PredicateException; import com.wjyup.coolq.exception.UnexpectedException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.wjyup.coolq.util; public class Predicates { private static final Pattern IP_PATTERN = Pattern .compile("^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$"); /** * 检查数值范围 * * @param number 数值 * @param min 最小值 * @param max 最大值 * @param msg 消息 * @throws PredicateException */
public static void ensureNumberRange(int number, int min, int max, String msg) throws PredicateException {
ForeverWJY/CoolQ_Java_Plugin
src/main/java/com/wjyup/coolq/util/Predicates.java
// Path: src/main/java/com/wjyup/coolq/exception/PredicateException.java // public class PredicateException extends RuntimeException{ // private static final long serialVersionUID = 1L; // // public PredicateException(String message) { // super(message); // } // } // // Path: src/main/java/com/wjyup/coolq/exception/UnexpectedException.java // public class UnexpectedException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public UnexpectedException(String message) { // super(message); // } // // public UnexpectedException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedException(Throwable cause) { // super(cause); // } // }
import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.collect.Iterables; import com.wjyup.coolq.exception.PredicateException; import com.wjyup.coolq.exception.UnexpectedException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern;
ensureIn(value, predicates, msg.get()); } private static int compare(Number x, Number y) { if(isSpecial(x) || isSpecial(y)) { return Double.compare(x.doubleValue(), y.doubleValue()); } else { return toBigDecimal(x).compareTo(toBigDecimal(y)); } } private static boolean isSpecial(Number x) { boolean specialDouble = x instanceof Double && (Double.isNaN((Double) x) || Double.isInfinite((Double) x)); boolean specialFloat = x instanceof Float && (Float.isNaN((Float)x) || Float.isInfinite((Float)x)); return specialDouble || specialFloat; } private static BigDecimal toBigDecimal(Number number) { if(number instanceof BigDecimal) { return (BigDecimal) number; } else if(number instanceof BigInteger) { return new BigDecimal((BigInteger) number); } else if(number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) { return new BigDecimal(number.longValue()); } else if(number instanceof Float || number instanceof Double) { return new BigDecimal(number.doubleValue()); } else { try { return new BigDecimal(number.toString()); } catch(final NumberFormatException e) {
// Path: src/main/java/com/wjyup/coolq/exception/PredicateException.java // public class PredicateException extends RuntimeException{ // private static final long serialVersionUID = 1L; // // public PredicateException(String message) { // super(message); // } // } // // Path: src/main/java/com/wjyup/coolq/exception/UnexpectedException.java // public class UnexpectedException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public UnexpectedException(String message) { // super(message); // } // // public UnexpectedException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/wjyup/coolq/util/Predicates.java import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.collect.Iterables; import com.wjyup.coolq.exception.PredicateException; import com.wjyup.coolq.exception.UnexpectedException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; ensureIn(value, predicates, msg.get()); } private static int compare(Number x, Number y) { if(isSpecial(x) || isSpecial(y)) { return Double.compare(x.doubleValue(), y.doubleValue()); } else { return toBigDecimal(x).compareTo(toBigDecimal(y)); } } private static boolean isSpecial(Number x) { boolean specialDouble = x instanceof Double && (Double.isNaN((Double) x) || Double.isInfinite((Double) x)); boolean specialFloat = x instanceof Float && (Float.isNaN((Float)x) || Float.isInfinite((Float)x)); return specialDouble || specialFloat; } private static BigDecimal toBigDecimal(Number number) { if(number instanceof BigDecimal) { return (BigDecimal) number; } else if(number instanceof BigInteger) { return new BigDecimal((BigInteger) number); } else if(number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) { return new BigDecimal(number.longValue()); } else if(number instanceof Float || number instanceof Double) { return new BigDecimal(number.doubleValue()); } else { try { return new BigDecimal(number.toString()); } catch(final NumberFormatException e) {
throw new UnexpectedException(String.format("数值%s(类型%s)无法转换为合法的字符串", number.toString(), number.getClass().getName()), e);
ForeverWJY/CoolQ_Java_Plugin
src/test/java/junit/SpringJunit.java
// Path: src/main/java/com/wjyup/coolq/MainApp.java // @SpringBootApplication // @EnableTransactionManagement // public class MainApp { // private static final Logger log = LogManager.getLogger(MainApp.class); // // @Bean // public TaskExecutor taskExecutor() { // ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // executor.setCorePoolSize(5); // executor.setMaxPoolSize(10); // executor.setQueueCapacity(25); // return executor; // } // // public static void main(String[] args) { // SpringApplication.run(MainApp.class,args); // } // } // // Path: src/main/java/com/wjyup/coolq/entity/RequestData.java // @Getter // @Setter // public class RequestData implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * <pre> // 代码(Type) 说明 含有的子消息类型(SubType) // 1 私聊信息 11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组 // 2 群消息 1/普通消息 2/匿名消息 3/系统消息 // 4 讨论组信息 目前固定为1 // 11 上传群文件 目前固定为1 // 101 群管理员变动 1/被取消管理员 2/被设置管理员 // 102 群成员减少 1/群员离开 2/群员被踢 3/自己(即登录号)被踢 // 103 群成员增加 1/管理员已同意 2/管理员邀请 // 201 好友已添加 目前固定为1 // 301 请求添加好友 目前固定为1 // 302 请求添加群 1/他人申请入群 2/自己(即登录号)受邀入群 // </pre> // */ // private Integer Type; // /** // * 消息子类型,一般为1 // */ // private Integer SubType; // /** // * 消息来源的QQ/操作者QQ // */ // private Long QQ; // /** // * 消息来源的群号 // */ // private Long Group; // /** // * 消息来源的讨论组号 // */ // private Long Discuss; // /** // * 消息内容,或加群/加好友事件的请求理由 // */ // private String Msg; // /** // * 未转义的字体代码 // */ // private Integer Font; // /** // * 操作的QQ,比如加群时是哪个QQ申请的加群 // */ // private Long beingOperateQQ; // //key token相关校验 // private Long authTime; // private String authToken; // // public RequestData() { // } // }
import com.wjyup.coolq.MainApp; import com.wjyup.coolq.entity.RequestData; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner;
package junit; @RunWith(SpringRunner.class) @SpringBootTest(classes = {MainApp.class}) //相当于 --spring.profiles.active=dev @ActiveProfiles(value="dev") public class SpringJunit { private final Logger log = LogManager.getLogger("SpringJunit");
// Path: src/main/java/com/wjyup/coolq/MainApp.java // @SpringBootApplication // @EnableTransactionManagement // public class MainApp { // private static final Logger log = LogManager.getLogger(MainApp.class); // // @Bean // public TaskExecutor taskExecutor() { // ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // executor.setCorePoolSize(5); // executor.setMaxPoolSize(10); // executor.setQueueCapacity(25); // return executor; // } // // public static void main(String[] args) { // SpringApplication.run(MainApp.class,args); // } // } // // Path: src/main/java/com/wjyup/coolq/entity/RequestData.java // @Getter // @Setter // public class RequestData implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * <pre> // 代码(Type) 说明 含有的子消息类型(SubType) // 1 私聊信息 11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组 // 2 群消息 1/普通消息 2/匿名消息 3/系统消息 // 4 讨论组信息 目前固定为1 // 11 上传群文件 目前固定为1 // 101 群管理员变动 1/被取消管理员 2/被设置管理员 // 102 群成员减少 1/群员离开 2/群员被踢 3/自己(即登录号)被踢 // 103 群成员增加 1/管理员已同意 2/管理员邀请 // 201 好友已添加 目前固定为1 // 301 请求添加好友 目前固定为1 // 302 请求添加群 1/他人申请入群 2/自己(即登录号)受邀入群 // </pre> // */ // private Integer Type; // /** // * 消息子类型,一般为1 // */ // private Integer SubType; // /** // * 消息来源的QQ/操作者QQ // */ // private Long QQ; // /** // * 消息来源的群号 // */ // private Long Group; // /** // * 消息来源的讨论组号 // */ // private Long Discuss; // /** // * 消息内容,或加群/加好友事件的请求理由 // */ // private String Msg; // /** // * 未转义的字体代码 // */ // private Integer Font; // /** // * 操作的QQ,比如加群时是哪个QQ申请的加群 // */ // private Long beingOperateQQ; // //key token相关校验 // private Long authTime; // private String authToken; // // public RequestData() { // } // } // Path: src/test/java/junit/SpringJunit.java import com.wjyup.coolq.MainApp; import com.wjyup.coolq.entity.RequestData; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; package junit; @RunWith(SpringRunner.class) @SpringBootTest(classes = {MainApp.class}) //相当于 --spring.profiles.active=dev @ActiveProfiles(value="dev") public class SpringJunit { private final Logger log = LogManager.getLogger("SpringJunit");
private RequestData requestData = new RequestData();
memo33/jDBPFX
src/jdbpfx/util/DBPFUtil.java
// Path: src/jdbpfx/properties/DBPFPropertyType.java // public enum DBPFPropertyType { // UINT8 ((short) 0x0100, "Uint8", 1), // UINT16 ((short) 0x0200, "Uint16", 2), // UINT32 ((short) 0x0300, "Uint32", 4), // SINT32 ((short) 0x0700, "Sint32", 4), // SINT64 ((short) 0x0800, "Sint64", 8), // FLOAT32((short) 0x0900, "Float32", 4), // BOOL ((short) 0x0B00, "Bool", 1), // STRING ((short) 0x0C00, "String", 1); // // /** A map of data type IDs ({@link #id}) to PropertyType constants. */ // public static final Map<Short, DBPFPropertyType> forID; // // static { // HashMap<Short, DBPFPropertyType> modifiable = new HashMap<Short, DBPFPropertyType>( // DBPFPropertyType.values().length); // // for (DBPFPropertyType type : DBPFPropertyType.values()) // modifiable.put(type.id, type); // // forID = Collections.unmodifiableMap(modifiable); // } // // public final short id; // public final String name; // public final int length; // // private DBPFPropertyType(short id, String name, int length) { // this.id = id; // this.name = name; // this.length = length; // } // // @Override // public String toString() { // return name; // } // }
import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import java.util.logging.Logger; import jdbpfx.properties.DBPFPropertyType;
long result = 0; hexString = hexString.toLowerCase(); if (hexString.startsWith("0x")) { hexString = hexString.substring(2); } result = Long.parseLong(hexString, 16); if(signed) { long signBit = 1L << ((hexString.length() * 4) - 1); if((result & signBit) == signBit) { result |= ~(signBit * 2 - 1); } } return result; } /** * Reads a value till length reached.<br> * * @param type * PropertyType.SINT32 or PropertyType.SINT64 for signed values; * Otherwise for unsigned * @param data * The data * @param start * The start offset * @param length * The length * * @return A long value */
// Path: src/jdbpfx/properties/DBPFPropertyType.java // public enum DBPFPropertyType { // UINT8 ((short) 0x0100, "Uint8", 1), // UINT16 ((short) 0x0200, "Uint16", 2), // UINT32 ((short) 0x0300, "Uint32", 4), // SINT32 ((short) 0x0700, "Sint32", 4), // SINT64 ((short) 0x0800, "Sint64", 8), // FLOAT32((short) 0x0900, "Float32", 4), // BOOL ((short) 0x0B00, "Bool", 1), // STRING ((short) 0x0C00, "String", 1); // // /** A map of data type IDs ({@link #id}) to PropertyType constants. */ // public static final Map<Short, DBPFPropertyType> forID; // // static { // HashMap<Short, DBPFPropertyType> modifiable = new HashMap<Short, DBPFPropertyType>( // DBPFPropertyType.values().length); // // for (DBPFPropertyType type : DBPFPropertyType.values()) // modifiable.put(type.id, type); // // forID = Collections.unmodifiableMap(modifiable); // } // // public final short id; // public final String name; // public final int length; // // private DBPFPropertyType(short id, String name, int length) { // this.id = id; // this.name = name; // this.length = length; // } // // @Override // public String toString() { // return name; // } // } // Path: src/jdbpfx/util/DBPFUtil.java import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import java.util.logging.Logger; import jdbpfx.properties.DBPFPropertyType; long result = 0; hexString = hexString.toLowerCase(); if (hexString.startsWith("0x")) { hexString = hexString.substring(2); } result = Long.parseLong(hexString, 16); if(signed) { long signBit = 1L << ((hexString.length() * 4) - 1); if((result & signBit) == signBit) { result |= ~(signBit * 2 - 1); } } return result; } /** * Reads a value till length reached.<br> * * @param type * PropertyType.SINT32 or PropertyType.SINT64 for signed values; * Otherwise for unsigned * @param data * The data * @param start * The start offset * @param length * The length * * @return A long value */
public static long getValue(DBPFPropertyType type, byte[] data, int start, int length) {
jskcse4/FreeTamilEBooks
src/com/jskaleel/abstracts/BasicFragment.java
// Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // }
import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import com.jskaleel.fte.common.UIProgressLoading;
package com.jskaleel.abstracts; public class BasicFragment extends Fragment{ public AlertDialog alertDialog;
// Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // } // Path: src/com/jskaleel/abstracts/BasicFragment.java import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import com.jskaleel.fte.common.UIProgressLoading; package com.jskaleel.abstracts; public class BasicFragment extends Fragment{ public AlertDialog alertDialog;
public UIProgressLoading uiProgressLoading;
jskcse4/FreeTamilEBooks
src/com/jskaleel/fte/app/FTEApplication.java
// Path: src/com/jskaleel/fte/common/LruBitmapCache.java // public class LruBitmapCache extends LruCache<String, Bitmap> implements // ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / 8; // // return cacheSize; // } // // public LruBitmapCache() { // this(getDefaultLruCacheSize()); // } // // public LruBitmapCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // }
import android.app.Application; import android.content.Context; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; import com.jskaleel.fte.common.LruBitmapCache;
@Override public void onCreate() { super.onCreate(); mInstance = this; this.setAppContext(getApplicationContext()); } public static FTEApplication getInstance(){ return mInstance; } public static Context getAppContext() { return mAppContext; } public void setAppContext(Context mAppContext) { FTEApplication.mAppContext = mAppContext; } public RequestQueue getRequestQueue(){ if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(getApplicationContext()); } return this.mRequestQueue; } public ImageLoader getImageLoader(){ getRequestQueue(); if (mImageLoader == null) {
// Path: src/com/jskaleel/fte/common/LruBitmapCache.java // public class LruBitmapCache extends LruCache<String, Bitmap> implements // ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / 8; // // return cacheSize; // } // // public LruBitmapCache() { // this(getDefaultLruCacheSize()); // } // // public LruBitmapCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // } // Path: src/com/jskaleel/fte/app/FTEApplication.java import android.app.Application; import android.content.Context; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; import com.jskaleel.fte.common.LruBitmapCache; @Override public void onCreate() { super.onCreate(); mInstance = this; this.setAppContext(getApplicationContext()); } public static FTEApplication getInstance(){ return mInstance; } public static Context getAppContext() { return mAppContext; } public void setAppContext(Context mAppContext) { FTEApplication.mAppContext = mAppContext; } public RequestQueue getRequestQueue(){ if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(getApplicationContext()); } return this.mRequestQueue; } public ImageLoader getImageLoader(){ getRequestQueue(); if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
jskcse4/FreeTamilEBooks
src/com/jskaleel/abstracts/BasicActivity.java
// Path: src/com/jskaleel/fte/common/ConnectionDetector.java // public class ConnectionDetector { // // private Context _context; // // // public ConnectionDetector(Context context) { // this._context = context; // } // // public boolean isConnectingToInternet() // { // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // { // for (int i = 0; i < info.length; i++) // { // if (info[i].getState() == NetworkInfo.State.CONNECTED) // { // return true; // } // } // } // // } // return false; // } // // // // } // // Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // // Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // }
import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import com.jskaleel.fte.common.ConnectionDetector; import com.jskaleel.fte.common.PrintLog; import com.jskaleel.fte.common.UIProgressLoading;
package com.jskaleel.abstracts; public class BasicActivity extends FragmentActivity{ public AlertDialog alertDialog; // public ProgressDialog progressDialog;
// Path: src/com/jskaleel/fte/common/ConnectionDetector.java // public class ConnectionDetector { // // private Context _context; // // // public ConnectionDetector(Context context) { // this._context = context; // } // // public boolean isConnectingToInternet() // { // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // { // for (int i = 0; i < info.length; i++) // { // if (info[i].getState() == NetworkInfo.State.CONNECTED) // { // return true; // } // } // } // // } // return false; // } // // // // } // // Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // // Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // } // Path: src/com/jskaleel/abstracts/BasicActivity.java import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import com.jskaleel.fte.common.ConnectionDetector; import com.jskaleel.fte.common.PrintLog; import com.jskaleel.fte.common.UIProgressLoading; package com.jskaleel.abstracts; public class BasicActivity extends FragmentActivity{ public AlertDialog alertDialog; // public ProgressDialog progressDialog;
public UIProgressLoading uiProgressLoading;
jskcse4/FreeTamilEBooks
src/com/jskaleel/abstracts/BasicActivity.java
// Path: src/com/jskaleel/fte/common/ConnectionDetector.java // public class ConnectionDetector { // // private Context _context; // // // public ConnectionDetector(Context context) { // this._context = context; // } // // public boolean isConnectingToInternet() // { // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // { // for (int i = 0; i < info.length; i++) // { // if (info[i].getState() == NetworkInfo.State.CONNECTED) // { // return true; // } // } // } // // } // return false; // } // // // // } // // Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // // Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // }
import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import com.jskaleel.fte.common.ConnectionDetector; import com.jskaleel.fte.common.PrintLog; import com.jskaleel.fte.common.UIProgressLoading;
package com.jskaleel.abstracts; public class BasicActivity extends FragmentActivity{ public AlertDialog alertDialog; // public ProgressDialog progressDialog; public UIProgressLoading uiProgressLoading; public static Boolean isAppRunningBackground = false; public static String TAG = "BasicActivity"; public boolean doubleBackToExitPressedOnce; //Connection Detectors public Boolean isInternetAvailable = false;
// Path: src/com/jskaleel/fte/common/ConnectionDetector.java // public class ConnectionDetector { // // private Context _context; // // // public ConnectionDetector(Context context) { // this._context = context; // } // // public boolean isConnectingToInternet() // { // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // { // for (int i = 0; i < info.length; i++) // { // if (info[i].getState() == NetworkInfo.State.CONNECTED) // { // return true; // } // } // } // // } // return false; // } // // // // } // // Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // // Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // } // Path: src/com/jskaleel/abstracts/BasicActivity.java import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import com.jskaleel.fte.common.ConnectionDetector; import com.jskaleel.fte.common.PrintLog; import com.jskaleel.fte.common.UIProgressLoading; package com.jskaleel.abstracts; public class BasicActivity extends FragmentActivity{ public AlertDialog alertDialog; // public ProgressDialog progressDialog; public UIProgressLoading uiProgressLoading; public static Boolean isAppRunningBackground = false; public static String TAG = "BasicActivity"; public boolean doubleBackToExitPressedOnce; //Connection Detectors public Boolean isInternetAvailable = false;
public ConnectionDetector connectionDetector;
jskcse4/FreeTamilEBooks
src/com/jskaleel/abstracts/BasicActivity.java
// Path: src/com/jskaleel/fte/common/ConnectionDetector.java // public class ConnectionDetector { // // private Context _context; // // // public ConnectionDetector(Context context) { // this._context = context; // } // // public boolean isConnectingToInternet() // { // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // { // for (int i = 0; i < info.length; i++) // { // if (info[i].getState() == NetworkInfo.State.CONNECTED) // { // return true; // } // } // } // // } // return false; // } // // // // } // // Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // // Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // }
import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import com.jskaleel.fte.common.ConnectionDetector; import com.jskaleel.fte.common.PrintLog; import com.jskaleel.fte.common.UIProgressLoading;
alertDialogBuilder.setCancelable(false); alertDialogBuilder.setNeutralButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); alertDialogBuilder.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ dialog.dismiss(); finish(); } return false; } }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override protected void onPause() { isAppRunningBackground = true;
// Path: src/com/jskaleel/fte/common/ConnectionDetector.java // public class ConnectionDetector { // // private Context _context; // // // public ConnectionDetector(Context context) { // this._context = context; // } // // public boolean isConnectingToInternet() // { // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // { // for (int i = 0; i < info.length; i++) // { // if (info[i].getState() == NetworkInfo.State.CONNECTED) // { // return true; // } // } // } // // } // return false; // } // // // // } // // Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // // Path: src/com/jskaleel/fte/common/UIProgressLoading.java // public class UIProgressLoading { // // public ProgressLoading progressLoading; // public Activity activity; // public void init(Activity context){ // progressLoading = new ProgressLoading(context); // activity = context; // } // public void showProgressLoading(String msg){ // progressLoading.getDialog(msg, false); // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // progressLoading.show(); // } // public void stop() { // if(progressLoading != null && progressLoading.isShowing()){ // progressLoading.dismiss(); // } // } // } // Path: src/com/jskaleel/abstracts/BasicActivity.java import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import com.jskaleel.fte.common.ConnectionDetector; import com.jskaleel.fte.common.PrintLog; import com.jskaleel.fte.common.UIProgressLoading; alertDialogBuilder.setCancelable(false); alertDialogBuilder.setNeutralButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); alertDialogBuilder.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ dialog.dismiss(); finish(); } return false; } }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override protected void onPause() { isAppRunningBackground = true;
PrintLog.debug(TAG, "isAppRunningBackground onPause: "+isAppRunningBackground);
jskcse4/FreeTamilEBooks
src/com/jskaleel/http/HttpGetConnection.java
// Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // }
import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import com.jskaleel.fte.common.PrintLog;
package com.jskaleel.http; public class HttpGetConnection { public static String HTTP_LOG = "HttpConnection"; public static UrlResponse getRequest(String url) { UrlResponse response = new UrlResponse(); HttpClient httpclient = new DefaultHttpClient();
// Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // Path: src/com/jskaleel/http/HttpGetConnection.java import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import com.jskaleel.fte.common.PrintLog; package com.jskaleel.http; public class HttpGetConnection { public static String HTTP_LOG = "HttpConnection"; public static UrlResponse getRequest(String url) { UrlResponse response = new UrlResponse(); HttpClient httpclient = new DefaultHttpClient();
PrintLog.debug("URL", "---->"+url);
jskcse4/FreeTamilEBooks
src/com/jskaleel/http/HttpUtils.java
// Path: src/com/jskaleel/fte/common/TextUtils.java // public class TextUtils { // // public static final String encodeToBase64(CharSequence content){ // byte[] bytes = Base64.encode(content.toString().getBytes(), Base64.DEFAULT); // return new String(bytes); // } // // public static final String decodeBase64(String base64String){ // try { // return new String(Base64.decode(base64String, Base64.DEFAULT)); // } catch (Exception e) { // e.printStackTrace(); // } // // return base64String; // } // // public static boolean isNullOrEmpty(String value){ // return value == null || value.trim().equals(""); // } // // public static boolean isNullOrEmpty(CharSequence value){ // return value == null || value.toString().equals(""); // } // // public static boolean isEmpty(TextView txt){ // String text = txt.getText().toString().trim(); // return text.length() <= 0; // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpStatus; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import com.jskaleel.fte.common.TextUtils;
} } catch (JSONException e) { e.printStackTrace(); } } return isErrorcode; } public static UrlResponse getResponse(int responseCode, String content){ UrlResponse response = new UrlResponse(); response.setResposeCode(responseCode); String errorMsg = HttpUtils.getErrorMsg(content); if(responseCode == HttpStatus.SC_CREATED || responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_TEMPORARILY){ if(HttpUtils.isError(content)){ response.setErrorMsg(errorMsg); response.setErrorCode(getErrorCode(content)); } else{ response.setContent(content); } } else { response.setErrorMsg(errorMsg); } try { int errorCode = -1;
// Path: src/com/jskaleel/fte/common/TextUtils.java // public class TextUtils { // // public static final String encodeToBase64(CharSequence content){ // byte[] bytes = Base64.encode(content.toString().getBytes(), Base64.DEFAULT); // return new String(bytes); // } // // public static final String decodeBase64(String base64String){ // try { // return new String(Base64.decode(base64String, Base64.DEFAULT)); // } catch (Exception e) { // e.printStackTrace(); // } // // return base64String; // } // // public static boolean isNullOrEmpty(String value){ // return value == null || value.trim().equals(""); // } // // public static boolean isNullOrEmpty(CharSequence value){ // return value == null || value.toString().equals(""); // } // // public static boolean isEmpty(TextView txt){ // String text = txt.getText().toString().trim(); // return text.length() <= 0; // } // // } // Path: src/com/jskaleel/http/HttpUtils.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpStatus; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import com.jskaleel.fte.common.TextUtils; } } catch (JSONException e) { e.printStackTrace(); } } return isErrorcode; } public static UrlResponse getResponse(int responseCode, String content){ UrlResponse response = new UrlResponse(); response.setResposeCode(responseCode); String errorMsg = HttpUtils.getErrorMsg(content); if(responseCode == HttpStatus.SC_CREATED || responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_TEMPORARILY){ if(HttpUtils.isError(content)){ response.setErrorMsg(errorMsg); response.setErrorCode(getErrorCode(content)); } else{ response.setContent(content); } } else { response.setErrorMsg(errorMsg); } try { int errorCode = -1;
if(!TextUtils.isNullOrEmpty(content)){
jskcse4/FreeTamilEBooks
src/com/jskaleel/http/HttpGetUrlConnection.java
// Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // }
import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import com.jskaleel.fte.common.PrintLog;
package com.jskaleel.http; public class HttpGetUrlConnection { public HttpGetUrlConnection(){ } public static String getContentFromUrl(String api_url) throws UnsupportedEncodingException{ HttpURLConnection conn = null; StringBuilder jsonResults = new StringBuilder(); UrlResponse response = new UrlResponse(); String content = null; try { StringBuilder sb = new StringBuilder(api_url); HttpURLConnection.setFollowRedirects(true); URL url = new URL(sb.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); InputStreamReader in = new InputStreamReader(conn.getInputStream()); int statusCode = conn.getResponseCode(); int read; char[] buff = new char[1024]; while ((read = in.read(buff)) != -1) { jsonResults.append(buff, 0, read); } content = jsonResults.toString(); response = HttpUtils.getResponse(statusCode, content);
// Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // Path: src/com/jskaleel/http/HttpGetUrlConnection.java import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import com.jskaleel.fte.common.PrintLog; package com.jskaleel.http; public class HttpGetUrlConnection { public HttpGetUrlConnection(){ } public static String getContentFromUrl(String api_url) throws UnsupportedEncodingException{ HttpURLConnection conn = null; StringBuilder jsonResults = new StringBuilder(); UrlResponse response = new UrlResponse(); String content = null; try { StringBuilder sb = new StringBuilder(api_url); HttpURLConnection.setFollowRedirects(true); URL url = new URL(sb.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); InputStreamReader in = new InputStreamReader(conn.getInputStream()); int statusCode = conn.getResponseCode(); int read; char[] buff = new char[1024]; while ((read = in.read(buff)) != -1) { jsonResults.append(buff, 0, read); } content = jsonResults.toString(); response = HttpUtils.getResponse(statusCode, content);
PrintLog.debug("HttpGerUrl", "Response: "+content);
jskcse4/FreeTamilEBooks
src/com/jskaleel/fte/common/FTEDevice.java
// Path: src/com/jskaleel/fte/AppPreference.java // public class AppPreference extends Application { // // // public static final String PREFS_NAME = "app_preference"; // public static final String IS_OPEN_FIRSTTIME = "open firsttime"; // // private SharedPreferences mPrefrence; // private SharedPreferences.Editor mEditor; // // public AppPreference(Context mContext){ // String packageName = mContext.getPackageName(); // mPrefrence = mContext.getSharedPreferences(packageName + "." + PREFS_NAME, Context.MODE_PRIVATE); // mEditor = mPrefrence.edit(); // } // // public void setIsOpenFirstTime(boolean isPosteredInterview){ // mEditor.putBoolean(IS_OPEN_FIRSTTIME, isPosteredInterview); // mEditor.commit(); // } // // public boolean getIsOpenFirstTime() { // return mPrefrence.getBoolean(IS_OPEN_FIRSTTIME, true); // } // }
import android.app.Application; import android.content.Context; import android.os.Build; import android.os.Build.VERSION_CODES; import android.util.TypedValue; import com.jskaleel.fte.AppPreference;
package com.jskaleel.fte.common; public class FTEDevice extends Application { // public static boolean GTE_GB_9 = false; // public static boolean GTE_GB_10 = false; public static boolean GTE_HC_11 = false; // public static boolean GTE_HC_12 = false; // public static boolean GTE_HC_13 = false; // public static boolean GTE_ICS_14 = false; // public static boolean GTE_ICS_15 = false; // public static boolean GTE_JB_16 = false; // public static boolean GTE_JB_17 = false; // public static boolean GTE_JB_18 = false; // public static boolean PRE_GB_9 = false; // public static boolean PRE_GB_10 = false; public static boolean PRE_HC_11 = false; // public static boolean PRE_HC_12 = false; // public static boolean PRE_HC_13 = false;
// Path: src/com/jskaleel/fte/AppPreference.java // public class AppPreference extends Application { // // // public static final String PREFS_NAME = "app_preference"; // public static final String IS_OPEN_FIRSTTIME = "open firsttime"; // // private SharedPreferences mPrefrence; // private SharedPreferences.Editor mEditor; // // public AppPreference(Context mContext){ // String packageName = mContext.getPackageName(); // mPrefrence = mContext.getSharedPreferences(packageName + "." + PREFS_NAME, Context.MODE_PRIVATE); // mEditor = mPrefrence.edit(); // } // // public void setIsOpenFirstTime(boolean isPosteredInterview){ // mEditor.putBoolean(IS_OPEN_FIRSTTIME, isPosteredInterview); // mEditor.commit(); // } // // public boolean getIsOpenFirstTime() { // return mPrefrence.getBoolean(IS_OPEN_FIRSTTIME, true); // } // } // Path: src/com/jskaleel/fte/common/FTEDevice.java import android.app.Application; import android.content.Context; import android.os.Build; import android.os.Build.VERSION_CODES; import android.util.TypedValue; import com.jskaleel.fte.AppPreference; package com.jskaleel.fte.common; public class FTEDevice extends Application { // public static boolean GTE_GB_9 = false; // public static boolean GTE_GB_10 = false; public static boolean GTE_HC_11 = false; // public static boolean GTE_HC_12 = false; // public static boolean GTE_HC_13 = false; // public static boolean GTE_ICS_14 = false; // public static boolean GTE_ICS_15 = false; // public static boolean GTE_JB_16 = false; // public static boolean GTE_JB_17 = false; // public static boolean GTE_JB_18 = false; // public static boolean PRE_GB_9 = false; // public static boolean PRE_GB_10 = false; public static boolean PRE_HC_11 = false; // public static boolean PRE_HC_12 = false; // public static boolean PRE_HC_13 = false;
private static AppPreference mUserPrefrence;
jskcse4/FreeTamilEBooks
src/com/jskaleel/http/HttpUrlConnection.java
// Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // }
import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import com.jskaleel.fte.common.PrintLog;
package com.jskaleel.http; public class HttpUrlConnection { private static final String TAG = "HttpUrlConnection"; public HttpUrlConnection(){ } public static String getContentFromUrl(String api_url) throws UnsupportedEncodingException{ HttpURLConnection conn = null; StringBuilder jsonResults = new StringBuilder(); try { StringBuilder sb = new StringBuilder(api_url);
// Path: src/com/jskaleel/fte/common/PrintLog.java // public class PrintLog { // // public static void debug(String TAG,String str) { // if(str.length() > 4000) // { // Log.d("FTE",TAG+" ---> " + str.substring(0, 4000)); // debug(TAG,str.substring(4000)); // } else // { // Log.d("FTE",TAG+ " ---->" +str); // } // } // public static void error(String TAG,String str) { // if(str.length() > 4000) // { // Log.e("FTE",TAG +" ---> " + str.substring(0, 4000)); // error(TAG,str.substring(4000)); // } // else // { // Log.e("FTE",TAG+ " ---->" +str); // } // } // // } // Path: src/com/jskaleel/http/HttpUrlConnection.java import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import com.jskaleel.fte.common.PrintLog; package com.jskaleel.http; public class HttpUrlConnection { private static final String TAG = "HttpUrlConnection"; public HttpUrlConnection(){ } public static String getContentFromUrl(String api_url) throws UnsupportedEncodingException{ HttpURLConnection conn = null; StringBuilder jsonResults = new StringBuilder(); try { StringBuilder sb = new StringBuilder(api_url);
PrintLog.debug("HttpUrlConnection", "getContentFromUrl Url: "+api_url);
MatteoJoliveau/PlugFace
plugface-core/src/main/java/org/plugface/core/internal/DependencyResolver.java
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Graph.java // public class Graph { // // private Set<Node> all = new HashSet<>(); // private Map<Node, List<Node>> adj = new HashMap<>(); // // public Graph addLeaf(Node<?> node) { // addEdge(node, null); // return this; // } // // public Graph addEdges(Node<?> node, Collection<Node<?>> adjs) { // for (Node<?> adj : adjs) { // addEdge(node, adj); // } // return this; // } // // public Graph addEdge(Node<?> node, Node<?> adj) { // Objects.requireNonNull(node, "Cannot attach an edge to a null node"); // if (Objects.equals(node, adj)) { // throw new IllegalArgumentException("Cannot connect a node to itself"); // } // register(node); // register(adj); // checkCircularDependency(node, adj); // this.adj.get(node).add(adj); // return this; // } // // private void register(Node<?> node) { // if (node != null) { // all.add(node); // if (!this.adj.containsKey(node)) { // this.adj.put(node, new ArrayList<Node>(0)); // } // } // } // // private void checkCircularDependency(Node<?> node, Node<?> adj) { // final List<Node> twoDep = this.adj.get(adj); // // if (twoDep == null) return; // // if (twoDep.contains(node)) { // // throw new CircularDependencyException("Circular Dependency detected: %s <----> %s", node, adj); // } // // // } // // public Collection<Node<?>> resolve() { // return topologicalSort(); // } // // private Collection<Node<?>> topologicalSort() { // final Stack<Node> stack = new Stack<>(); // final Map<Node, Boolean> visited = new HashMap<>(); // for (Node node : all) { // visited.put(node, false); // } // // for (Node node : all) { // if (!visited.get(node)) { // doTopologicalSort(node, visited, stack); // } // } // final List<Node<?>> classes = new ArrayList<>(); // for (Node node : stack) { // classes.add(node); // } // return classes; // } // // private void doTopologicalSort(Node<?> node, Map<Node, Boolean> visited, Stack<Node> stack) { // visited.put(node, true); // // final List<Node> deps = adj.get(node); // for (Node dep : deps) { // final Boolean vis = visited.get(dep); // if (vis != null && !vis) { // doTopologicalSort(dep, visited, stack); // } // } // stack.push(node); // } // } // // Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // }
import org.plugface.core.internal.di.Graph; import org.plugface.core.internal.di.Node; import java.util.Collection;
package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ /** * Internal class used to create a dependency graph * for plugin dependency injection. */ public class DependencyResolver { private final AnnotationProcessor processor; public DependencyResolver(AnnotationProcessor processor) { this.processor = processor; }
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Graph.java // public class Graph { // // private Set<Node> all = new HashSet<>(); // private Map<Node, List<Node>> adj = new HashMap<>(); // // public Graph addLeaf(Node<?> node) { // addEdge(node, null); // return this; // } // // public Graph addEdges(Node<?> node, Collection<Node<?>> adjs) { // for (Node<?> adj : adjs) { // addEdge(node, adj); // } // return this; // } // // public Graph addEdge(Node<?> node, Node<?> adj) { // Objects.requireNonNull(node, "Cannot attach an edge to a null node"); // if (Objects.equals(node, adj)) { // throw new IllegalArgumentException("Cannot connect a node to itself"); // } // register(node); // register(adj); // checkCircularDependency(node, adj); // this.adj.get(node).add(adj); // return this; // } // // private void register(Node<?> node) { // if (node != null) { // all.add(node); // if (!this.adj.containsKey(node)) { // this.adj.put(node, new ArrayList<Node>(0)); // } // } // } // // private void checkCircularDependency(Node<?> node, Node<?> adj) { // final List<Node> twoDep = this.adj.get(adj); // // if (twoDep == null) return; // // if (twoDep.contains(node)) { // // throw new CircularDependencyException("Circular Dependency detected: %s <----> %s", node, adj); // } // // // } // // public Collection<Node<?>> resolve() { // return topologicalSort(); // } // // private Collection<Node<?>> topologicalSort() { // final Stack<Node> stack = new Stack<>(); // final Map<Node, Boolean> visited = new HashMap<>(); // for (Node node : all) { // visited.put(node, false); // } // // for (Node node : all) { // if (!visited.get(node)) { // doTopologicalSort(node, visited, stack); // } // } // final List<Node<?>> classes = new ArrayList<>(); // for (Node node : stack) { // classes.add(node); // } // return classes; // } // // private void doTopologicalSort(Node<?> node, Map<Node, Boolean> visited, Stack<Node> stack) { // visited.put(node, true); // // final List<Node> deps = adj.get(node); // for (Node dep : deps) { // final Boolean vis = visited.get(dep); // if (vis != null && !vis) { // doTopologicalSort(dep, visited, stack); // } // } // stack.push(node); // } // } // // Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // Path: plugface-core/src/main/java/org/plugface/core/internal/DependencyResolver.java import org.plugface.core.internal.di.Graph; import org.plugface.core.internal.di.Node; import java.util.Collection; package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ /** * Internal class used to create a dependency graph * for plugin dependency injection. */ public class DependencyResolver { private final AnnotationProcessor processor; public DependencyResolver(AnnotationProcessor processor) { this.processor = processor; }
public Collection<Node<?>> resolve(Collection<Class<?>> pluginClasses) {
MatteoJoliveau/PlugFace
plugface-core/src/main/java/org/plugface/core/internal/DependencyResolver.java
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Graph.java // public class Graph { // // private Set<Node> all = new HashSet<>(); // private Map<Node, List<Node>> adj = new HashMap<>(); // // public Graph addLeaf(Node<?> node) { // addEdge(node, null); // return this; // } // // public Graph addEdges(Node<?> node, Collection<Node<?>> adjs) { // for (Node<?> adj : adjs) { // addEdge(node, adj); // } // return this; // } // // public Graph addEdge(Node<?> node, Node<?> adj) { // Objects.requireNonNull(node, "Cannot attach an edge to a null node"); // if (Objects.equals(node, adj)) { // throw new IllegalArgumentException("Cannot connect a node to itself"); // } // register(node); // register(adj); // checkCircularDependency(node, adj); // this.adj.get(node).add(adj); // return this; // } // // private void register(Node<?> node) { // if (node != null) { // all.add(node); // if (!this.adj.containsKey(node)) { // this.adj.put(node, new ArrayList<Node>(0)); // } // } // } // // private void checkCircularDependency(Node<?> node, Node<?> adj) { // final List<Node> twoDep = this.adj.get(adj); // // if (twoDep == null) return; // // if (twoDep.contains(node)) { // // throw new CircularDependencyException("Circular Dependency detected: %s <----> %s", node, adj); // } // // // } // // public Collection<Node<?>> resolve() { // return topologicalSort(); // } // // private Collection<Node<?>> topologicalSort() { // final Stack<Node> stack = new Stack<>(); // final Map<Node, Boolean> visited = new HashMap<>(); // for (Node node : all) { // visited.put(node, false); // } // // for (Node node : all) { // if (!visited.get(node)) { // doTopologicalSort(node, visited, stack); // } // } // final List<Node<?>> classes = new ArrayList<>(); // for (Node node : stack) { // classes.add(node); // } // return classes; // } // // private void doTopologicalSort(Node<?> node, Map<Node, Boolean> visited, Stack<Node> stack) { // visited.put(node, true); // // final List<Node> deps = adj.get(node); // for (Node dep : deps) { // final Boolean vis = visited.get(dep); // if (vis != null && !vis) { // doTopologicalSort(dep, visited, stack); // } // } // stack.push(node); // } // } // // Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // }
import org.plugface.core.internal.di.Graph; import org.plugface.core.internal.di.Node; import java.util.Collection;
package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ /** * Internal class used to create a dependency graph * for plugin dependency injection. */ public class DependencyResolver { private final AnnotationProcessor processor; public DependencyResolver(AnnotationProcessor processor) { this.processor = processor; } public Collection<Node<?>> resolve(Collection<Class<?>> pluginClasses) {
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Graph.java // public class Graph { // // private Set<Node> all = new HashSet<>(); // private Map<Node, List<Node>> adj = new HashMap<>(); // // public Graph addLeaf(Node<?> node) { // addEdge(node, null); // return this; // } // // public Graph addEdges(Node<?> node, Collection<Node<?>> adjs) { // for (Node<?> adj : adjs) { // addEdge(node, adj); // } // return this; // } // // public Graph addEdge(Node<?> node, Node<?> adj) { // Objects.requireNonNull(node, "Cannot attach an edge to a null node"); // if (Objects.equals(node, adj)) { // throw new IllegalArgumentException("Cannot connect a node to itself"); // } // register(node); // register(adj); // checkCircularDependency(node, adj); // this.adj.get(node).add(adj); // return this; // } // // private void register(Node<?> node) { // if (node != null) { // all.add(node); // if (!this.adj.containsKey(node)) { // this.adj.put(node, new ArrayList<Node>(0)); // } // } // } // // private void checkCircularDependency(Node<?> node, Node<?> adj) { // final List<Node> twoDep = this.adj.get(adj); // // if (twoDep == null) return; // // if (twoDep.contains(node)) { // // throw new CircularDependencyException("Circular Dependency detected: %s <----> %s", node, adj); // } // // // } // // public Collection<Node<?>> resolve() { // return topologicalSort(); // } // // private Collection<Node<?>> topologicalSort() { // final Stack<Node> stack = new Stack<>(); // final Map<Node, Boolean> visited = new HashMap<>(); // for (Node node : all) { // visited.put(node, false); // } // // for (Node node : all) { // if (!visited.get(node)) { // doTopologicalSort(node, visited, stack); // } // } // final List<Node<?>> classes = new ArrayList<>(); // for (Node node : stack) { // classes.add(node); // } // return classes; // } // // private void doTopologicalSort(Node<?> node, Map<Node, Boolean> visited, Stack<Node> stack) { // visited.put(node, true); // // final List<Node> deps = adj.get(node); // for (Node dep : deps) { // final Boolean vis = visited.get(dep); // if (vis != null && !vis) { // doTopologicalSort(dep, visited, stack); // } // } // stack.push(node); // } // } // // Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // Path: plugface-core/src/main/java/org/plugface/core/internal/DependencyResolver.java import org.plugface.core.internal.di.Graph; import org.plugface.core.internal.di.Node; import java.util.Collection; package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ /** * Internal class used to create a dependency graph * for plugin dependency injection. */ public class DependencyResolver { private final AnnotationProcessor processor; public DependencyResolver(AnnotationProcessor processor) { this.processor = processor; } public Collection<Node<?>> resolve(Collection<Class<?>> pluginClasses) {
final Graph graph = new Graph();
MatteoJoliveau/PlugFace
plugface-core/src/main/java/org/plugface/core/internal/AnnotationProcessor.java
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // }
import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node; import javax.inject.Inject;
package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ /** * Internal class used to process the {@link Plugin} annotation */ public class AnnotationProcessor { public static <T> String getPluginName(T plugin) { return getPluginName(plugin.getClass()); } public static <T> String getPluginName(Class<T> plugin) { final Plugin annotation = getPluginAnnotation(plugin); final String name = annotation.name(); return "".equalsIgnoreCase(name) ? null : name; } public boolean hasDependencies(Class<?> pluginClass) { getPluginAnnotation(pluginClass); final Constructor<?>[] constructors = pluginClass.getConstructors(); if (constructors.length == 0) return false; for (Constructor<?> constructor : constructors) { final Inject annotation = constructor.getAnnotation(Inject.class); if (annotation != null) { return true; } } return false; }
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // Path: plugface-core/src/main/java/org/plugface/core/internal/AnnotationProcessor.java import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node; import javax.inject.Inject; package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ /** * Internal class used to process the {@link Plugin} annotation */ public class AnnotationProcessor { public static <T> String getPluginName(T plugin) { return getPluginName(plugin.getClass()); } public static <T> String getPluginName(Class<T> plugin) { final Plugin annotation = getPluginAnnotation(plugin); final String name = annotation.name(); return "".equalsIgnoreCase(name) ? null : name; } public boolean hasDependencies(Class<?> pluginClass) { getPluginAnnotation(pluginClass); final Constructor<?>[] constructors = pluginClass.getConstructors(); if (constructors.length == 0) return false; for (Constructor<?> constructor : constructors) { final Inject annotation = constructor.getAnnotation(Inject.class); if (annotation != null) { return true; } } return false; }
public Collection<Node<?>> getDependencies(Class<?> pluginClass) {
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/internal/AnnotationProcessorTest.java
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/DependencyPlugin.java // @Plugin(name = "dependency") // public class DependencyPlugin { // // private final TestPlugin dependency; // private final OptionalPlugin optional; // // @Inject // public DependencyPlugin(TestPlugin dependency, OptionalPlugin optional) { // this.dependency = dependency; // this.optional = optional; // } // // public String test() { // return String.format("Dependency: %s\nOptional: %s", dependency.greet(), optional != null ? optional.greet() : null); // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // }
import org.plugface.core.plugins.DependencyPlugin; import org.plugface.core.plugins.TestPlugin; import java.util.Collection; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node;
package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class AnnotationProcessorTest { private AnnotationProcessor sut; @Before public void setUp() throws Exception { sut = new AnnotationProcessor(); } @Test public void shouldGetPluginName() {
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/DependencyPlugin.java // @Plugin(name = "dependency") // public class DependencyPlugin { // // private final TestPlugin dependency; // private final OptionalPlugin optional; // // @Inject // public DependencyPlugin(TestPlugin dependency, OptionalPlugin optional) { // this.dependency = dependency; // this.optional = optional; // } // // public String test() { // return String.format("Dependency: %s\nOptional: %s", dependency.greet(), optional != null ? optional.greet() : null); // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // Path: plugface-core/src/test/java/org/plugface/core/internal/AnnotationProcessorTest.java import org.plugface.core.plugins.DependencyPlugin; import org.plugface.core.plugins.TestPlugin; import java.util.Collection; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node; package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class AnnotationProcessorTest { private AnnotationProcessor sut; @Before public void setUp() throws Exception { sut = new AnnotationProcessor(); } @Test public void shouldGetPluginName() {
final String name = sut.getPluginName(new TestPlugin());
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/internal/AnnotationProcessorTest.java
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/DependencyPlugin.java // @Plugin(name = "dependency") // public class DependencyPlugin { // // private final TestPlugin dependency; // private final OptionalPlugin optional; // // @Inject // public DependencyPlugin(TestPlugin dependency, OptionalPlugin optional) { // this.dependency = dependency; // this.optional = optional; // } // // public String test() { // return String.format("Dependency: %s\nOptional: %s", dependency.greet(), optional != null ? optional.greet() : null); // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // }
import org.plugface.core.plugins.DependencyPlugin; import org.plugface.core.plugins.TestPlugin; import java.util.Collection; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node;
package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class AnnotationProcessorTest { private AnnotationProcessor sut; @Before public void setUp() throws Exception { sut = new AnnotationProcessor(); } @Test public void shouldGetPluginName() { final String name = sut.getPluginName(new TestPlugin()); assertEquals("test", name); } @Test public void shouldReturnNullIfNoNameIsProvided() { final String name = sut.getPluginName(new EmptyPlugin()); assertNull(name); } @Test public void shouldDetectDependencies() {
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/DependencyPlugin.java // @Plugin(name = "dependency") // public class DependencyPlugin { // // private final TestPlugin dependency; // private final OptionalPlugin optional; // // @Inject // public DependencyPlugin(TestPlugin dependency, OptionalPlugin optional) { // this.dependency = dependency; // this.optional = optional; // } // // public String test() { // return String.format("Dependency: %s\nOptional: %s", dependency.greet(), optional != null ? optional.greet() : null); // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // Path: plugface-core/src/test/java/org/plugface/core/internal/AnnotationProcessorTest.java import org.plugface.core.plugins.DependencyPlugin; import org.plugface.core.plugins.TestPlugin; import java.util.Collection; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node; package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class AnnotationProcessorTest { private AnnotationProcessor sut; @Before public void setUp() throws Exception { sut = new AnnotationProcessor(); } @Test public void shouldGetPluginName() { final String name = sut.getPluginName(new TestPlugin()); assertEquals("test", name); } @Test public void shouldReturnNullIfNoNameIsProvided() { final String name = sut.getPluginName(new EmptyPlugin()); assertNull(name); } @Test public void shouldDetectDependencies() {
final boolean hasDependencies = sut.hasDependencies(DependencyPlugin.class);
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/internal/AnnotationProcessorTest.java
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/DependencyPlugin.java // @Plugin(name = "dependency") // public class DependencyPlugin { // // private final TestPlugin dependency; // private final OptionalPlugin optional; // // @Inject // public DependencyPlugin(TestPlugin dependency, OptionalPlugin optional) { // this.dependency = dependency; // this.optional = optional; // } // // public String test() { // return String.format("Dependency: %s\nOptional: %s", dependency.greet(), optional != null ? optional.greet() : null); // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // }
import org.plugface.core.plugins.DependencyPlugin; import org.plugface.core.plugins.TestPlugin; import java.util.Collection; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node;
package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class AnnotationProcessorTest { private AnnotationProcessor sut; @Before public void setUp() throws Exception { sut = new AnnotationProcessor(); } @Test public void shouldGetPluginName() { final String name = sut.getPluginName(new TestPlugin()); assertEquals("test", name); } @Test public void shouldReturnNullIfNoNameIsProvided() { final String name = sut.getPluginName(new EmptyPlugin()); assertNull(name); } @Test public void shouldDetectDependencies() { final boolean hasDependencies = sut.hasDependencies(DependencyPlugin.class); assertTrue(hasDependencies); } @Test public void shouldReturnFalseOnNoDependencies() { final boolean hasDependencies = sut.hasDependencies(TestPlugin.class); assertFalse(hasDependencies); } @Test public void shouldRetrieveDependencies() {
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/DependencyPlugin.java // @Plugin(name = "dependency") // public class DependencyPlugin { // // private final TestPlugin dependency; // private final OptionalPlugin optional; // // @Inject // public DependencyPlugin(TestPlugin dependency, OptionalPlugin optional) { // this.dependency = dependency; // this.optional = optional; // } // // public String test() { // return String.format("Dependency: %s\nOptional: %s", dependency.greet(), optional != null ? optional.greet() : null); // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // Path: plugface-core/src/test/java/org/plugface/core/internal/AnnotationProcessorTest.java import org.plugface.core.plugins.DependencyPlugin; import org.plugface.core.plugins.TestPlugin; import java.util.Collection; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.annotations.Plugin; import org.plugface.core.internal.di.Node; package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class AnnotationProcessorTest { private AnnotationProcessor sut; @Before public void setUp() throws Exception { sut = new AnnotationProcessor(); } @Test public void shouldGetPluginName() { final String name = sut.getPluginName(new TestPlugin()); assertEquals("test", name); } @Test public void shouldReturnNullIfNoNameIsProvided() { final String name = sut.getPluginName(new EmptyPlugin()); assertNull(name); } @Test public void shouldDetectDependencies() { final boolean hasDependencies = sut.hasDependencies(DependencyPlugin.class); assertTrue(hasDependencies); } @Test public void shouldReturnFalseOnNoDependencies() { final boolean hasDependencies = sut.hasDependencies(TestPlugin.class); assertFalse(hasDependencies); } @Test public void shouldRetrieveDependencies() {
final Collection<Node<?>> dependencies = sut.getDependencies(DependencyPlugin.class);
MatteoJoliveau/PlugFace
plugface-spring/src/test/java/org/plugface/spring/SpringPluginContextTest.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginContext.java // public interface PluginContext { // /** // * Return an instance of the plugin that is registered with the given name // * // * @param pluginName the name of the plugin // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(String pluginName); // // /** // * Return an instance of the plugin matching the given type // * given type // * // * @param pluginClass type the plugin must match; can be an interface or superclass. Cannot be <code>null</code> // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(Class<T> pluginClass); // // /** // * Return the complete list of all the plugins currently registered // * // * @return a {@link Collection} of all the plugins // */ // Collection<PluginRef> getAllPlugins(); // // /** // * Register a plugin in the context // * // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void addPlugin(T plugin); // // /** // * Register a plugin in the context with the given name // * // * @param name the name to associate with the plugin // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void addPlugin(String name, T plugin); // // /** // * Remove a plugin from the context // * @param plugin the plugin instance to remove // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(T plugin); // // /** // * Remove a plugin with the given name from the context // * @param pluginName the name associated with the plugin // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(String pluginName); // // /** // * Check if the context has a plugin with the given name // * @param pluginName the name associated with the plugin // * @return <code>true</code> if a plugin is present, <code>false</code> otherwise // */ // boolean hasPlugin(String pluginName); // // /** // * Check if the context has a plugin with the given type // * @param pluginClass type the plugin must match; can be an interface or superclass. // * @return <code>true</code> if a plugin is present, <code>false</code> otherwise // */ // <T> boolean hasPlugin(Class<T> pluginClass); // // // }
import org.plugface.core.annotations.Plugin; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.junit.Assert.assertNotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.plugface.core.PluginContext;
package org.plugface.spring; /*- * #%L * PlugFace :: Spring * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class SpringPluginContextTest { private AnnotationConfigApplicationContext context;
// Path: plugface-core/src/main/java/org/plugface/core/PluginContext.java // public interface PluginContext { // /** // * Return an instance of the plugin that is registered with the given name // * // * @param pluginName the name of the plugin // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(String pluginName); // // /** // * Return an instance of the plugin matching the given type // * given type // * // * @param pluginClass type the plugin must match; can be an interface or superclass. Cannot be <code>null</code> // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(Class<T> pluginClass); // // /** // * Return the complete list of all the plugins currently registered // * // * @return a {@link Collection} of all the plugins // */ // Collection<PluginRef> getAllPlugins(); // // /** // * Register a plugin in the context // * // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void addPlugin(T plugin); // // /** // * Register a plugin in the context with the given name // * // * @param name the name to associate with the plugin // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void addPlugin(String name, T plugin); // // /** // * Remove a plugin from the context // * @param plugin the plugin instance to remove // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(T plugin); // // /** // * Remove a plugin with the given name from the context // * @param pluginName the name associated with the plugin // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(String pluginName); // // /** // * Check if the context has a plugin with the given name // * @param pluginName the name associated with the plugin // * @return <code>true</code> if a plugin is present, <code>false</code> otherwise // */ // boolean hasPlugin(String pluginName); // // /** // * Check if the context has a plugin with the given type // * @param pluginClass type the plugin must match; can be an interface or superclass. // * @return <code>true</code> if a plugin is present, <code>false</code> otherwise // */ // <T> boolean hasPlugin(Class<T> pluginClass); // // // } // Path: plugface-spring/src/test/java/org/plugface/spring/SpringPluginContextTest.java import org.plugface.core.annotations.Plugin; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.junit.Assert.assertNotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.plugface.core.PluginContext; package org.plugface.spring; /*- * #%L * PlugFace :: Spring * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class SpringPluginContextTest { private AnnotationConfigApplicationContext context;
private PluginContext sut;
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // }
import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef;
package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ @SuppressWarnings({"SuspiciousMethodCalls", "ResultOfMethodCallIgnored"}) public class DefaultPluginContextTest { private Map<String, Object> registry = new HashMap<>(); private DefaultPluginContext context;
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // } // Path: plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef; package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ @SuppressWarnings({"SuspiciousMethodCalls", "ResultOfMethodCallIgnored"}) public class DefaultPluginContextTest { private Map<String, Object> registry = new HashMap<>(); private DefaultPluginContext context;
private TestPlugin plugin = new TestPlugin();
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // }
import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef;
package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ @SuppressWarnings({"SuspiciousMethodCalls", "ResultOfMethodCallIgnored"}) public class DefaultPluginContextTest { private Map<String, Object> registry = new HashMap<>(); private DefaultPluginContext context; private TestPlugin plugin = new TestPlugin();
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // } // Path: plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef; package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ @SuppressWarnings({"SuspiciousMethodCalls", "ResultOfMethodCallIgnored"}) public class DefaultPluginContextTest { private Map<String, Object> registry = new HashMap<>(); private DefaultPluginContext context; private TestPlugin plugin = new TestPlugin();
private OptionalPlugin optionalPlugin = new OptionalPlugin();
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // }
import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef;
assertEquals(plugin, test); } @Test public void shouldRemovePluginFromInstance() { registry.put("test", plugin); final TestPlugin test = context.removePlugin(plugin); assertFalse(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromName() { registry.put("test", plugin); final TestPlugin test = context.getPlugin("test"); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromClass() { registry.put("test", plugin); final TestPlugin test = context.getPlugin(TestPlugin.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromInterface() { registry.put("test", plugin);
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // } // Path: plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef; assertEquals(plugin, test); } @Test public void shouldRemovePluginFromInstance() { registry.put("test", plugin); final TestPlugin test = context.removePlugin(plugin); assertFalse(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromName() { registry.put("test", plugin); final TestPlugin test = context.getPlugin("test"); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromClass() { registry.put("test", plugin); final TestPlugin test = context.getPlugin(TestPlugin.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromInterface() { registry.put("test", plugin);
final TestInterface test = context.getPlugin(TestInterface.class);
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // }
import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef;
assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromName() { registry.put("test", plugin); final TestPlugin test = context.getPlugin("test"); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromClass() { registry.put("test", plugin); final TestPlugin test = context.getPlugin(TestPlugin.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromInterface() { registry.put("test", plugin); final TestInterface test = context.getPlugin(TestInterface.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromSuperclass() { registry.put("test", plugin);
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // } // Path: plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef; assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromName() { registry.put("test", plugin); final TestPlugin test = context.getPlugin("test"); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromClass() { registry.put("test", plugin); final TestPlugin test = context.getPlugin(TestPlugin.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromInterface() { registry.put("test", plugin); final TestInterface test = context.getPlugin(TestInterface.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromSuperclass() { registry.put("test", plugin);
final TestSuperclass test = context.getPlugin(TestSuperclass.class);
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // }
import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef;
@Test public void shouldRetrievePluginFromClass() { registry.put("test", plugin); final TestPlugin test = context.getPlugin(TestPlugin.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromInterface() { registry.put("test", plugin); final TestInterface test = context.getPlugin(TestInterface.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromSuperclass() { registry.put("test", plugin); final TestSuperclass test = context.getPlugin(TestSuperclass.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrieveAllThePlugins() throws Exception { registry.put("test", plugin); registry.put("optional", optionalPlugin);
// Path: plugface-core/src/main/java/org/plugface/core/PluginRef.java // public final class PluginRef<T> { // // private final T ref; // private final String name; // private final Class<T> type; // // private PluginRef(T ref, String name, Class<T> type) { // this.ref = Objects.requireNonNull(ref, "Plugin reference cannot be null"); // this.name = Objects.requireNonNull(name, "Plugin name cannot be null"); // this.type = Objects.requireNonNull(type, "Plugin type cannot be null"); // } // // @SuppressWarnings("unchecked") // public static <T> PluginRef<T> of(T ref, String name) { // return new PluginRef<>(ref, name, (Class<T>) ref.getClass()); // } // // public T get() { // return ref; // } // // public String getName() { // return name; // } // // public Class<T> getType() { // return type; // } // // // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/OptionalPlugin.java // @Plugin(name = "optional") // public class OptionalPlugin { // // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestInterface.java // public interface TestInterface { // // String greet(); // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestPlugin.java // @Plugin(name = "test") // public class TestPlugin extends TestSuperclass { // // @Override // public String greet() { // return "Hello PlugFace!"; // } // } // // Path: plugface-core/src/test/java/org/plugface/core/plugins/TestSuperclass.java // public abstract class TestSuperclass implements TestInterface{ // } // Path: plugface-core/src/test/java/org/plugface/core/impl/DefaultPluginContextTest.java import org.plugface.core.plugins.OptionalPlugin; import org.plugface.core.plugins.TestInterface; import org.plugface.core.plugins.TestPlugin; import org.plugface.core.plugins.TestSuperclass; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.plugface.core.PluginRef; @Test public void shouldRetrievePluginFromClass() { registry.put("test", plugin); final TestPlugin test = context.getPlugin(TestPlugin.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromInterface() { registry.put("test", plugin); final TestInterface test = context.getPlugin(TestInterface.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrievePluginFromSuperclass() { registry.put("test", plugin); final TestSuperclass test = context.getPlugin(TestSuperclass.class); assertTrue(registry.containsKey("test")); assertEquals(plugin, test); } @Test public void shouldRetrieveAllThePlugins() throws Exception { registry.put("test", plugin); registry.put("optional", optionalPlugin);
final List<PluginRef> all = (List<PluginRef>) context.getAllPlugins();
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/internal/DependencyResolverTest.java
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.plugface.core.internal.di.Node; import org.plugface.core.plugins.*;
package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class DependencyResolverTest { // private AnnotationProcessor mockProcessor = mock(AnnotationProcessor.class); private AnnotationProcessor mockProcessor = new AnnotationProcessor(); private DependencyResolver sut; @Before public void setUp() throws Exception { sut = new DependencyResolver(mockProcessor); } @Test public void shouldResolveComplexDependencies() throws Exception { List<Class<?>> plugins = newArrayList(DeepDependencyPlugin.class, DependencyPlugin.class, TestPlugin.class, OptionalPlugin.class, SingleDependencyPlugin.class );
// Path: plugface-core/src/main/java/org/plugface/core/internal/di/Node.java // public class Node<T> { // private final Class<T> refClass; // // public Node(Class<T> refClass) { // this.refClass = refClass; // } // // public Class<T> getRefClass() { // return refClass; // } // // @Override // public String toString() { // return "Node{" + // "class=" + refClass.getSimpleName() + // '}'; // } // // @Override // public boolean equals(Object o) { // if (!(o instanceof Node)) { // return false; // } // Node<?> node = (Node<?>) o; // return Objects.equals(refClass, node.refClass); // } // // @Override // public int hashCode() { // return Objects.hash(refClass); // } // } // Path: plugface-core/src/test/java/org/plugface/core/internal/DependencyResolverTest.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.plugface.core.internal.di.Node; import org.plugface.core.plugins.*; package org.plugface.core.internal; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class DependencyResolverTest { // private AnnotationProcessor mockProcessor = mock(AnnotationProcessor.class); private AnnotationProcessor mockProcessor = new AnnotationProcessor(); private DependencyResolver sut; @Before public void setUp() throws Exception { sut = new DependencyResolver(mockProcessor); } @Test public void shouldResolveComplexDependencies() throws Exception { List<Class<?>> plugins = newArrayList(DeepDependencyPlugin.class, DependencyPlugin.class, TestPlugin.class, OptionalPlugin.class, SingleDependencyPlugin.class );
Collection<Node<?>> nodes = sut.resolve(plugins);
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/impl/ITPluginLoading.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginManager.java // public interface PluginManager { // // /** // * Register a plugin in the context // * // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(T plugin); // // /** // * Register a plugin in the context with the given name // * // * @param name the name to associate with the plugin // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(String name, T plugin); // // /** // * Return an instance of the plugin that is registered with the given name // * // * @param name the name of the plugin // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(String name); // // /** // * Return an instance of the plugin matching the given type // * given type // * // * @param pluginClass type the plugin must match; can be an interface or superclass. Cannot be <code>null</code> // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(Class<T> pluginClass); // // /** // * Return the complete list of all the plugins currently registered // * // * @return a {@link Collection} of all the plugins // */ // Collection<PluginRef> getAllPlugins(); // // /** // * Remove a plugin with the given name from the context // * // * @param name the name associated with the plugin // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(String name); // // /** // * Remove a plugin from the context // * // * @param plugin the plugin instance to remove // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(T plugin); // // /** // * Load a set of plugin retrieved from the give {@link PluginSource}, // * instantiating the objects, resolving any dependency and registering them // * in the context // * @param source the <code>PluginSource</code> to use for loading // * @return a list of loaded plugins, never <code>null</code> // * @throws Exception an exception that occurred during loading, see {@link PluginSource#load()} // */ // Collection<Object> loadPlugins(PluginSource source) throws Exception; // // } // // Path: plugface-core/src/main/java/org/plugface/core/PluginSource.java // public interface PluginSource { // // /** // * Load a list of classes that are either // * plugins or related code // * // * @return a list of class // * @throws Exception an exception that occurred during loading // */ // Collection<Class<?>> load() throws Exception; // } // // Path: plugface-core/src/main/java/org/plugface/core/factory/PluginManagers.java // public class PluginManagers { // // /** // * A default {@link PluginManager} configured with internal dependencies for {@link PluginContext}, {@link AnnotationProcessor} and {@link DependencyResolver} // * // * @return a fully configured {@link DefaultPluginManager} // */ // public static PluginManager defaultPluginManager() { // final DefaultPluginContext context = new DefaultPluginContext(); // final AnnotationProcessor processor = new AnnotationProcessor(); // final DependencyResolver resolver = new DependencyResolver(processor); // return newPluginManager(context, processor, resolver); // } // // public static PluginManager newPluginManager(PluginContext context, AnnotationProcessor processor, DependencyResolver resolver) { // return new DefaultPluginManager(context, processor, resolver); // } // }
import org.plugface.core.factory.PluginManagers; import org.plugface.core.plugins.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.PluginManager; import org.plugface.core.PluginSource;
package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class ITPluginLoading { private PluginManager manager; @Before public void setUp() throws Exception {
// Path: plugface-core/src/main/java/org/plugface/core/PluginManager.java // public interface PluginManager { // // /** // * Register a plugin in the context // * // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(T plugin); // // /** // * Register a plugin in the context with the given name // * // * @param name the name to associate with the plugin // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(String name, T plugin); // // /** // * Return an instance of the plugin that is registered with the given name // * // * @param name the name of the plugin // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(String name); // // /** // * Return an instance of the plugin matching the given type // * given type // * // * @param pluginClass type the plugin must match; can be an interface or superclass. Cannot be <code>null</code> // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(Class<T> pluginClass); // // /** // * Return the complete list of all the plugins currently registered // * // * @return a {@link Collection} of all the plugins // */ // Collection<PluginRef> getAllPlugins(); // // /** // * Remove a plugin with the given name from the context // * // * @param name the name associated with the plugin // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(String name); // // /** // * Remove a plugin from the context // * // * @param plugin the plugin instance to remove // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(T plugin); // // /** // * Load a set of plugin retrieved from the give {@link PluginSource}, // * instantiating the objects, resolving any dependency and registering them // * in the context // * @param source the <code>PluginSource</code> to use for loading // * @return a list of loaded plugins, never <code>null</code> // * @throws Exception an exception that occurred during loading, see {@link PluginSource#load()} // */ // Collection<Object> loadPlugins(PluginSource source) throws Exception; // // } // // Path: plugface-core/src/main/java/org/plugface/core/PluginSource.java // public interface PluginSource { // // /** // * Load a list of classes that are either // * plugins or related code // * // * @return a list of class // * @throws Exception an exception that occurred during loading // */ // Collection<Class<?>> load() throws Exception; // } // // Path: plugface-core/src/main/java/org/plugface/core/factory/PluginManagers.java // public class PluginManagers { // // /** // * A default {@link PluginManager} configured with internal dependencies for {@link PluginContext}, {@link AnnotationProcessor} and {@link DependencyResolver} // * // * @return a fully configured {@link DefaultPluginManager} // */ // public static PluginManager defaultPluginManager() { // final DefaultPluginContext context = new DefaultPluginContext(); // final AnnotationProcessor processor = new AnnotationProcessor(); // final DependencyResolver resolver = new DependencyResolver(processor); // return newPluginManager(context, processor, resolver); // } // // public static PluginManager newPluginManager(PluginContext context, AnnotationProcessor processor, DependencyResolver resolver) { // return new DefaultPluginManager(context, processor, resolver); // } // } // Path: plugface-core/src/test/java/org/plugface/core/impl/ITPluginLoading.java import org.plugface.core.factory.PluginManagers; import org.plugface.core.plugins.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.PluginManager; import org.plugface.core.PluginSource; package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class ITPluginLoading { private PluginManager manager; @Before public void setUp() throws Exception {
manager = PluginManagers.defaultPluginManager();
MatteoJoliveau/PlugFace
plugface-core/src/test/java/org/plugface/core/impl/ITPluginLoading.java
// Path: plugface-core/src/main/java/org/plugface/core/PluginManager.java // public interface PluginManager { // // /** // * Register a plugin in the context // * // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(T plugin); // // /** // * Register a plugin in the context with the given name // * // * @param name the name to associate with the plugin // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(String name, T plugin); // // /** // * Return an instance of the plugin that is registered with the given name // * // * @param name the name of the plugin // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(String name); // // /** // * Return an instance of the plugin matching the given type // * given type // * // * @param pluginClass type the plugin must match; can be an interface or superclass. Cannot be <code>null</code> // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(Class<T> pluginClass); // // /** // * Return the complete list of all the plugins currently registered // * // * @return a {@link Collection} of all the plugins // */ // Collection<PluginRef> getAllPlugins(); // // /** // * Remove a plugin with the given name from the context // * // * @param name the name associated with the plugin // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(String name); // // /** // * Remove a plugin from the context // * // * @param plugin the plugin instance to remove // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(T plugin); // // /** // * Load a set of plugin retrieved from the give {@link PluginSource}, // * instantiating the objects, resolving any dependency and registering them // * in the context // * @param source the <code>PluginSource</code> to use for loading // * @return a list of loaded plugins, never <code>null</code> // * @throws Exception an exception that occurred during loading, see {@link PluginSource#load()} // */ // Collection<Object> loadPlugins(PluginSource source) throws Exception; // // } // // Path: plugface-core/src/main/java/org/plugface/core/PluginSource.java // public interface PluginSource { // // /** // * Load a list of classes that are either // * plugins or related code // * // * @return a list of class // * @throws Exception an exception that occurred during loading // */ // Collection<Class<?>> load() throws Exception; // } // // Path: plugface-core/src/main/java/org/plugface/core/factory/PluginManagers.java // public class PluginManagers { // // /** // * A default {@link PluginManager} configured with internal dependencies for {@link PluginContext}, {@link AnnotationProcessor} and {@link DependencyResolver} // * // * @return a fully configured {@link DefaultPluginManager} // */ // public static PluginManager defaultPluginManager() { // final DefaultPluginContext context = new DefaultPluginContext(); // final AnnotationProcessor processor = new AnnotationProcessor(); // final DependencyResolver resolver = new DependencyResolver(processor); // return newPluginManager(context, processor, resolver); // } // // public static PluginManager newPluginManager(PluginContext context, AnnotationProcessor processor, DependencyResolver resolver) { // return new DefaultPluginManager(context, processor, resolver); // } // }
import org.plugface.core.factory.PluginManagers; import org.plugface.core.plugins.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.PluginManager; import org.plugface.core.PluginSource;
package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class ITPluginLoading { private PluginManager manager; @Before public void setUp() throws Exception { manager = PluginManagers.defaultPluginManager(); } @Test public void shouldLoadAndResolveDependencies() throws Exception {
// Path: plugface-core/src/main/java/org/plugface/core/PluginManager.java // public interface PluginManager { // // /** // * Register a plugin in the context // * // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(T plugin); // // /** // * Register a plugin in the context with the given name // * // * @param name the name to associate with the plugin // * @param plugin the plugin object to register // * @param <T> the inferred type of the plugin // */ // <T> void register(String name, T plugin); // // /** // * Return an instance of the plugin that is registered with the given name // * // * @param name the name of the plugin // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(String name); // // /** // * Return an instance of the plugin matching the given type // * given type // * // * @param pluginClass type the plugin must match; can be an interface or superclass. Cannot be <code>null</code> // * @param <T> the inferred type of the plugin // * @return the plugin object or <code>null</code> if none exists // */ // @Nullable // <T> T getPlugin(Class<T> pluginClass); // // /** // * Return the complete list of all the plugins currently registered // * // * @return a {@link Collection} of all the plugins // */ // Collection<PluginRef> getAllPlugins(); // // /** // * Remove a plugin with the given name from the context // * // * @param name the name associated with the plugin // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(String name); // // /** // * Remove a plugin from the context // * // * @param plugin the plugin instance to remove // * @param <T> the inferred type of the plugin // * @return the removed plugin, or <code>null</code> if none is exists // */ // @Nullable // <T> T removePlugin(T plugin); // // /** // * Load a set of plugin retrieved from the give {@link PluginSource}, // * instantiating the objects, resolving any dependency and registering them // * in the context // * @param source the <code>PluginSource</code> to use for loading // * @return a list of loaded plugins, never <code>null</code> // * @throws Exception an exception that occurred during loading, see {@link PluginSource#load()} // */ // Collection<Object> loadPlugins(PluginSource source) throws Exception; // // } // // Path: plugface-core/src/main/java/org/plugface/core/PluginSource.java // public interface PluginSource { // // /** // * Load a list of classes that are either // * plugins or related code // * // * @return a list of class // * @throws Exception an exception that occurred during loading // */ // Collection<Class<?>> load() throws Exception; // } // // Path: plugface-core/src/main/java/org/plugface/core/factory/PluginManagers.java // public class PluginManagers { // // /** // * A default {@link PluginManager} configured with internal dependencies for {@link PluginContext}, {@link AnnotationProcessor} and {@link DependencyResolver} // * // * @return a fully configured {@link DefaultPluginManager} // */ // public static PluginManager defaultPluginManager() { // final DefaultPluginContext context = new DefaultPluginContext(); // final AnnotationProcessor processor = new AnnotationProcessor(); // final DependencyResolver resolver = new DependencyResolver(processor); // return newPluginManager(context, processor, resolver); // } // // public static PluginManager newPluginManager(PluginContext context, AnnotationProcessor processor, DependencyResolver resolver) { // return new DefaultPluginManager(context, processor, resolver); // } // } // Path: plugface-core/src/test/java/org/plugface/core/impl/ITPluginLoading.java import org.plugface.core.factory.PluginManagers; import org.plugface.core.plugins.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.plugface.core.PluginManager; import org.plugface.core.PluginSource; package org.plugface.core.impl; /*- * #%L * PlugFace :: Core * %% * Copyright (C) 2017 - 2018 PlugFace * %% * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * #L% */ public class ITPluginLoading { private PluginManager manager; @Before public void setUp() throws Exception { manager = PluginManagers.defaultPluginManager(); } @Test public void shouldLoadAndResolveDependencies() throws Exception {
final PluginSource source = new PluginSource() {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/OsMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.os.OsStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class OsMetricsGenerator extends MetricsGenerator<OsStats> { private static final Logger logger = Loggers.getLogger(OsMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/OsMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.os.OsStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class OsMetricsGenerator extends MetricsGenerator<OsStats> { private static final Logger logger = Loggers.getLogger(OsMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, OsStats osStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/StriptsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.elasticsearch.script.ScriptStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class StriptsGenerator extends MetricsGenerator<ScriptStats> { @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/StriptsGenerator.java import org.elasticsearch.script.ScriptStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class StriptsGenerator extends MetricsGenerator<ScriptStats> { @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ScriptStats scriptsStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/PendingTasksMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse; import org.elasticsearch.cluster.service.PendingClusterTask; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.List;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class PendingTasksMetricsGenerator extends MetricsGenerator<PendingClusterTasksResponse> { private static final Logger logger = Loggers.getLogger(PendingTasksMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/PendingTasksMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse; import org.elasticsearch.cluster.service.PendingClusterTask; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.List; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class PendingTasksMetricsGenerator extends MetricsGenerator<PendingClusterTasksResponse> { private static final Logger logger = Loggers.getLogger(PendingTasksMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer,
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/PendingTasksMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse; import org.elasticsearch.cluster.service.PendingClusterTask; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.List;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class PendingTasksMetricsGenerator extends MetricsGenerator<PendingClusterTasksResponse> { private static final Logger logger = Loggers.getLogger(PendingTasksMetricsGenerator.class, "init"); @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, PendingClusterTasksResponse pendingClusterTasksResponse) { List<PendingClusterTask> pendingTasks = pendingClusterTasksResponse.getPendingTasks(); logger.debug("Generating output for PendingTasks stats: {}", pendingTasks); writer.addGauge("es_tasks_count") .withHelp("Number of background tasks running") .value(pendingTasks.size());
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/PendingTasksMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse; import org.elasticsearch.cluster.service.PendingClusterTask; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.List; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class PendingTasksMetricsGenerator extends MetricsGenerator<PendingClusterTasksResponse> { private static final Logger logger = Loggers.getLogger(PendingTasksMetricsGenerator.class, "init"); @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, PendingClusterTasksResponse pendingClusterTasksResponse) { List<PendingClusterTask> pendingTasks = pendingClusterTasksResponse.getPendingTasks(); logger.debug("Generating output for PendingTasks stats: {}", pendingTasks); writer.addGauge("es_tasks_count") .withHelp("Number of background tasks running") .value(pendingTasks.size());
SingleValueWriter esTasksTimeInQueueSeconds = writer
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/HttpMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.http.HttpStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class HttpMetricsGenerator extends MetricsGenerator<HttpStats> { private static final Logger logger = Loggers.getLogger(HttpMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/HttpMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.http.HttpStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class HttpMetricsGenerator extends MetricsGenerator<HttpStats> { private static final Logger logger = Loggers.getLogger(HttpMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, HttpStats httpStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ProcessMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.process.ProcessStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; /* Aligned with process data returned by JVM and golang clients https://github.com/prometheus/client_java/blob/master/simpleclient_hotspot/src/main/java/io/prometheus/client/hotspot/StandardExports.java https://github.com/prometheus/client_golang/blob/master/prometheus/process_collector.go */ public class ProcessMetricsGenerator extends MetricsGenerator<ProcessStats> { private static final Logger logger = Loggers.getLogger(OsMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ProcessMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.process.ProcessStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; /* Aligned with process data returned by JVM and golang clients https://github.com/prometheus/client_java/blob/master/simpleclient_hotspot/src/main/java/io/prometheus/client/hotspot/StandardExports.java https://github.com/prometheus/client_golang/blob/master/prometheus/process_collector.go */ public class ProcessMetricsGenerator extends MetricsGenerator<ProcessStats> { private static final Logger logger = Loggers.getLogger(OsMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ProcessStats processStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/FsMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.fs.FsInfo; import org.elasticsearch.monitor.fs.FsInfo.Path; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class FsMetricsGenerator extends MetricsGenerator<FsInfo> { private static final Logger logger = Loggers.getLogger(FsMetricsGenerator.class, "init"); private static final String PATH_LABEL = "path"; @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/FsMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.fs.FsInfo; import org.elasticsearch.monitor.fs.FsInfo.Path; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class FsMetricsGenerator extends MetricsGenerator<FsInfo> { private static final Logger logger = Loggers.getLogger(FsMetricsGenerator.class, "init"); private static final String PATH_LABEL = "path"; @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, FsInfo fsInfo) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/FsMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.fs.FsInfo; import org.elasticsearch.monitor.fs.FsInfo.Path; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class FsMetricsGenerator extends MetricsGenerator<FsInfo> { private static final Logger logger = Loggers.getLogger(FsMetricsGenerator.class, "init"); private static final String PATH_LABEL = "path"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, FsInfo fsInfo) { logger.debug("Generating data about FS stats: {}", fsInfo); writer.addGauge("es_fs_total_bytes") .withHelp("Total size of ES storage") .value(fsInfo.getTotal().getTotal().getBytes()); writer.addGauge("es_fs_available_bytes") .withHelp("Available size of ES storage") .value(fsInfo.getTotal().getAvailable().getBytes()); writer.addGauge("es_fs_free_bytes") .withHelp("Free size of ES storage") .value(fsInfo.getTotal().getFree().getBytes());
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/FsMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.monitor.fs.FsInfo; import org.elasticsearch.monitor.fs.FsInfo.Path; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class FsMetricsGenerator extends MetricsGenerator<FsInfo> { private static final Logger logger = Loggers.getLogger(FsMetricsGenerator.class, "init"); private static final String PATH_LABEL = "path"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, FsInfo fsInfo) { logger.debug("Generating data about FS stats: {}", fsInfo); writer.addGauge("es_fs_total_bytes") .withHelp("Total size of ES storage") .value(fsInfo.getTotal().getTotal().getBytes()); writer.addGauge("es_fs_available_bytes") .withHelp("Available size of ES storage") .value(fsInfo.getTotal().getAvailable().getBytes()); writer.addGauge("es_fs_free_bytes") .withHelp("Free size of ES storage") .value(fsInfo.getTotal().getFree().getBytes());
SingleValueWriter pathTotal = writer.addGauge("es_fs_path_total_bytes")
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/IndicesMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.index.cache.query.QueryCacheStats; import org.elasticsearch.index.fielddata.FieldDataStats; import org.elasticsearch.index.recovery.RecoveryStats; import org.elasticsearch.index.search.stats.SearchStats; import org.elasticsearch.index.shard.DocsStats; import org.elasticsearch.index.shard.IndexingStats; import org.elasticsearch.index.store.StoreStats; import org.elasticsearch.index.translog.TranslogStats; import org.elasticsearch.indices.NodeIndicesStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class IndicesMetricsGenerator extends MetricsGenerator<NodeIndicesStats> { private static final Logger logger = Loggers.getLogger(IndicesMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/IndicesMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.index.cache.query.QueryCacheStats; import org.elasticsearch.index.fielddata.FieldDataStats; import org.elasticsearch.index.recovery.RecoveryStats; import org.elasticsearch.index.search.stats.SearchStats; import org.elasticsearch.index.shard.DocsStats; import org.elasticsearch.index.shard.IndexingStats; import org.elasticsearch.index.store.StoreStats; import org.elasticsearch.index.translog.TranslogStats; import org.elasticsearch.indices.NodeIndicesStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class IndicesMetricsGenerator extends MetricsGenerator<NodeIndicesStats> { private static final Logger logger = Loggers.getLogger(IndicesMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, NodeIndicesStats indicesStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/TransportMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.transport.TransportStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class TransportMetricsGenerator extends MetricsGenerator<TransportStats>{ private static final Logger logger = Loggers.getLogger(OsMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/TransportMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.transport.TransportStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class TransportMetricsGenerator extends MetricsGenerator<TransportStats>{ private static final Logger logger = Loggers.getLogger(OsMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, TransportStats transportStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterStateMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ClusterStateMetricsGenerator extends MetricsGenerator<ClusterState> { private static final Logger logger = Loggers.getLogger(ClusterStateMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterStateMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ClusterStateMetricsGenerator extends MetricsGenerator<ClusterState> { private static final Logger logger = Loggers.getLogger(ClusterStateMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ClusterState clusterState) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterStateMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ClusterStateMetricsGenerator extends MetricsGenerator<ClusterState> { private static final Logger logger = Loggers.getLogger(ClusterStateMetricsGenerator.class, "init"); @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ClusterState clusterState) { logger.debug("Generating data about cluster state: {}", clusterState);
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterStateMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ClusterStateMetricsGenerator extends MetricsGenerator<ClusterState> { private static final Logger logger = Loggers.getLogger(ClusterStateMetricsGenerator.class, "init"); @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ClusterState clusterState) { logger.debug("Generating data about cluster state: {}", clusterState);
SingleValueWriter persistentGauge = writer.addGauge("es_cluster_persistent_settings")
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/StringBufferedRestHandler.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.RestChannel; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestRequest; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import java.util.concurrent.CompletableFuture; import static org.elasticsearch.rest.RestStatus.INTERNAL_SERVER_ERROR; import static org.elasticsearch.rest.RestStatus.OK;
package pl.suchenia.elasticsearchPrometheusMetrics; @FunctionalInterface public interface StringBufferedRestHandler extends RestHandler { @Override default void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception { generateResponse(channel, client) .thenAccept((writer) ->channel.sendResponse(new BytesRestResponse(OK, "text/plain; version=0.0.4; charset=utf-8", writer.toString()))) .exceptionally((e) -> { channel.sendResponse(new BytesRestResponse(INTERNAL_SERVER_ERROR, "text/plain; charset=utf-8", e.toString())); return null; }); }
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/StringBufferedRestHandler.java import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.RestChannel; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestRequest; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import java.util.concurrent.CompletableFuture; import static org.elasticsearch.rest.RestStatus.INTERNAL_SERVER_ERROR; import static org.elasticsearch.rest.RestStatus.OK; package pl.suchenia.elasticsearchPrometheusMetrics; @FunctionalInterface public interface StringBufferedRestHandler extends RestHandler { @Override default void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception { generateResponse(channel, client) .thenAccept((writer) ->channel.sendResponse(new BytesRestResponse(OK, "text/plain; version=0.0.4; charset=utf-8", writer.toString()))) .exceptionally((e) -> { channel.sendResponse(new BytesRestResponse(INTERNAL_SERVER_ERROR, "text/plain; charset=utf-8", e.toString())); return null; }); }
CompletableFuture<PrometheusFormatWriter> generateResponse(RestChannel channel, NodeClient client);
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ThreadPoolMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.threadpool.ThreadPoolStats; import org.elasticsearch.threadpool.ThreadPoolStats.Stats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ThreadPoolMetricsGenerator extends MetricsGenerator<ThreadPoolStats> { private static final Logger logger = Loggers.getLogger(ThreadPoolMetricsGenerator.class, "init"); private static final String LABEL_NAME = "threadpool"; @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ThreadPoolMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.threadpool.ThreadPoolStats; import org.elasticsearch.threadpool.ThreadPoolStats.Stats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ThreadPoolMetricsGenerator extends MetricsGenerator<ThreadPoolStats> { private static final Logger logger = Loggers.getLogger(ThreadPoolMetricsGenerator.class, "init"); private static final String LABEL_NAME = "threadpool"; @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ThreadPoolStats threadPoolStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ThreadPoolMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.threadpool.ThreadPoolStats; import org.elasticsearch.threadpool.ThreadPoolStats.Stats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ThreadPoolMetricsGenerator extends MetricsGenerator<ThreadPoolStats> { private static final Logger logger = Loggers.getLogger(ThreadPoolMetricsGenerator.class, "init"); private static final String LABEL_NAME = "threadpool"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ThreadPoolStats threadPoolStats) { logger.debug("Generating output for ThreadPool stats: {}", threadPoolStats);
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ThreadPoolMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.threadpool.ThreadPoolStats; import org.elasticsearch.threadpool.ThreadPoolStats.Stats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ThreadPoolMetricsGenerator extends MetricsGenerator<ThreadPoolStats> { private static final Logger logger = Loggers.getLogger(ThreadPoolMetricsGenerator.class, "init"); private static final String LABEL_NAME = "threadpool"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ThreadPoolStats threadPoolStats) { logger.debug("Generating output for ThreadPool stats: {}", threadPoolStats);
SingleValueWriter threads = writer.addGauge("es_threadpool_threads")
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterHealthMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.cluster.health.ClusterIndexHealth; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.Map;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ClusterHealthMetricsGenerator extends MetricsGenerator<ClusterHealthResponse> { private static final Logger logger = Loggers.getLogger(ClusterHealthMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterHealthMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.cluster.health.ClusterIndexHealth; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.Map; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class ClusterHealthMetricsGenerator extends MetricsGenerator<ClusterHealthResponse> { private static final Logger logger = Loggers.getLogger(ClusterHealthMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, ClusterHealthResponse clusterHealth) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterHealthMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.cluster.health.ClusterIndexHealth; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.Map;
//Nodes data writer.addGauge("es_nodes") .withHelp("Number of nodes in a cluster") .value(clusterHealth.getNumberOfNodes()); writer.addGauge("es_data_nodes") .withHelp("Number of data nodes in a cluster") .value(clusterHealth.getNumberOfDataNodes()); //Tasks data writer.addGauge("es_pending_tasks") .withHelp("Number of tasks pending") .value(clusterHealth.getNumberOfPendingTasks()); //Tasks data writer.addGauge("es_pending_inflight_fetch") .withHelp("Number of in-flight fetch") .value(clusterHealth.getNumberOfInFlightFetch()); //Cluster status writer.addGauge("es_status") .withHelp("Cluster status") .value(clusterHealth.getStatus().value()); writer.addGauge("es_status_type") .withHelp("Cluster status per type") .value(1, "status", clusterHealth.getStatus().name()); //Status for each index
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/ClusterHealthMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.cluster.health.ClusterIndexHealth; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; import java.util.Map; //Nodes data writer.addGauge("es_nodes") .withHelp("Number of nodes in a cluster") .value(clusterHealth.getNumberOfNodes()); writer.addGauge("es_data_nodes") .withHelp("Number of data nodes in a cluster") .value(clusterHealth.getNumberOfDataNodes()); //Tasks data writer.addGauge("es_pending_tasks") .withHelp("Number of tasks pending") .value(clusterHealth.getNumberOfPendingTasks()); //Tasks data writer.addGauge("es_pending_inflight_fetch") .withHelp("Number of in-flight fetch") .value(clusterHealth.getNumberOfInFlightFetch()); //Cluster status writer.addGauge("es_status") .withHelp("Cluster status") .value(clusterHealth.getStatus().value()); writer.addGauge("es_status_type") .withHelp("Cluster status per type") .value(1, "status", clusterHealth.getStatus().name()); //Status for each index
SingleValueWriter es_index_active_shards = writer.addGauge("es_index_active_shards")
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/CircuitBreakerMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.indices.breaker.AllCircuitBreakerStats; import org.elasticsearch.indices.breaker.CircuitBreakerStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class CircuitBreakerMetricsGenerator extends MetricsGenerator<AllCircuitBreakerStats> { private static final Logger logger = Loggers.getLogger(CircuitBreakerMetricsGenerator.class, "init"); private static final String LABEL_NAME = "circuit_name"; @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/CircuitBreakerMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.indices.breaker.AllCircuitBreakerStats; import org.elasticsearch.indices.breaker.CircuitBreakerStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class CircuitBreakerMetricsGenerator extends MetricsGenerator<AllCircuitBreakerStats> { private static final Logger logger = Loggers.getLogger(CircuitBreakerMetricsGenerator.class, "init"); private static final String LABEL_NAME = "circuit_name"; @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, AllCircuitBreakerStats allStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/CircuitBreakerMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.indices.breaker.AllCircuitBreakerStats; import org.elasticsearch.indices.breaker.CircuitBreakerStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class CircuitBreakerMetricsGenerator extends MetricsGenerator<AllCircuitBreakerStats> { private static final Logger logger = Loggers.getLogger(CircuitBreakerMetricsGenerator.class, "init"); private static final String LABEL_NAME = "circuit_name"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, AllCircuitBreakerStats allStats) { logger.debug("Generating data about circuit breaker: {}", allStats);
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/CircuitBreakerMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.indices.breaker.AllCircuitBreakerStats; import org.elasticsearch.indices.breaker.CircuitBreakerStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class CircuitBreakerMetricsGenerator extends MetricsGenerator<AllCircuitBreakerStats> { private static final Logger logger = Loggers.getLogger(CircuitBreakerMetricsGenerator.class, "init"); private static final String LABEL_NAME = "circuit_name"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, AllCircuitBreakerStats allStats) { logger.debug("Generating data about circuit breaker: {}", allStats);
SingleValueWriter circuitBreakerLimit = writer
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/IngestMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.ingest.IngestStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class IngestMetricsGenerator extends MetricsGenerator<IngestStats> { private static final Logger logger = Loggers.getLogger(IngestMetricsGenerator.class, "init"); @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/IngestMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.ingest.IngestStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class IngestMetricsGenerator extends MetricsGenerator<IngestStats> { private static final Logger logger = Loggers.getLogger(IngestMetricsGenerator.class, "init"); @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, IngestStats ingestStats) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/IngestMetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.ingest.IngestStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class IngestMetricsGenerator extends MetricsGenerator<IngestStats> { private static final Logger logger = Loggers.getLogger(IngestMetricsGenerator.class, "init"); @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, IngestStats ingestStats) { logger.debug("Generating metrics about ingest stats: {}", ingestStats); writer.addCounter("es_ingest_total_count") .withHelp("Total number of processed documents during ingestion phase") .value(ingestStats.getTotalStats().getIngestCount()); writer.addCounter("es_ingest_total_time_seconds") .withHelp("Total time spend on processed documents during ingestion phase") .value(ingestStats.getTotalStats().getIngestTimeInMillis() / 1000); writer.addGauge("es_ingest_total_current") .withHelp("The total number of ingest preprocessing operations that have failed") .value(ingestStats.getTotalStats().getIngestCurrent()); writer.addGauge("es_ingest_total_failed_count") .withHelp("The total number of ingest preprocessing operations that have failed") .value(ingestStats.getTotalStats().getIngestFailedCount());
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/IngestMetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.ingest.IngestStats; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class IngestMetricsGenerator extends MetricsGenerator<IngestStats> { private static final Logger logger = Loggers.getLogger(IngestMetricsGenerator.class, "init"); @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, IngestStats ingestStats) { logger.debug("Generating metrics about ingest stats: {}", ingestStats); writer.addCounter("es_ingest_total_count") .withHelp("Total number of processed documents during ingestion phase") .value(ingestStats.getTotalStats().getIngestCount()); writer.addCounter("es_ingest_total_time_seconds") .withHelp("Total time spend on processed documents during ingestion phase") .value(ingestStats.getTotalStats().getIngestTimeInMillis() / 1000); writer.addGauge("es_ingest_total_current") .withHelp("The total number of ingest preprocessing operations that have failed") .value(ingestStats.getTotalStats().getIngestCurrent()); writer.addGauge("es_ingest_total_failed_count") .withHelp("The total number of ingest preprocessing operations that have failed") .value(ingestStats.getTotalStats().getIngestFailedCount());
SingleValueWriter es_ingest_pipeline_count = writer.addCounter("es_ingest_pipeline_count")
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/NodeUsageGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.node.usage.NodeUsage; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class NodeUsageGenerator extends MetricsGenerator<NodeUsage> { private static final Logger logger = Loggers.getLogger(NodeUsageGenerator.class, "init"); private static final String ENDPOINT_LABEL = "endpoint"; @Override
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/NodeUsageGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.node.usage.NodeUsage; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class NodeUsageGenerator extends MetricsGenerator<NodeUsage> { private static final Logger logger = Loggers.getLogger(NodeUsageGenerator.class, "init"); private static final String ENDPOINT_LABEL = "endpoint"; @Override
public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, NodeUsage nodeUsage) {
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/NodeUsageGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.node.usage.NodeUsage; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class NodeUsageGenerator extends MetricsGenerator<NodeUsage> { private static final Logger logger = Loggers.getLogger(NodeUsageGenerator.class, "init"); private static final String ENDPOINT_LABEL = "endpoint"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, NodeUsage nodeUsage) { logger.debug("Generating output for REST usage: {}", nodeUsage);
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/SingleValueWriter.java // public final class SingleValueWriter { // private final ValueWriter valueWriter; // private final String name; // // SingleValueWriter(StringWriter writer, String name, Map<String, String> globalLabels) { // this.valueWriter = new ValueWriter(writer, globalLabels); // this.name = name; // } // // public SingleValueWriter withSharedLabel(String labelName, String labelValue) { // valueWriter.addSharedLabel(labelName, labelValue); // return this; // } // // public void value(double value) { // this.value(value, Collections.emptyMap()); // } // // public SingleValueWriter value(double value, Map<String, String> labels) { // valueWriter.writeValue(name, value, labels); // return this; // } // // // public SingleValueWriter value(double value, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // // return this.value(value, paramsMap); // } // // // // public void summary(long collectionCount, long millis, String...labels) { // if (labels.length % 2 != 0) { // throw new IllegalArgumentException("Wrong number of labels, should be in pairs.."); // } // Map<String, String> paramsMap = new LinkedHashMap<>(); // for (int i = 0; i < labels.length; i++) { // paramsMap.put(labels[i], labels[++i]); // } // valueWriter.writeValue(name + "_count", collectionCount, paramsMap); // valueWriter.writeValue(name + "_sum", millis, paramsMap); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/NodeUsageGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.node.usage.NodeUsage; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import pl.suchenia.elasticsearchPrometheusMetrics.writer.SingleValueWriter; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public class NodeUsageGenerator extends MetricsGenerator<NodeUsage> { private static final Logger logger = Loggers.getLogger(NodeUsageGenerator.class, "init"); private static final String ENDPOINT_LABEL = "endpoint"; @Override public PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, NodeUsage nodeUsage) { logger.debug("Generating output for REST usage: {}", nodeUsage);
SingleValueWriter restActions = writer.addCounter("es_rest_count")
jsuchenia/elasticsearch-prometheus-metrics
elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/MetricsGenerator.java
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // }
import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
package pl.suchenia.elasticsearchPrometheusMetrics.generators; public abstract class MetricsGenerator<T> { private static final Logger logger = Loggers.getLogger(MetricsGenerator.class, "init"); static double getDynamicValue(Object obj, String methodName) { try { Method method = obj.getClass().getMethod(methodName); Object value = method.invoke(obj); if (value.getClass().isAssignableFrom(Long.class)) { Long l = (Long) value; return l.doubleValue(); } return (double) value; } catch (NoSuchMethodException e) { logger.error("There are no getTotalSizeInBytes method defined"); return -1.0; } catch (IllegalAccessException | InvocationTargetException | ClassCastException e) { logger.error("Exception during method invocation: {}", e.getMessage()); return -1.0; } }
// Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/writer/PrometheusFormatWriter.java // public class PrometheusFormatWriter { // private final StringWriter writer = new StringWriter(); // private final Map<String, String> globalLabels; // // public PrometheusFormatWriter(Map<String, String> globalLabels) { // this.globalLabels = globalLabels; // } // // public SingleMetricsDefinitionBuilder addGauge(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.GAUGE, writer, name, globalLabels); // } // // public SingleMetricsDefinitionBuilder addCounter(String name) { // return new SingleMetricsDefinitionBuilder(MetricType.COUNTER, writer, name, globalLabels); // } // // public SummaryMetricsDefinitionBuilder addSummary(String name) { // return new SummaryMetricsDefinitionBuilder(writer, name, globalLabels); // } // // public String toString() { // return writer.toString(); // } // } // Path: elasticsearch-plugin/src/main/java/pl/suchenia/elasticsearchPrometheusMetrics/generators/MetricsGenerator.java import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import pl.suchenia.elasticsearchPrometheusMetrics.writer.PrometheusFormatWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; package pl.suchenia.elasticsearchPrometheusMetrics.generators; public abstract class MetricsGenerator<T> { private static final Logger logger = Loggers.getLogger(MetricsGenerator.class, "init"); static double getDynamicValue(Object obj, String methodName) { try { Method method = obj.getClass().getMethod(methodName); Object value = method.invoke(obj); if (value.getClass().isAssignableFrom(Long.class)) { Long l = (Long) value; return l.doubleValue(); } return (double) value; } catch (NoSuchMethodException e) { logger.error("There are no getTotalSizeInBytes method defined"); return -1.0; } catch (IllegalAccessException | InvocationTargetException | ClassCastException e) { logger.error("Exception during method invocation: {}", e.getMessage()); return -1.0; } }
public abstract PrometheusFormatWriter generateMetrics(PrometheusFormatWriter writer, T inputData);
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/FieldAssignmentFactory.java
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // }
import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Field;
package com.jenkov.container.impl.factory; /** */ public class FieldAssignmentFactory extends LocalFactoryBase implements ILocalFactory { protected Field field = null; protected Class fieldOwningClass = null; protected ILocalFactory fieldAssignmentTargetFactory = null; protected ILocalFactory assignmentValueFactory = null; public FieldAssignmentFactory(Field field, ILocalFactory assignmentTargetFactory, ILocalFactory assignmentValueFactory) { this.field = field; this.fieldAssignmentTargetFactory = assignmentTargetFactory; this.assignmentValueFactory = assignmentValueFactory; } public FieldAssignmentFactory(Field field, Class fieldOwningClass, ILocalFactory assignmentValueFactory) { this.field = field; this.fieldOwningClass = fieldOwningClass; this.assignmentValueFactory = assignmentValueFactory; } public Class getReturnType() { return this.field.getType(); } /* todo clean up this method. Field can never be void return types. Fields always have a type. */ public Object instance(Object[] parameters, Object[] localProducts) { Object value = this.assignmentValueFactory.instance(parameters, localProducts); try { if(isInstanceField()) { field.set(this.fieldAssignmentTargetFactory.instance(parameters, localProducts), value); return value; } field.set(null, value); return value; } catch (Throwable t){
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // Path: src/main/java/com/jenkov/container/impl/factory/FieldAssignmentFactory.java import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Field; package com.jenkov.container.impl.factory; /** */ public class FieldAssignmentFactory extends LocalFactoryBase implements ILocalFactory { protected Field field = null; protected Class fieldOwningClass = null; protected ILocalFactory fieldAssignmentTargetFactory = null; protected ILocalFactory assignmentValueFactory = null; public FieldAssignmentFactory(Field field, ILocalFactory assignmentTargetFactory, ILocalFactory assignmentValueFactory) { this.field = field; this.fieldAssignmentTargetFactory = assignmentTargetFactory; this.assignmentValueFactory = assignmentValueFactory; } public FieldAssignmentFactory(Field field, Class fieldOwningClass, ILocalFactory assignmentValueFactory) { this.field = field; this.fieldOwningClass = fieldOwningClass; this.assignmentValueFactory = assignmentValueFactory; } public Class getReturnType() { return this.field.getType(); } /* todo clean up this method. Field can never be void return types. Fields always have a type. */ public Object instance(Object[] parameters, Object[] localProducts) { Object value = this.assignmentValueFactory.instance(parameters, localProducts); try { if(isInstanceField()) { field.set(this.fieldAssignmentTargetFactory.instance(parameters, localProducts), value); return value; } field.set(null, value); return value; } catch (Throwable t){
throw new FactoryException(
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/TestProduct.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // }
import com.jenkov.container.IContainer; import java.util.List; import java.util.Set; import java.net.URL;
package com.jenkov.container; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class TestProduct { public static final String FIELD_VALUE = "fieldValue"; protected TestProduct internalProduct = null; protected String value1 = null; protected String value2 = null; protected double decimal = 0; protected String[] stringArray = null; protected List list = null; protected Set set = null; protected URL[] urlArray = null; protected List<URL> urlList = null; protected List<Integer> integerList = null; protected String[] array1 = null; protected Integer[] array2 = null; protected TestProduct[] array3 = null; protected Class classValue = null; public int instanceInt = -1; public static int staticInt = -1;
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // Path: src/test/java/com/jenkov/container/TestProduct.java import com.jenkov.container.IContainer; import java.util.List; import java.util.Set; import java.net.URL; package com.jenkov.container; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class TestProduct { public static final String FIELD_VALUE = "fieldValue"; protected TestProduct internalProduct = null; protected String value1 = null; protected String value2 = null; protected double decimal = 0; protected String[] stringArray = null; protected List list = null; protected Set set = null; protected URL[] urlArray = null; protected List<URL> urlList = null; protected List<Integer> integerList = null; protected String[] array1 = null; protected Integer[] array2 = null; protected TestProduct[] array3 = null; protected Class classValue = null; public int instanceInt = -1; public static int staticInt = -1;
public IContainer container = null;
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/InjectThreadLocalTest.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // }
import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container;
package com.jenkov.container.script; /** */ public class InjectThreadLocalTest extends TestCase { public static final ThreadLocal<String> threadLocal = new ThreadLocal<String>(); protected String local3 = null; public void testInjectThreadLocal() throws InterruptedException {
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // } // Path: src/test/java/com/jenkov/container/script/InjectThreadLocalTest.java import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; package com.jenkov.container.script; /** */ public class InjectThreadLocalTest extends TestCase { public static final ThreadLocal<String> threadLocal = new ThreadLocal<String>(); protected String local3 = null; public void testInjectThreadLocal() throws InterruptedException {
final IContainer container = new Container();
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/InjectThreadLocalTest.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // }
import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container;
package com.jenkov.container.script; /** */ public class InjectThreadLocalTest extends TestCase { public static final ThreadLocal<String> threadLocal = new ThreadLocal<String>(); protected String local3 = null; public void testInjectThreadLocal() throws InterruptedException {
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // } // Path: src/test/java/com/jenkov/container/script/InjectThreadLocalTest.java import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; package com.jenkov.container.script; /** */ public class InjectThreadLocalTest extends TestCase { public static final ThreadLocal<String> threadLocal = new ThreadLocal<String>(); protected String local3 = null; public void testInjectThreadLocal() throws InterruptedException {
final IContainer container = new Container();
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/FactoryBuilder.java
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/script/ParserException.java // public class ParserException extends ContainerException { // // public ParserException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public ParserException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // }
import com.jenkov.container.itf.factory.ILocalFactory; import com.jenkov.container.script.ParserException; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class FactoryBuilder { // ConstructorFactory methods public ILocalFactory createConstructorFactory(String className, List<ILocalFactory> constructorArgFactories, Class[] forcedArgumentTypes){ Class theClass = FactoryUtil.getClassForName(className); if(theClass == null){
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/script/ParserException.java // public class ParserException extends ContainerException { // // public ParserException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public ParserException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // } // Path: src/main/java/com/jenkov/container/impl/factory/FactoryBuilder.java import com.jenkov.container.itf.factory.ILocalFactory; import com.jenkov.container.script.ParserException; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class FactoryBuilder { // ConstructorFactory methods public ILocalFactory createConstructorFactory(String className, List<ILocalFactory> constructorArgFactories, Class[] forcedArgumentTypes){ Class theClass = FactoryUtil.getClassForName(className); if(theClass == null){
throw new ParserException(
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/ConstructorFactory.java
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // }
import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List;
this.constructor = contructor; this.constructorArgFactories = contructorArgFactories; } public ConstructorFactory(Constructor constructor, ILocalFactory[] constructorArgFactories){ this.constructor = constructor; for(ILocalFactory factory : constructorArgFactories){ this.constructorArgFactories.add(factory); } } public Constructor getConstructor() { return constructor; } public List<ILocalFactory> getConstructorArgFactories() { return constructorArgFactories; } public Class getReturnType() { return this.constructor.getDeclaringClass(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.constructorArgFactories, parameters, localProducts); Object returnValue = null; try { returnValue = this.constructor.newInstance(arguments); } catch (Throwable t){
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // Path: src/main/java/com/jenkov/container/impl/factory/ConstructorFactory.java import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; this.constructor = contructor; this.constructorArgFactories = contructorArgFactories; } public ConstructorFactory(Constructor constructor, ILocalFactory[] constructorArgFactories){ this.constructor = constructor; for(ILocalFactory factory : constructorArgFactories){ this.constructorArgFactories.add(factory); } } public Constructor getConstructor() { return constructor; } public List<ILocalFactory> getConstructorArgFactories() { return constructorArgFactories; } public Class getReturnType() { return this.constructor.getDeclaringClass(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.constructorArgFactories, parameters, localProducts); Object returnValue = null; try { returnValue = this.constructor.newInstance(arguments); } catch (Throwable t){
throw new FactoryException(
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/Bugs.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // }
import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream;
package com.jenkov.container.script; /** */ public class Bugs extends TestCase { public void testExtraParanthesesErrorMessage(){
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // } // Path: src/test/java/com/jenkov/container/script/Bugs.java import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; package com.jenkov.container.script; /** */ public class Bugs extends TestCase { public void testExtraParanthesesErrorMessage(){
IContainer container = new Container();
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/Bugs.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // }
import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream;
package com.jenkov.container.script; /** */ public class Bugs extends TestCase { public void testExtraParanthesesErrorMessage(){
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // } // Path: src/test/java/com/jenkov/container/script/Bugs.java import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; package com.jenkov.container.script; /** */ public class Bugs extends TestCase { public void testExtraParanthesesErrorMessage(){
IContainer container = new Container();
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/FactoryUtil.java
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // }
import com.jenkov.container.impl.factory.convert.*; import com.jenkov.container.itf.factory.ILocalFactory; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Set; import java.math.BigInteger; import java.math.BigDecimal;
if("Short".equals(className)) return Short.class; if("char".equals(className)) return char.class; if("Character".equals(className)) return Character.class; if("int".equals(className)) return int.class; if("Integer".equals(className)) return Integer.class; if("long".equals(className)) return long.class; if("Long".equals(className)) return Long.class; if("float".equals(className)) return float.class; if("Float".equals(className)) return Float.class; if("double".equals(className)) return double.class; if("Double".equals(className)) return Double.class; if("BigInteger".equals(className)) return BigInteger.class; if("BigDecimal".equals(className)) return BigDecimal.class; if("URL".equals(className)) return URL.class; try { return Class.forName(className); } catch (ClassNotFoundException e) { return null; } } public static Class[] createEmptyClassArray(int size) { Class[] forcedArgumentTypes = new Class[size]; for(int i=0; i<forcedArgumentTypes.length; i++) forcedArgumentTypes[i] = null; return forcedArgumentTypes; } //todo add ISO date formats
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // Path: src/main/java/com/jenkov/container/impl/factory/FactoryUtil.java import com.jenkov.container.impl.factory.convert.*; import com.jenkov.container.itf.factory.ILocalFactory; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Set; import java.math.BigInteger; import java.math.BigDecimal; if("Short".equals(className)) return Short.class; if("char".equals(className)) return char.class; if("Character".equals(className)) return Character.class; if("int".equals(className)) return int.class; if("Integer".equals(className)) return Integer.class; if("long".equals(className)) return long.class; if("Long".equals(className)) return Long.class; if("float".equals(className)) return float.class; if("Float".equals(className)) return Float.class; if("double".equals(className)) return double.class; if("Double".equals(className)) return Double.class; if("BigInteger".equals(className)) return BigInteger.class; if("BigDecimal".equals(className)) return BigDecimal.class; if("URL".equals(className)) return URL.class; try { return Class.forName(className); } catch (ClassNotFoundException e) { return null; } } public static Class[] createEmptyClassArray(int size) { Class[] forcedArgumentTypes = new Class[size]; for(int i=0; i<forcedArgumentTypes.length; i++) forcedArgumentTypes[i] = null; return forcedArgumentTypes; } //todo add ISO date formats
public static ILocalFactory createConversionFactory(ILocalFactory sourceFactory, Class returnType){
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/convert/UrlFactory.java
// Path: src/main/java/com/jenkov/container/impl/factory/LocalFactoryBase.java // public abstract class LocalFactoryBase implements ILocalFactory { // // public abstract Class getReturnType(); // // public abstract Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // }
import com.jenkov.container.impl.factory.LocalFactoryBase; import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.net.MalformedURLException; import java.net.URL;
package com.jenkov.container.impl.factory.convert; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class UrlFactory extends LocalFactoryBase implements ILocalFactory { protected ILocalFactory sourceFactory = null; public UrlFactory(ILocalFactory sourceFactory) { this.sourceFactory = sourceFactory; } public Class getReturnType() { return URL.class; } public Object instance(Object[] parameters, Object[] localProducts) { Object urlSource = null; try { urlSource = this.sourceFactory.instance(parameters, localProducts); return new URL(urlSource.toString()); } catch (MalformedURLException e) {
// Path: src/main/java/com/jenkov/container/impl/factory/LocalFactoryBase.java // public abstract class LocalFactoryBase implements ILocalFactory { // // public abstract Class getReturnType(); // // public abstract Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // Path: src/main/java/com/jenkov/container/impl/factory/convert/UrlFactory.java import com.jenkov.container.impl.factory.LocalFactoryBase; import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.net.MalformedURLException; import java.net.URL; package com.jenkov.container.impl.factory.convert; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class UrlFactory extends LocalFactoryBase implements ILocalFactory { protected ILocalFactory sourceFactory = null; public UrlFactory(ILocalFactory sourceFactory) { this.sourceFactory = sourceFactory; } public Class getReturnType() { return URL.class; } public Object instance(Object[] parameters, Object[] localProducts) { Object urlSource = null; try { urlSource = this.sourceFactory.instance(parameters, localProducts); return new URL(urlSource.toString()); } catch (MalformedURLException e) {
throw new FactoryException(
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/TestThread.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // }
import com.jenkov.container.IContainer;
package com.jenkov.container.script; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class TestThread extends Thread{ protected Object instance1 = null; protected Object instance2 = null; protected String string1 = null; protected String string2 = null;
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // Path: src/test/java/com/jenkov/container/script/TestThread.java import com.jenkov.container.IContainer; package com.jenkov.container.script; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class TestThread extends Thread{ protected Object instance1 = null; protected Object instance2 = null; protected String string1 = null; protected String string2 = null;
protected IContainer container = null;
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/FieldFactory.java
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // }
import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType;
package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class FieldFactory extends LocalFactoryBase implements ILocalFactory { protected Field field = null; protected Object fieldOwner = null; protected ILocalFactory fieldOwnerFactory = null; public FieldFactory(Field method) { this.field = method; } public FieldFactory(Field field, Object fieldOwner) { this.field = field; this.fieldOwner = fieldOwner; } public FieldFactory(Field field, ILocalFactory fieldOwnerFactory) { this.field = field; this.fieldOwnerFactory = fieldOwnerFactory; } public Class getReturnType() { return this.field.getType(); } public Object instance(Object[] parameters, Object[] localProducts) { try { if(this.fieldOwnerFactory != null){ return this.field.get(this.fieldOwnerFactory.instance(parameters, localProducts)); } return this.field.get(this.fieldOwner); } catch (IllegalAccessException e) {
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // Path: src/main/java/com/jenkov/container/impl/factory/FieldFactory.java import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class FieldFactory extends LocalFactoryBase implements ILocalFactory { protected Field field = null; protected Object fieldOwner = null; protected ILocalFactory fieldOwnerFactory = null; public FieldFactory(Field method) { this.field = method; } public FieldFactory(Field field, Object fieldOwner) { this.field = field; this.fieldOwner = fieldOwner; } public FieldFactory(Field field, ILocalFactory fieldOwnerFactory) { this.field = field; this.fieldOwnerFactory = fieldOwnerFactory; } public Class getReturnType() { return this.field.getType(); } public Object instance(Object[] parameters, Object[] localProducts) { try { if(this.fieldOwnerFactory != null){ return this.field.get(this.fieldOwnerFactory.instance(parameters, localProducts)); } return this.field.get(this.fieldOwner); } catch (IllegalAccessException e) {
throw new FactoryException(
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/FlyweightKey.java
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // }
import com.jenkov.container.itf.factory.FactoryException;
package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class FlyweightKey { Object[] parameters = null; int hashCode = 0; public FlyweightKey(Object[] parameters) { this.parameters = parameters; for(int i=0; i< parameters.length; i++){
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // Path: src/main/java/com/jenkov/container/impl/factory/FlyweightKey.java import com.jenkov.container.itf.factory.FactoryException; package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class FlyweightKey { Object[] parameters = null; int hashCode = 0; public FlyweightKey(Object[] parameters) { this.parameters = parameters; for(int i=0; i< parameters.length; i++){
if(parameters[i] == null) throw new FactoryException(
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/StaticMethodFactory.java
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // }
import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
package com.jenkov.container.impl.factory; /** */ public class StaticMethodFactory extends LocalFactoryBase implements ILocalFactory { protected Method method = null; protected List<ILocalFactory> methodArgFactories = new ArrayList<ILocalFactory>(); public StaticMethodFactory(Method method, List<ILocalFactory> methodArgFactories) { if(method == null) throw new IllegalArgumentException("Method cannot be null"); this.method = method; this.methodArgFactories = methodArgFactories; } public Class getReturnType() { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ return Class.class; } return this.method.getReturnType(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.methodArgFactories, parameters, localProducts); try { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. Object returnValue = method.invoke(null, arguments); if(isVoidReturnType()){ return null; } return returnValue; } catch(NullPointerException e){
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // Path: src/main/java/com/jenkov/container/impl/factory/StaticMethodFactory.java import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; package com.jenkov.container.impl.factory; /** */ public class StaticMethodFactory extends LocalFactoryBase implements ILocalFactory { protected Method method = null; protected List<ILocalFactory> methodArgFactories = new ArrayList<ILocalFactory>(); public StaticMethodFactory(Method method, List<ILocalFactory> methodArgFactories) { if(method == null) throw new IllegalArgumentException("Method cannot be null"); this.method = method; this.methodArgFactories = methodArgFactories; } public Class getReturnType() { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ return Class.class; } return this.method.getReturnType(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.methodArgFactories, parameters, localProducts); try { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. Object returnValue = method.invoke(null, arguments); if(isVoidReturnType()){ return null; } return returnValue; } catch(NullPointerException e){
throw new FactoryException(
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/LocalizedResourceFactory.java
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/itf/factory/IGlobalFactory.java // public interface IGlobalFactory<T> { // // public Class getReturnType(); // // // /** // * Returns an instance of whatever component this global factory produces // * // * @param parameters Any parameters needed by the factory to create its instance. // * @return The object instance as created by the facttory. // */ // public T instance(Object ... parameters); // // /** // * This method is called by the container when executing a phase in a factory that supports life cycle phases. // * The container knows nothing about local products, therefore this method is called. Only the concrete // * factory knows about cached local products (if any). // * // * <br/><br/> // * This is the method a global factory will override when implementing life cycle phase behaviour, e.g. for // * cached objects. // * // * @param phase The name of the phase to execute. For instance, "config" or "dispose". // * @param parameters The parameters passed to the container when the phase begins. For instance to // * an instance() method call, or an execPhase(phase, factory, parameters) call. // * @return Null, or the local products the phase ends up being executed on. If executed // * for several local product arrays (e.g. in pools or flyweights), null will be returned, since it does not // * make sense to return anything. Returning anything would only make sense for // * the "create" phase, but currently this phase does not use the execPhase() method // * to carry out its work. It uses the factory.instance() methods instead. // */ // public Object[] execPhase(String phase, Object ... parameters); // // // }
import com.jenkov.container.itf.factory.ILocalFactory; import com.jenkov.container.itf.factory.IGlobalFactory; import java.util.Map; import java.util.Locale;
package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class LocalizedResourceFactory extends LocalFactoryBase implements ILocalFactory { protected ILocalFactory resourceMapFactory = null;
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/itf/factory/IGlobalFactory.java // public interface IGlobalFactory<T> { // // public Class getReturnType(); // // // /** // * Returns an instance of whatever component this global factory produces // * // * @param parameters Any parameters needed by the factory to create its instance. // * @return The object instance as created by the facttory. // */ // public T instance(Object ... parameters); // // /** // * This method is called by the container when executing a phase in a factory that supports life cycle phases. // * The container knows nothing about local products, therefore this method is called. Only the concrete // * factory knows about cached local products (if any). // * // * <br/><br/> // * This is the method a global factory will override when implementing life cycle phase behaviour, e.g. for // * cached objects. // * // * @param phase The name of the phase to execute. For instance, "config" or "dispose". // * @param parameters The parameters passed to the container when the phase begins. For instance to // * an instance() method call, or an execPhase(phase, factory, parameters) call. // * @return Null, or the local products the phase ends up being executed on. If executed // * for several local product arrays (e.g. in pools or flyweights), null will be returned, since it does not // * make sense to return anything. Returning anything would only make sense for // * the "create" phase, but currently this phase does not use the execPhase() method // * to carry out its work. It uses the factory.instance() methods instead. // */ // public Object[] execPhase(String phase, Object ... parameters); // // // } // Path: src/main/java/com/jenkov/container/impl/factory/LocalizedResourceFactory.java import com.jenkov.container.itf.factory.ILocalFactory; import com.jenkov.container.itf.factory.IGlobalFactory; import java.util.Map; import java.util.Locale; package com.jenkov.container.impl.factory; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class LocalizedResourceFactory extends LocalFactoryBase implements ILocalFactory { protected ILocalFactory resourceMapFactory = null;
protected IGlobalFactory localeFactory = null;
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/MathMaxTest.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // }
import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container;
package com.jenkov.container.script; /** */ public class MathMaxTest extends TestCase{ public void test(){
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // } // Path: src/test/java/com/jenkov/container/script/MathMaxTest.java import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; package com.jenkov.container.script; /** */ public class MathMaxTest extends TestCase{ public void test(){
IContainer container = new Container();
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/MathMaxTest.java
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // }
import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container;
package com.jenkov.container.script; /** */ public class MathMaxTest extends TestCase{ public void test(){
// Path: src/main/java/com/jenkov/container/IContainer.java // public interface IContainer { // // /** // * Adds a factory to the container using the given name. // * @param name A name to identify the factory by. // * @param factory A factory producing some component. // */ // public void addFactory(String name, IGlobalFactory factory); // // /** // * Adds a value factory to the container using the given name. // * A value factory just returns the value passed in the value parameter. // * Thus the value object becomes a singleton. // * Value factories can be used to add constants or configuration parameters to the container, // * though these can also be added in scripts. // * // * @param name The name to identify the factory by. // * @param value The value the value factory is to return (as a singleton). // */ // public void addValueFactory(String name, Object value); // // /** // * Replaces the existing factory with the given name, with the new factory passed as parameter. // * All factories referencing the old factory will hereafter reference the new factory. // * @param name The name of the factory to replace. // * @param newFactory The new factory that is to replace the old. // * @return The old factory - the one that was replaced. // */ // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory); // // /** // * Removes the factory identified by the given name from the container. // * @param name The name identifying the factory to remove. // */ // public void removeFactory(String name); // // /** // * Returns the factory identified by the given name. // * @param name The name identifying the factory to return. // * @return The factory identified by the given name. // */ // public IGlobalFactory getFactory(String name); // // /** // * Returns a Map containing all the factories in this container. // * @return A Map containing all the factories in this container. // */ // public Map<String, IGlobalFactory> getFactories(); // // /** // * Returns instance of whatever component the factory identified by the given // * name produces. // * @param name The name of the factory to obtain an instance from. // * @param parameters Any parameters needed by the factory to produce the component instance. // * @return An instance of the component the factory identified by the given name produces. // */ // public Object instance(String name, Object ... parameters); // // /** // * Initializes the container. Currently this means creating all singletons and other cached instances. // */ // public void init(); // // /** // * Executes the given life cycle phase on all factories in the container. // * @param phase The name of the life cycle phase to execute ("config", "dipose" etc.) // */ // public void execPhase(String phase); // // /** // * Executes the given life cycle phase on the factory identified by the given name. // * @param phase The name of the life cycle phase to execute ("config", "dispose" etc.) // * @param name The name of the factory to execute the life cycle phase on. // */ // public void execPhase(String phase, String name); // // /** // * Executes the "dispose" life cycle phase on all factories in the container. // */ // public void dispose(); // // } // // Path: src/main/java/com/jenkov/container/Container.java // public class Container implements IContainer { // // protected Map<String, IGlobalFactory> factories = null; // // public Container() { // this.factories = new ConcurrentHashMap<String, IGlobalFactory>(); // } // // public Container(Map<String, IGlobalFactory> factories) { // this.factories = factories; // } // // // public void addFactory(String name, IGlobalFactory factory) { // if(this.factories.containsKey(name)) throw // new ContainerException( // "Container", "FACTORY_ALREADY_EXISTS", // "Container already contains a factory with this name: " + name); // this.factories.put(name, new GlobalFactoryProxy(factory)); // } // // public void addValueFactory(String id, Object value){ // GlobalFactoryBase factory = new GlobalNewInstanceFactory(); // factory.setLocalInstantiationFactory(new ValueFactory(value)); // this.factories.put(id, new GlobalFactoryProxy(factory)); // } // // public IGlobalFactory replaceFactory(String name, IGlobalFactory newFactory){ // GlobalFactoryProxy factoryProxy = (GlobalFactoryProxy) this.factories.get(name); // if(factoryProxy == null) { // addFactory(name, newFactory); // return null; // } else { // return factoryProxy.setDelegateFactory(newFactory); // } // } // // public void removeFactory(String id) { // this.factories.remove(id); // } // // public IGlobalFactory getFactory(String id) { // IGlobalFactory factory = this.factories.get(id); // //if(factory == null) throw new ContainerException("Unknown Factory: " + id); // return factory; // } // // public Map<String, IGlobalFactory> getFactories() { // return this.factories; // } // // public Object instance(String id, Object ... parameters){ // IGlobalFactory factory = this.factories.get(id); // if(factory == null) throw new ContainerException( // "Container", "UNKNOWN_FACTORY", // "Unknown Factory: " + id); // return factory.instance(parameters); // } // // public void init(){ // for(String key : this.factories.keySet()){ // Object factory = this.factories.get(key); // // if(factory instanceof GlobalFactoryProxy){ // factory = ((GlobalFactoryProxy) factory).getDelegateFactory(); // if(factory instanceof GlobalSingletonFactory){ // ((GlobalSingletonFactory) factory).instance(); // } // } // } // } // // public void dispose(){ // execPhase("dispose"); // } // // public void execPhase(String phase) { // for(String key : this.factories.keySet()){ // execPhase(phase, key); // } // } // // public void execPhase(String phase, String factoryName) { // Object factory = this.factories.get(factoryName); // if(factory instanceof GlobalFactoryProxy){ // ((GlobalFactoryProxy) factory).execPhase(phase); // } // } // // // } // Path: src/test/java/com/jenkov/container/script/MathMaxTest.java import junit.framework.TestCase; import com.jenkov.container.IContainer; import com.jenkov.container.Container; package com.jenkov.container.script; /** */ public class MathMaxTest extends TestCase{ public void test(){
IContainer container = new Container();
jjenkov/butterfly-di-container
src/test/java/com/jenkov/container/script/FieldGenericTypeTest.java
// Path: src/test/java/com/jenkov/container/TestProduct.java // public class TestProduct { // // public static final String FIELD_VALUE = "fieldValue"; // // protected TestProduct internalProduct = null; // protected String value1 = null; // protected String value2 = null; // protected double decimal = 0; // // protected String[] stringArray = null; // protected List list = null; // protected Set set = null; // protected URL[] urlArray = null; // protected List<URL> urlList = null; // protected List<Integer> integerList = null; // // protected String[] array1 = null; // protected Integer[] array2 = null; // protected TestProduct[] array3 = null; // // protected Class classValue = null; // // public int instanceInt = -1; // public static int staticInt = -1; // // public IContainer container = null; // public ICustomFactory factory = null; // // public static IContainer staticContainer = null; // public static ICustomFactory staticFactory = null; // // public List<Integer> genericListInt = null; // public List<URL> genericListUrl = null; // public List normalList = null; // // // public static TestProduct createProduct(){ // return new TestProduct(); // } // // public static TestProduct createProduct(TestProduct product){ // return new TestProduct(product); // } // // public TestProduct() { // } // // public TestProduct(TestProduct product){ // this.internalProduct = product; // } // // public TestProduct(ICustomFactory factory) { // this.factory = factory; // } // // public TestProduct(IContainer container) { // this.container = container; // } // // public TestProduct getInternalProduct() { // return internalProduct; // } // // public String getValue1() { // return value1; // } // // public void setValue1(String value1) { // this.value1 = value1; // } // // public String getValue2() { // return value2; // } // // public void setValue2(String value2) { // this.value2 = value2; // } // // public void setValues(String value1, Object value2){ // this.value1 = value1; // this.value2 = value2.toString(); // } // // public void setValues(String value1, String value2){ // this.value1 = value1; // this.value2 = value2; // } // // public void setIntValue(int lengthOfString){ // //System.out.println("length: " + lengthOfString); // } // // public double getDecimal() { // return decimal; // } // // public void setDecimal(double decimal) { // this.decimal = decimal; // } // // public Class getClassValue() { // return classValue; // } // // public void setClassValue(Class classValue) { // this.classValue = classValue; // } // // public void setFactory(ICustomFactory factory) { // this.factory = factory; // } // // public void setContainer(IContainer container) { // this.container = container; // } // // public static void setStaticContainer(IContainer staticContainer) { // TestProduct.staticContainer = staticContainer; // } // // public static void setStaticFactory(ICustomFactory staticFactory) { // TestProduct.staticFactory = staticFactory; // } // // public String[] getStringArray() { // return stringArray; // } // // public void setStringArray(String[] stringArray) { // this.stringArray = stringArray; // } // // public List getList() { // return list; // } // // public void setList(List<String> list) { // this.list = list; // } // // public Set getSet() { // return set; // } // // public void setSet(Set<String> set) { // this.set = set; // } // // public URL[] getUrlArray() { // return urlArray; // } // // public void setUrlArray(URL[] urlArray) { // this.urlArray = urlArray; // } // // public List<URL> getUrlList() { // return urlList; // } // // public void setUrlList(List<URL> urlList) { // this.urlList = urlList; // } // // public List<Integer> getIntegerList() { // return integerList; // } // // public void setIntegerList(List<Integer> integerList) { // this.integerList = integerList; // } // // public String[] getArray1() { // return array1; // } // // public void setArray(String[] array1) { // this.array1 = array1; // } // // public Integer[] getArray2() { // return array2; // } // // public void setArray(Integer[] array2) { // this.array2 = array2; // } // // public TestProduct[] getArray3() { // return array3; // } // // public void setArray(TestProduct[] array3) { // this.array3 = array3; // } // // }
import junit.framework.TestCase; import com.jenkov.container.TestProduct; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType;
package com.jenkov.container.script; /** */ public class FieldGenericTypeTest extends TestCase { public void testGenericType() throws NoSuchFieldException {
// Path: src/test/java/com/jenkov/container/TestProduct.java // public class TestProduct { // // public static final String FIELD_VALUE = "fieldValue"; // // protected TestProduct internalProduct = null; // protected String value1 = null; // protected String value2 = null; // protected double decimal = 0; // // protected String[] stringArray = null; // protected List list = null; // protected Set set = null; // protected URL[] urlArray = null; // protected List<URL> urlList = null; // protected List<Integer> integerList = null; // // protected String[] array1 = null; // protected Integer[] array2 = null; // protected TestProduct[] array3 = null; // // protected Class classValue = null; // // public int instanceInt = -1; // public static int staticInt = -1; // // public IContainer container = null; // public ICustomFactory factory = null; // // public static IContainer staticContainer = null; // public static ICustomFactory staticFactory = null; // // public List<Integer> genericListInt = null; // public List<URL> genericListUrl = null; // public List normalList = null; // // // public static TestProduct createProduct(){ // return new TestProduct(); // } // // public static TestProduct createProduct(TestProduct product){ // return new TestProduct(product); // } // // public TestProduct() { // } // // public TestProduct(TestProduct product){ // this.internalProduct = product; // } // // public TestProduct(ICustomFactory factory) { // this.factory = factory; // } // // public TestProduct(IContainer container) { // this.container = container; // } // // public TestProduct getInternalProduct() { // return internalProduct; // } // // public String getValue1() { // return value1; // } // // public void setValue1(String value1) { // this.value1 = value1; // } // // public String getValue2() { // return value2; // } // // public void setValue2(String value2) { // this.value2 = value2; // } // // public void setValues(String value1, Object value2){ // this.value1 = value1; // this.value2 = value2.toString(); // } // // public void setValues(String value1, String value2){ // this.value1 = value1; // this.value2 = value2; // } // // public void setIntValue(int lengthOfString){ // //System.out.println("length: " + lengthOfString); // } // // public double getDecimal() { // return decimal; // } // // public void setDecimal(double decimal) { // this.decimal = decimal; // } // // public Class getClassValue() { // return classValue; // } // // public void setClassValue(Class classValue) { // this.classValue = classValue; // } // // public void setFactory(ICustomFactory factory) { // this.factory = factory; // } // // public void setContainer(IContainer container) { // this.container = container; // } // // public static void setStaticContainer(IContainer staticContainer) { // TestProduct.staticContainer = staticContainer; // } // // public static void setStaticFactory(ICustomFactory staticFactory) { // TestProduct.staticFactory = staticFactory; // } // // public String[] getStringArray() { // return stringArray; // } // // public void setStringArray(String[] stringArray) { // this.stringArray = stringArray; // } // // public List getList() { // return list; // } // // public void setList(List<String> list) { // this.list = list; // } // // public Set getSet() { // return set; // } // // public void setSet(Set<String> set) { // this.set = set; // } // // public URL[] getUrlArray() { // return urlArray; // } // // public void setUrlArray(URL[] urlArray) { // this.urlArray = urlArray; // } // // public List<URL> getUrlList() { // return urlList; // } // // public void setUrlList(List<URL> urlList) { // this.urlList = urlList; // } // // public List<Integer> getIntegerList() { // return integerList; // } // // public void setIntegerList(List<Integer> integerList) { // this.integerList = integerList; // } // // public String[] getArray1() { // return array1; // } // // public void setArray(String[] array1) { // this.array1 = array1; // } // // public Integer[] getArray2() { // return array2; // } // // public void setArray(Integer[] array2) { // this.array2 = array2; // } // // public TestProduct[] getArray3() { // return array3; // } // // public void setArray(TestProduct[] array3) { // this.array3 = array3; // } // // } // Path: src/test/java/com/jenkov/container/script/FieldGenericTypeTest.java import junit.framework.TestCase; import com.jenkov.container.TestProduct; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; package com.jenkov.container.script; /** */ public class FieldGenericTypeTest extends TestCase { public void testGenericType() throws NoSuchFieldException {
Field listField = TestProduct.class.getField("normalList");
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/script/ScriptTokenizer.java
// Path: src/main/java/com/jenkov/container/script/ParserException.java // public class ParserException extends ContainerException { // // public ParserException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public ParserException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // }
import com.jenkov.container.script.ParserException;
} else { unread(next); return; } case 'F' : case 'T' : if(token.length() == 1 && token.charAt(0) == '1'){ //if is thread singleton or flyweight. append(token, (char) next); return; } default : unread(next); return; } } } private Token getToken() { Token token = inputBuffer.token(); return token; } /** * This method returns the same string instance per delimiter, instead of returning a new string instance * every time a delimiter is met. You can think of this method as a hardcoded flyweight (GOF pattern). * * @deprecated No longer used. */ private Token readSignificantDelimiter() { Token token = Token.delimiterToken((char) this.nextChar); if(token != null) return token;
// Path: src/main/java/com/jenkov/container/script/ParserException.java // public class ParserException extends ContainerException { // // public ParserException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public ParserException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // } // Path: src/main/java/com/jenkov/container/script/ScriptTokenizer.java import com.jenkov.container.script.ParserException; } else { unread(next); return; } case 'F' : case 'T' : if(token.length() == 1 && token.charAt(0) == '1'){ //if is thread singleton or flyweight. append(token, (char) next); return; } default : unread(next); return; } } } private Token getToken() { Token token = inputBuffer.token(); return token; } /** * This method returns the same string instance per delimiter, instead of returning a new string instance * every time a delimiter is met. You can think of this method as a hardcoded flyweight (GOF pattern). * * @deprecated No longer used. */ private Token readSignificantDelimiter() { Token token = Token.delimiterToken((char) this.nextChar); if(token != null) return token;
throw new ParserException(
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/InstanceMethodFactory.java
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // }
import com.jenkov.container.itf.factory.ILocalFactory; import com.jenkov.container.itf.factory.FactoryException; import java.lang.reflect.Method; import java.util.List; import java.util.ArrayList;
this.methodArgFactories = methodArgFactories; } public Class getReturnType() { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ return methodInvocationTargetFactory.getReturnType(); } return this.method.getReturnType(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.methodArgFactories, parameters, localProducts); try { Object target = this.methodInvocationTargetFactory.instance(parameters, localProducts); if(target == null){ throw new NullPointerException("The object call the method " + method.toString() + " on was null"); } Object returnValue = method.invoke(target, arguments); //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ return target; } else { return returnValue; } } catch (Throwable t){
// Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // // Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // Path: src/main/java/com/jenkov/container/impl/factory/InstanceMethodFactory.java import com.jenkov.container.itf.factory.ILocalFactory; import com.jenkov.container.itf.factory.FactoryException; import java.lang.reflect.Method; import java.util.List; import java.util.ArrayList; this.methodArgFactories = methodArgFactories; } public Class getReturnType() { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ return methodInvocationTargetFactory.getReturnType(); } return this.method.getReturnType(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.methodArgFactories, parameters, localProducts); try { Object target = this.methodInvocationTargetFactory.instance(parameters, localProducts); if(target == null){ throw new NullPointerException("The object call the method " + method.toString() + " on was null"); } Object returnValue = method.invoke(target, arguments); //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ return target; } else { return returnValue; } } catch (Throwable t){
throw new FactoryException(
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/impl/factory/MethodFactory.java
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // }
import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.List;
//} return this.method.getReturnType(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.methodArgFactories, parameters, localProducts); try { if(this.methodInvocationTargetFactory != null) { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ Object target = this.methodInvocationTargetFactory.instance(parameters, localProducts); if(target == null){ throw new NullPointerException("The object call the method " + method.toString() + " on was null"); } method.invoke(target, arguments); return target; } else { return method.invoke(this.methodInvocationTargetFactory.instance(parameters, localProducts), arguments); } } //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ method.invoke(this.methodInvocationTarget, arguments); return this.methodInvocationTarget; } return method.invoke(this.methodInvocationTarget, arguments); } catch (Throwable t){
// Path: src/main/java/com/jenkov/container/itf/factory/FactoryException.java // public class FactoryException extends ContainerException { // public FactoryException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public FactoryException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // // } // // Path: src/main/java/com/jenkov/container/itf/factory/ILocalFactory.java // public interface ILocalFactory { // // public Class getReturnType(); // // /** // * This method is intended to be called *internally between* factories when creating // * an instance of some class. It is not intended to be called directly by client code, // * or from the Container. For that purpose use the instance(Object ... parameters) // * method. If you do call this method directly, a null will suffice for the localProducts // * array. // * // * NOTE: Only called on local factories. Never on global factories. // * // * <br/><br/> // * If you develop a custom IFactory implementation you should // * extend LocalFactoryBase and override this method, not the instance(Object ... parameters) // * method. If your factory implementation calls any other factories it should pass on // * both the parameters and localProducts object arrays!! // * ... as in factory.instance(parameters, localProducts); . // * Do not just call the instance() or instance(parameters) method. // * // * @param parameters // * @param localProducts // * @return The created object. // */ // public Object instance(Object[] parameters, Object[] localProducts); // } // Path: src/main/java/com/jenkov/container/impl/factory/MethodFactory.java import com.jenkov.container.itf.factory.FactoryException; import com.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.List; //} return this.method.getReturnType(); } public Object instance(Object[] parameters, Object[] localProducts) { Object[] arguments = FactoryUtil.toArgumentArray(this.methodArgFactories, parameters, localProducts); try { if(this.methodInvocationTargetFactory != null) { //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ Object target = this.methodInvocationTargetFactory.instance(parameters, localProducts); if(target == null){ throw new NullPointerException("The object call the method " + method.toString() + " on was null"); } method.invoke(target, arguments); return target; } else { return method.invoke(this.methodInvocationTargetFactory.instance(parameters, localProducts), arguments); } } //if a method returns void, it should return the invocation target instead, enabling method chaining on methods returning void. if(isVoidReturnType()){ method.invoke(this.methodInvocationTarget, arguments); return this.methodInvocationTarget; } return method.invoke(this.methodInvocationTarget, arguments); } catch (Throwable t){
throw new FactoryException(
jjenkov/butterfly-di-container
src/main/java/com/jenkov/container/script/ParserInput.java
// Path: src/main/java/com/jenkov/container/script/ParserException.java // public class ParserException extends ContainerException { // // public ParserException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public ParserException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // }
import com.jenkov.container.script.ParserException; import java.io.*; import java.util.Stack;
package com.jenkov.container.script; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class ParserInput { protected ScriptTokenizer scriptTokenizer = null; protected Stack<ParserMark> marks = new Stack<ParserMark>(); /** * @deprecated Use the constructor that takes a Reader instead. * @param input */ public ParserInput(InputStream input) { this.scriptTokenizer = new ScriptTokenizer(new ScriptTokenizerInputBuffer(new InputStreamReader(input))); } public ParserInput(Reader reader) { this.scriptTokenizer = new ScriptTokenizer(new ScriptTokenizerInputBuffer(reader)); } public ParserInput(String input){ this.scriptTokenizer = new ScriptTokenizer(new ScriptTokenizerInputBuffer(new StringReader(input))); } public void factoryStart(){ this.scriptTokenizer.factoryStart(); } public boolean isNextElseBacktrack(Token expectedToken){ mark(); Token nextToken = nextToken(); boolean matches = expectedToken.equals(nextToken); if(matches) clearMark(); else backtrack(); return matches; } public void assertNextToken(Token token){ Token nextToken = nextToken(); if(nextToken == null || !nextToken.equals(token)){
// Path: src/main/java/com/jenkov/container/script/ParserException.java // public class ParserException extends ContainerException { // // public ParserException(String errorContext, String errorCode, String errorMessage) { // super(errorContext, errorCode, errorMessage); // } // // public ParserException(String errorContext, String errorCode, String errorMessage, Throwable cause) { // super(errorContext, errorCode, errorMessage, cause); // } // } // Path: src/main/java/com/jenkov/container/script/ParserInput.java import com.jenkov.container.script.ParserException; import java.io.*; import java.util.Stack; package com.jenkov.container.script; /** * @author Jakob Jenkov - Copyright 2004-2006 Jenkov Development */ public class ParserInput { protected ScriptTokenizer scriptTokenizer = null; protected Stack<ParserMark> marks = new Stack<ParserMark>(); /** * @deprecated Use the constructor that takes a Reader instead. * @param input */ public ParserInput(InputStream input) { this.scriptTokenizer = new ScriptTokenizer(new ScriptTokenizerInputBuffer(new InputStreamReader(input))); } public ParserInput(Reader reader) { this.scriptTokenizer = new ScriptTokenizer(new ScriptTokenizerInputBuffer(reader)); } public ParserInput(String input){ this.scriptTokenizer = new ScriptTokenizer(new ScriptTokenizerInputBuffer(new StringReader(input))); } public void factoryStart(){ this.scriptTokenizer.factoryStart(); } public boolean isNextElseBacktrack(Token expectedToken){ mark(); Token nextToken = nextToken(); boolean matches = expectedToken.equals(nextToken); if(matches) clearMark(); else backtrack(); return matches; } public void assertNextToken(Token token){ Token nextToken = nextToken(); if(nextToken == null || !nextToken.equals(token)){
throw new ParserException(
meethai/mithai
src/main/java/edu/sjsu/mithai/export/HttpExporterTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/http/HttpExporter.java // public class HttpExporter implements IExporter<ExportMessage> { // // private CloseableHttpClient client; // // public HttpExporter() { // } // // @Override // public void setup() throws Exception { // this.client = HttpClients.createDefault(); // } // // @Override // public void send(ExportMessage message) throws IOException { // // if (message instanceof HttpExportMessage) { // HttpExportMessage message1 = (HttpExportMessage) message; // System.out.println("Sending message over HTTP: " + message); // System.out.println("URI:" + message1.getUri()); // HttpPost post = new HttpPost(message1.getUri()); // post.addHeader("content-type", "application/json"); // post.setEntity(new StringEntity(message1.getMessage())); // CloseableHttpResponse response = client.execute(post); // System.out.println(response.getStatusLine()); // EntityUtils.consume(response.getEntity()); // } else { // System.out.println("HTTP message of type ExportMessage: " + message); // } // } // // @Override // public void tearDown() throws IOException { // client.close(); // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // }
import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.http.HttpExporter; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException;
package edu.sjsu.mithai.export; public class HttpExporterTask extends StoppableRunnableTask { private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); private static final String STOP_MESSAGE = "STOP";
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/http/HttpExporter.java // public class HttpExporter implements IExporter<ExportMessage> { // // private CloseableHttpClient client; // // public HttpExporter() { // } // // @Override // public void setup() throws Exception { // this.client = HttpClients.createDefault(); // } // // @Override // public void send(ExportMessage message) throws IOException { // // if (message instanceof HttpExportMessage) { // HttpExportMessage message1 = (HttpExportMessage) message; // System.out.println("Sending message over HTTP: " + message); // System.out.println("URI:" + message1.getUri()); // HttpPost post = new HttpPost(message1.getUri()); // post.addHeader("content-type", "application/json"); // post.setEntity(new StringEntity(message1.getMessage())); // CloseableHttpResponse response = client.execute(post); // System.out.println(response.getStatusLine()); // EntityUtils.consume(response.getEntity()); // } else { // System.out.println("HTTP message of type ExportMessage: " + message); // } // } // // @Override // public void tearDown() throws IOException { // client.close(); // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/java/edu/sjsu/mithai/export/HttpExporterTask.java import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.http.HttpExporter; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; package edu.sjsu.mithai.export; public class HttpExporterTask extends StoppableRunnableTask { private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); private static final String STOP_MESSAGE = "STOP";
private Configuration configuration;
meethai/mithai
src/main/java/edu/sjsu/mithai/export/HttpExporterTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/http/HttpExporter.java // public class HttpExporter implements IExporter<ExportMessage> { // // private CloseableHttpClient client; // // public HttpExporter() { // } // // @Override // public void setup() throws Exception { // this.client = HttpClients.createDefault(); // } // // @Override // public void send(ExportMessage message) throws IOException { // // if (message instanceof HttpExportMessage) { // HttpExportMessage message1 = (HttpExportMessage) message; // System.out.println("Sending message over HTTP: " + message); // System.out.println("URI:" + message1.getUri()); // HttpPost post = new HttpPost(message1.getUri()); // post.addHeader("content-type", "application/json"); // post.setEntity(new StringEntity(message1.getMessage())); // CloseableHttpResponse response = client.execute(post); // System.out.println(response.getStatusLine()); // EntityUtils.consume(response.getEntity()); // } else { // System.out.println("HTTP message of type ExportMessage: " + message); // } // } // // @Override // public void tearDown() throws IOException { // client.close(); // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // }
import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.http.HttpExporter; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException;
package edu.sjsu.mithai.export; public class HttpExporterTask extends StoppableRunnableTask { private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); private static final String STOP_MESSAGE = "STOP"; private Configuration configuration; private IExporter exporter; private MessageStore<HttpExportMessage> messageStore; public HttpExporterTask(Configuration configuration) throws Exception { this.configuration = configuration; this.messageStore = Store.httpMessageStore();
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/http/HttpExporter.java // public class HttpExporter implements IExporter<ExportMessage> { // // private CloseableHttpClient client; // // public HttpExporter() { // } // // @Override // public void setup() throws Exception { // this.client = HttpClients.createDefault(); // } // // @Override // public void send(ExportMessage message) throws IOException { // // if (message instanceof HttpExportMessage) { // HttpExportMessage message1 = (HttpExportMessage) message; // System.out.println("Sending message over HTTP: " + message); // System.out.println("URI:" + message1.getUri()); // HttpPost post = new HttpPost(message1.getUri()); // post.addHeader("content-type", "application/json"); // post.setEntity(new StringEntity(message1.getMessage())); // CloseableHttpResponse response = client.execute(post); // System.out.println(response.getStatusLine()); // EntityUtils.consume(response.getEntity()); // } else { // System.out.println("HTTP message of type ExportMessage: " + message); // } // } // // @Override // public void tearDown() throws IOException { // client.close(); // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/java/edu/sjsu/mithai/export/HttpExporterTask.java import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.http.HttpExporter; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; package edu.sjsu.mithai.export; public class HttpExporterTask extends StoppableRunnableTask { private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); private static final String STOP_MESSAGE = "STOP"; private Configuration configuration; private IExporter exporter; private MessageStore<HttpExportMessage> messageStore; public HttpExporterTask(Configuration configuration) throws Exception { this.configuration = configuration; this.messageStore = Store.httpMessageStore();
exporter = new HttpExporter();
meethai/mithai
src/main/scala/edu/sjsu/mithai/mqtt/MQTTPublisherTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java // public class ExporterTask extends StoppableRunnableTask { // // private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); // private static final String STOP_MESSAGE = "STOP"; // // private Configuration configuration; // private Exporter exporter; // private long sendInterval; // private MessageStore<ExportMessage> messageStore; // // public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception { // this.configuration = configuration; // this.sendInterval = Long.parseLong(configuration.getProperty(MithaiProperties.EXPORTER_TIME_INTERVAL)); // this.messageStore = messageStore; // exporter = new Exporter(configuration); // exporter.getExporter().setup(); // } // // @Override // public void run() { // // //TODO Message added to store is sent immediately. If required add sleep to run task periodically. // while (true) { // try { // ExportMessage message = messageStore.getMessageQueue().take(); // // if (message.getMessage().equals(STOP_MESSAGE)) { // break; // } // exporter.getExporter().send(message); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } catch (InterruptedException e) { // logger.error(e.getMessage(), e); // } // } // } // // @Override // public void stop() { // super.stop(); // try { // exporter.getExporter().tearDown(); // messageStore.addMessage(new ExportMessage(STOP_MESSAGE)); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // } // // Path: src/main/java/edu/sjsu/mithai/export/MessageStore.java // public class MessageStore<T> { // // private LinkedBlockingQueue<T> messageQueue; // private int size; // // public MessageStore(int size) { // this.size = size; // this.messageQueue = new LinkedBlockingQueue<>(); // } // // public void addMessage(T message) { // // if (messageQueue.size() < size) { // messageQueue.add(message); // } // } // // public void addMessages(List<T> messages) { // messageQueue.addAll(messages); // } // // public LinkedBlockingQueue<T> getMessageQueue() { // return messageQueue; // } // // @Override // public String toString() { // return "MessageStore{" + // "messageQueue=" + messageQueue + // '}'; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // }
import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.ExporterTask; import edu.sjsu.mithai.export.MessageStore; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2;
package edu.sjsu.mithai.mqtt; public class MQTTPublisherTask extends StoppableRunnableTask { private static final String STOP_MESSAGE = "STOP";
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java // public class ExporterTask extends StoppableRunnableTask { // // private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); // private static final String STOP_MESSAGE = "STOP"; // // private Configuration configuration; // private Exporter exporter; // private long sendInterval; // private MessageStore<ExportMessage> messageStore; // // public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception { // this.configuration = configuration; // this.sendInterval = Long.parseLong(configuration.getProperty(MithaiProperties.EXPORTER_TIME_INTERVAL)); // this.messageStore = messageStore; // exporter = new Exporter(configuration); // exporter.getExporter().setup(); // } // // @Override // public void run() { // // //TODO Message added to store is sent immediately. If required add sleep to run task periodically. // while (true) { // try { // ExportMessage message = messageStore.getMessageQueue().take(); // // if (message.getMessage().equals(STOP_MESSAGE)) { // break; // } // exporter.getExporter().send(message); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } catch (InterruptedException e) { // logger.error(e.getMessage(), e); // } // } // } // // @Override // public void stop() { // super.stop(); // try { // exporter.getExporter().tearDown(); // messageStore.addMessage(new ExportMessage(STOP_MESSAGE)); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // } // // Path: src/main/java/edu/sjsu/mithai/export/MessageStore.java // public class MessageStore<T> { // // private LinkedBlockingQueue<T> messageQueue; // private int size; // // public MessageStore(int size) { // this.size = size; // this.messageQueue = new LinkedBlockingQueue<>(); // } // // public void addMessage(T message) { // // if (messageQueue.size() < size) { // messageQueue.add(message); // } // } // // public void addMessages(List<T> messages) { // messageQueue.addAll(messages); // } // // public LinkedBlockingQueue<T> getMessageQueue() { // return messageQueue; // } // // @Override // public String toString() { // return "MessageStore{" + // "messageQueue=" + messageQueue + // '}'; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/scala/edu/sjsu/mithai/mqtt/MQTTPublisherTask.java import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.ExporterTask; import edu.sjsu.mithai.export.MessageStore; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; package edu.sjsu.mithai.mqtt; public class MQTTPublisherTask extends StoppableRunnableTask { private static final String STOP_MESSAGE = "STOP";
private final Logger logger = LoggerFactory.getLogger(ExporterTask.class);
meethai/mithai
src/main/scala/edu/sjsu/mithai/mqtt/MQTTPublisherTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java // public class ExporterTask extends StoppableRunnableTask { // // private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); // private static final String STOP_MESSAGE = "STOP"; // // private Configuration configuration; // private Exporter exporter; // private long sendInterval; // private MessageStore<ExportMessage> messageStore; // // public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception { // this.configuration = configuration; // this.sendInterval = Long.parseLong(configuration.getProperty(MithaiProperties.EXPORTER_TIME_INTERVAL)); // this.messageStore = messageStore; // exporter = new Exporter(configuration); // exporter.getExporter().setup(); // } // // @Override // public void run() { // // //TODO Message added to store is sent immediately. If required add sleep to run task periodically. // while (true) { // try { // ExportMessage message = messageStore.getMessageQueue().take(); // // if (message.getMessage().equals(STOP_MESSAGE)) { // break; // } // exporter.getExporter().send(message); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } catch (InterruptedException e) { // logger.error(e.getMessage(), e); // } // } // } // // @Override // public void stop() { // super.stop(); // try { // exporter.getExporter().tearDown(); // messageStore.addMessage(new ExportMessage(STOP_MESSAGE)); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // } // // Path: src/main/java/edu/sjsu/mithai/export/MessageStore.java // public class MessageStore<T> { // // private LinkedBlockingQueue<T> messageQueue; // private int size; // // public MessageStore(int size) { // this.size = size; // this.messageQueue = new LinkedBlockingQueue<>(); // } // // public void addMessage(T message) { // // if (messageQueue.size() < size) { // messageQueue.add(message); // } // } // // public void addMessages(List<T> messages) { // messageQueue.addAll(messages); // } // // public LinkedBlockingQueue<T> getMessageQueue() { // return messageQueue; // } // // @Override // public String toString() { // return "MessageStore{" + // "messageQueue=" + messageQueue + // '}'; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // }
import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.ExporterTask; import edu.sjsu.mithai.export.MessageStore; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2;
package edu.sjsu.mithai.mqtt; public class MQTTPublisherTask extends StoppableRunnableTask { private static final String STOP_MESSAGE = "STOP"; private final Logger logger = LoggerFactory.getLogger(ExporterTask.class);
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java // public class ExporterTask extends StoppableRunnableTask { // // private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); // private static final String STOP_MESSAGE = "STOP"; // // private Configuration configuration; // private Exporter exporter; // private long sendInterval; // private MessageStore<ExportMessage> messageStore; // // public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception { // this.configuration = configuration; // this.sendInterval = Long.parseLong(configuration.getProperty(MithaiProperties.EXPORTER_TIME_INTERVAL)); // this.messageStore = messageStore; // exporter = new Exporter(configuration); // exporter.getExporter().setup(); // } // // @Override // public void run() { // // //TODO Message added to store is sent immediately. If required add sleep to run task periodically. // while (true) { // try { // ExportMessage message = messageStore.getMessageQueue().take(); // // if (message.getMessage().equals(STOP_MESSAGE)) { // break; // } // exporter.getExporter().send(message); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } catch (InterruptedException e) { // logger.error(e.getMessage(), e); // } // } // } // // @Override // public void stop() { // super.stop(); // try { // exporter.getExporter().tearDown(); // messageStore.addMessage(new ExportMessage(STOP_MESSAGE)); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // } // // Path: src/main/java/edu/sjsu/mithai/export/MessageStore.java // public class MessageStore<T> { // // private LinkedBlockingQueue<T> messageQueue; // private int size; // // public MessageStore(int size) { // this.size = size; // this.messageQueue = new LinkedBlockingQueue<>(); // } // // public void addMessage(T message) { // // if (messageQueue.size() < size) { // messageQueue.add(message); // } // } // // public void addMessages(List<T> messages) { // messageQueue.addAll(messages); // } // // public LinkedBlockingQueue<T> getMessageQueue() { // return messageQueue; // } // // @Override // public String toString() { // return "MessageStore{" + // "messageQueue=" + messageQueue + // '}'; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/scala/edu/sjsu/mithai/mqtt/MQTTPublisherTask.java import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.ExporterTask; import edu.sjsu.mithai.export.MessageStore; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; package edu.sjsu.mithai.mqtt; public class MQTTPublisherTask extends StoppableRunnableTask { private static final String STOP_MESSAGE = "STOP"; private final Logger logger = LoggerFactory.getLogger(ExporterTask.class);
private Configuration configuration;
meethai/mithai
src/main/scala/edu/sjsu/mithai/mqtt/MQTTPublisherTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java // public class ExporterTask extends StoppableRunnableTask { // // private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); // private static final String STOP_MESSAGE = "STOP"; // // private Configuration configuration; // private Exporter exporter; // private long sendInterval; // private MessageStore<ExportMessage> messageStore; // // public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception { // this.configuration = configuration; // this.sendInterval = Long.parseLong(configuration.getProperty(MithaiProperties.EXPORTER_TIME_INTERVAL)); // this.messageStore = messageStore; // exporter = new Exporter(configuration); // exporter.getExporter().setup(); // } // // @Override // public void run() { // // //TODO Message added to store is sent immediately. If required add sleep to run task periodically. // while (true) { // try { // ExportMessage message = messageStore.getMessageQueue().take(); // // if (message.getMessage().equals(STOP_MESSAGE)) { // break; // } // exporter.getExporter().send(message); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } catch (InterruptedException e) { // logger.error(e.getMessage(), e); // } // } // } // // @Override // public void stop() { // super.stop(); // try { // exporter.getExporter().tearDown(); // messageStore.addMessage(new ExportMessage(STOP_MESSAGE)); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // } // // Path: src/main/java/edu/sjsu/mithai/export/MessageStore.java // public class MessageStore<T> { // // private LinkedBlockingQueue<T> messageQueue; // private int size; // // public MessageStore(int size) { // this.size = size; // this.messageQueue = new LinkedBlockingQueue<>(); // } // // public void addMessage(T message) { // // if (messageQueue.size() < size) { // messageQueue.add(message); // } // } // // public void addMessages(List<T> messages) { // messageQueue.addAll(messages); // } // // public LinkedBlockingQueue<T> getMessageQueue() { // return messageQueue; // } // // @Override // public String toString() { // return "MessageStore{" + // "messageQueue=" + messageQueue + // '}'; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // }
import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.ExporterTask; import edu.sjsu.mithai.export.MessageStore; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2;
package edu.sjsu.mithai.mqtt; public class MQTTPublisherTask extends StoppableRunnableTask { private static final String STOP_MESSAGE = "STOP"; private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); private Configuration configuration;
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java // public class ExporterTask extends StoppableRunnableTask { // // private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); // private static final String STOP_MESSAGE = "STOP"; // // private Configuration configuration; // private Exporter exporter; // private long sendInterval; // private MessageStore<ExportMessage> messageStore; // // public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception { // this.configuration = configuration; // this.sendInterval = Long.parseLong(configuration.getProperty(MithaiProperties.EXPORTER_TIME_INTERVAL)); // this.messageStore = messageStore; // exporter = new Exporter(configuration); // exporter.getExporter().setup(); // } // // @Override // public void run() { // // //TODO Message added to store is sent immediately. If required add sleep to run task periodically. // while (true) { // try { // ExportMessage message = messageStore.getMessageQueue().take(); // // if (message.getMessage().equals(STOP_MESSAGE)) { // break; // } // exporter.getExporter().send(message); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } catch (InterruptedException e) { // logger.error(e.getMessage(), e); // } // } // } // // @Override // public void stop() { // super.stop(); // try { // exporter.getExporter().tearDown(); // messageStore.addMessage(new ExportMessage(STOP_MESSAGE)); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // } // // Path: src/main/java/edu/sjsu/mithai/export/MessageStore.java // public class MessageStore<T> { // // private LinkedBlockingQueue<T> messageQueue; // private int size; // // public MessageStore(int size) { // this.size = size; // this.messageQueue = new LinkedBlockingQueue<>(); // } // // public void addMessage(T message) { // // if (messageQueue.size() < size) { // messageQueue.add(message); // } // } // // public void addMessages(List<T> messages) { // messageQueue.addAll(messages); // } // // public LinkedBlockingQueue<T> getMessageQueue() { // return messageQueue; // } // // @Override // public String toString() { // return "MessageStore{" + // "messageQueue=" + messageQueue + // '}'; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java // public abstract class StoppableRunnableTask implements Runnable, Stoppable { // // protected boolean stop; // // public StoppableRunnableTask() { // this.stop = false; // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/scala/edu/sjsu/mithai/mqtt/MQTTPublisherTask.java import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.export.ExporterTask; import edu.sjsu.mithai.export.MessageStore; import edu.sjsu.mithai.spark.Store; import edu.sjsu.mithai.util.StoppableRunnableTask; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; package edu.sjsu.mithai.mqtt; public class MQTTPublisherTask extends StoppableRunnableTask { private static final String STOP_MESSAGE = "STOP"; private final Logger logger = LoggerFactory.getLogger(ExporterTask.class); private Configuration configuration;
private MessageStore<Tuple2<String, String>> messageStore;
meethai/mithai
src/test/avro/edu/sjsu/mithai/mqtt/MQTTMetaDataRecieverTaskTest.java
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java // public abstract class BaseTest { // // protected Configuration config; // // public BaseTest() throws IOException { // loadConfig(); // } // // public abstract void test() throws Exception; // // public void loadConfig() throws IOException { // config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile()); // } // // public void stopAfter(int seconds) { // // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // try { // TaskManager.getInstance().stopAll(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java // public class TaskManager { // private static TaskManager ourInstance = new TaskManager(); // // private List<Stoppable> tasks; // private ExecutorService threadPool; // private List<Ihandler> handlers; // // private TaskManager() { // this.threadPool = Executors.newCachedThreadPool(); // this.tasks = new ArrayList<>(); // this.handlers = new ArrayList<>(); // } // // public static TaskManager getInstance() { // return ourInstance; // } // // public synchronized void submitTask(StoppableExecutableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void submitTask(StoppableRunnableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void stopAll() throws InterruptedException { // // for (Stoppable task : tasks) { // System.out.println("Stopping task:" + task); // task.stop(); // System.out.println("Task stopped.."); // } // // // remove all tasks // tasks.clear(); // // threadPool.shutdown(); // System.out.println("Stopping streaming context.."); // SparkStreamingObject.streamingContext().stop(true, false); // System.out.println("Streaming context stopped.."); // threadPool.awaitTermination(60, TimeUnit.SECONDS); // } // // public synchronized void stop(Class clazz) { // System.out.println(tasks); // for(Stoppable task : tasks) { // if (clazz.isInstance(task)) { // task.stop(); // } // } // } // // public List<Ihandler> getHandlers() { // return handlers; // } // // public void addHandler(Ihandler handler) { // handlers.add(handler); // } // }
import edu.sjsu.mithai.util.BaseTest; import edu.sjsu.mithai.util.TaskManager; import java.io.IOException;
package edu.sjsu.mithai.mqtt; /** * Created by kaustubh on 10/12/16. */ public class MQTTMetaDataRecieverTaskTest extends BaseTest{ public MQTTMetaDataRecieverTaskTest() throws IOException { } public static void main(String[] args) throws Exception { new MQTTMetaDataRecieverTaskTest().test(); } @Override public void test() throws Exception {
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java // public abstract class BaseTest { // // protected Configuration config; // // public BaseTest() throws IOException { // loadConfig(); // } // // public abstract void test() throws Exception; // // public void loadConfig() throws IOException { // config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile()); // } // // public void stopAfter(int seconds) { // // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // try { // TaskManager.getInstance().stopAll(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java // public class TaskManager { // private static TaskManager ourInstance = new TaskManager(); // // private List<Stoppable> tasks; // private ExecutorService threadPool; // private List<Ihandler> handlers; // // private TaskManager() { // this.threadPool = Executors.newCachedThreadPool(); // this.tasks = new ArrayList<>(); // this.handlers = new ArrayList<>(); // } // // public static TaskManager getInstance() { // return ourInstance; // } // // public synchronized void submitTask(StoppableExecutableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void submitTask(StoppableRunnableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void stopAll() throws InterruptedException { // // for (Stoppable task : tasks) { // System.out.println("Stopping task:" + task); // task.stop(); // System.out.println("Task stopped.."); // } // // // remove all tasks // tasks.clear(); // // threadPool.shutdown(); // System.out.println("Stopping streaming context.."); // SparkStreamingObject.streamingContext().stop(true, false); // System.out.println("Streaming context stopped.."); // threadPool.awaitTermination(60, TimeUnit.SECONDS); // } // // public synchronized void stop(Class clazz) { // System.out.println(tasks); // for(Stoppable task : tasks) { // if (clazz.isInstance(task)) { // task.stop(); // } // } // } // // public List<Ihandler> getHandlers() { // return handlers; // } // // public void addHandler(Ihandler handler) { // handlers.add(handler); // } // } // Path: src/test/avro/edu/sjsu/mithai/mqtt/MQTTMetaDataRecieverTaskTest.java import edu.sjsu.mithai.util.BaseTest; import edu.sjsu.mithai.util.TaskManager; import java.io.IOException; package edu.sjsu.mithai.mqtt; /** * Created by kaustubh on 10/12/16. */ public class MQTTMetaDataRecieverTaskTest extends BaseTest{ public MQTTMetaDataRecieverTaskTest() throws IOException { } public static void main(String[] args) throws Exception { new MQTTMetaDataRecieverTaskTest().test(); } @Override public void test() throws Exception {
TaskManager.getInstance().submitTask(new MQTTMetaDataRecieverTask(config));
meethai/mithai
src/test/java/edu/sjsu/mithai/export/ExporterTaskTest.java
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java // public abstract class BaseTest { // // protected Configuration config; // // public BaseTest() throws IOException { // loadConfig(); // } // // public abstract void test() throws Exception; // // public void loadConfig() throws IOException { // config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile()); // } // // public void stopAfter(int seconds) { // // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // try { // TaskManager.getInstance().stopAll(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java // public class TaskManager { // private static TaskManager ourInstance = new TaskManager(); // // private List<Stoppable> tasks; // private ExecutorService threadPool; // private List<Ihandler> handlers; // // private TaskManager() { // this.threadPool = Executors.newCachedThreadPool(); // this.tasks = new ArrayList<>(); // this.handlers = new ArrayList<>(); // } // // public static TaskManager getInstance() { // return ourInstance; // } // // public synchronized void submitTask(StoppableExecutableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void submitTask(StoppableRunnableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void stopAll() throws InterruptedException { // // for (Stoppable task : tasks) { // System.out.println("Stopping task:" + task); // task.stop(); // System.out.println("Task stopped.."); // } // // // remove all tasks // tasks.clear(); // // threadPool.shutdown(); // System.out.println("Stopping streaming context.."); // SparkStreamingObject.streamingContext().stop(true, false); // System.out.println("Streaming context stopped.."); // threadPool.awaitTermination(60, TimeUnit.SECONDS); // } // // public synchronized void stop(Class clazz) { // System.out.println(tasks); // for(Stoppable task : tasks) { // if (clazz.isInstance(task)) { // task.stop(); // } // } // } // // public List<Ihandler> getHandlers() { // return handlers; // } // // public void addHandler(Ihandler handler) { // handlers.add(handler); // } // }
import edu.sjsu.mithai.util.BaseTest; import edu.sjsu.mithai.util.TaskManager; import org.junit.Test; import java.io.IOException;
package edu.sjsu.mithai.export; public class ExporterTaskTest extends BaseTest { public ExporterTaskTest() throws IOException { } @Test @Override public void test() throws Exception { MessageStore messageStore = new MessageStore(10); for (int i = 0; i < 10; i++) { messageStore.addMessage(new ExportMessage("Message" + i)); } System.out.println(messageStore);
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java // public abstract class BaseTest { // // protected Configuration config; // // public BaseTest() throws IOException { // loadConfig(); // } // // public abstract void test() throws Exception; // // public void loadConfig() throws IOException { // config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile()); // } // // public void stopAfter(int seconds) { // // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // try { // TaskManager.getInstance().stopAll(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java // public class TaskManager { // private static TaskManager ourInstance = new TaskManager(); // // private List<Stoppable> tasks; // private ExecutorService threadPool; // private List<Ihandler> handlers; // // private TaskManager() { // this.threadPool = Executors.newCachedThreadPool(); // this.tasks = new ArrayList<>(); // this.handlers = new ArrayList<>(); // } // // public static TaskManager getInstance() { // return ourInstance; // } // // public synchronized void submitTask(StoppableExecutableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void submitTask(StoppableRunnableTask task) { // threadPool.submit(task); // tasks.add(task); // } // // public synchronized void stopAll() throws InterruptedException { // // for (Stoppable task : tasks) { // System.out.println("Stopping task:" + task); // task.stop(); // System.out.println("Task stopped.."); // } // // // remove all tasks // tasks.clear(); // // threadPool.shutdown(); // System.out.println("Stopping streaming context.."); // SparkStreamingObject.streamingContext().stop(true, false); // System.out.println("Streaming context stopped.."); // threadPool.awaitTermination(60, TimeUnit.SECONDS); // } // // public synchronized void stop(Class clazz) { // System.out.println(tasks); // for(Stoppable task : tasks) { // if (clazz.isInstance(task)) { // task.stop(); // } // } // } // // public List<Ihandler> getHandlers() { // return handlers; // } // // public void addHandler(Ihandler handler) { // handlers.add(handler); // } // } // Path: src/test/java/edu/sjsu/mithai/export/ExporterTaskTest.java import edu.sjsu.mithai.util.BaseTest; import edu.sjsu.mithai.util.TaskManager; import org.junit.Test; import java.io.IOException; package edu.sjsu.mithai.export; public class ExporterTaskTest extends BaseTest { public ExporterTaskTest() throws IOException { } @Test @Override public void test() throws Exception { MessageStore messageStore = new MessageStore(10); for (int i = 0; i < 10; i++) { messageStore.addMessage(new ExportMessage("Message" + i)); } System.out.println(messageStore);
TaskManager.getInstance().submitTask(new HttpExporterTask(config));
meethai/mithai
src/main/scala/edu/sjsu/mithai/data/AvroSerializationHelper.java
// Path: src/main/java/edu/sjsu/mithai/main/Mithai.java // public class Mithai implements Observer { // // protected static Configuration configuration; // protected SensorStore sensorStore; // // // public static void main(String[] args) throws Exception { // Mithai mithai = new Mithai(); // if(args.length<1) // mithai.start(null); // else // mithai.start(args[0]); // } // // public static Configuration getConfiguration() { // return configuration; // } // // protected void start(String arg) throws Exception { // // Logger.getLogger("org").setLevel(Level.ERROR); // Logger.getLogger("akka").setLevel(Level.ERROR); // // ConfigFileObservable.getInstance().addObserver(this); // // Runtime.getRuntime().addShutdownHook(new ShutDownHook()); // // //TODO file path will be provided by user // if (arg == null || arg.equals("")) { // File configFile = new File(Mithai.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); // configuration = new Configuration(configFile.getParent() + "/application.properties"); // } else // configuration = new Configuration(arg); // // sensorStore = new SensorStore(); // // loadDevices(); // // setupHandlers(); // // boolean receiverTask = false; // //Start tasks here // // TaskManager.getInstance().submitTask(new ConfigMonitorTask(configuration)); // // String type = configuration.getProperty(MithaiProperties.TASK_LIST); // String[] tasks = type.split(","); // // for (String task : tasks) { // task = task.trim(); // if (task.equals("MQTTDataReceiverTask")) { // TaskManager.getInstance().submitTask(new MQTTDataReceiverTask(configuration)); // receiverTask = true; // } else if (task.equals("MQTTMetaDataRecieverTask")) { // TaskManager.getInstance().submitTask(new MQTTMetaDataRecieverTask(configuration)); // receiverTask = true; // } // if (task.equals("MQTTPublisherTask")) { // TaskManager.getInstance().submitTask(new MQTTPublisherTask(configuration)); // } // if (task.equals("DataGenerationTask")) { // TaskManager.getInstance().submitTask(new DataGenerationTask(configuration, sensorStore)); // } else if (task.equals("MetadataGenerationTask")) { // TaskManager.getInstance().submitTask(new MetadataGenerationTask(configuration)); // } // // } // TaskManager.getInstance().submitTask(new HttpExporterTask(configuration)); // // if (!configuration.getProperty(EXPORTER_TYPE).equals("HTTP")) { // TaskManager.getInstance().submitTask(new ExporterTask(configuration, Store.messageStore())); // } // // // Start Streaming context // // Thread.sleep(Long.parseLong(configuration.getProperty(MithaiProperties.STARTUP_THRESHOLD)) * 1000); // if (receiverTask) { // SparkStreamingObject.streamingContext().start(); // } // // // Stop all tasks and wait 60 seconds to finish them // // TaskManager.getInstance().stopAll(); // } // // protected synchronized void loadDevices() { // sensorStore.getDevices().clear(); // // for (int i = 1; i<= Integer.parseInt(configuration.getProperty(NUMBER_OF_SENSORS)); i++) { // sensorStore.addDevice(new TemperatureSensor("sensor" + i)); // } // } // // protected synchronized void setupHandlers() { // TaskManager.getInstance().addHandler(new MithaiHandler()); // } // // @Override // public void update(Observable observable, Object o) { // // if (observable instanceof ConfigFileObservable) { // loadDevices(); // // // Kick out old data generation task and start new one // TaskManager.getInstance().stop(DataGenerationTask.class); // // try { // TaskManager.getInstance().submitTask(new DataGenerationTask(configuration, sensorStore)); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // private static class ShutDownHook extends Thread { // // @Override // public void run() { // System.out.println("###Shutdown triggered.. Stopping all tasks.."); // try { // TaskManager.getInstance().stopAll(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // }
import edu.sjsu.mithai.main.Mithai; import org.apache.avro.Schema; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.*; import org.apache.avro.specific.SpecificDatumWriter; import org.apache.log4j.Logger; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Base64;
package edu.sjsu.mithai.data; public class AvroSerializationHelper implements SerializationHelper<GenericRecord>{ private Schema schema; private Logger logger = Logger.getLogger(getClass()); public void loadSchema(String schemaFile) throws IOException, URISyntaxException { Schema.Parser parser = new Schema.Parser(); // URL url = getClass().getClassLoader().getResource(schemaFile);
// Path: src/main/java/edu/sjsu/mithai/main/Mithai.java // public class Mithai implements Observer { // // protected static Configuration configuration; // protected SensorStore sensorStore; // // // public static void main(String[] args) throws Exception { // Mithai mithai = new Mithai(); // if(args.length<1) // mithai.start(null); // else // mithai.start(args[0]); // } // // public static Configuration getConfiguration() { // return configuration; // } // // protected void start(String arg) throws Exception { // // Logger.getLogger("org").setLevel(Level.ERROR); // Logger.getLogger("akka").setLevel(Level.ERROR); // // ConfigFileObservable.getInstance().addObserver(this); // // Runtime.getRuntime().addShutdownHook(new ShutDownHook()); // // //TODO file path will be provided by user // if (arg == null || arg.equals("")) { // File configFile = new File(Mithai.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); // configuration = new Configuration(configFile.getParent() + "/application.properties"); // } else // configuration = new Configuration(arg); // // sensorStore = new SensorStore(); // // loadDevices(); // // setupHandlers(); // // boolean receiverTask = false; // //Start tasks here // // TaskManager.getInstance().submitTask(new ConfigMonitorTask(configuration)); // // String type = configuration.getProperty(MithaiProperties.TASK_LIST); // String[] tasks = type.split(","); // // for (String task : tasks) { // task = task.trim(); // if (task.equals("MQTTDataReceiverTask")) { // TaskManager.getInstance().submitTask(new MQTTDataReceiverTask(configuration)); // receiverTask = true; // } else if (task.equals("MQTTMetaDataRecieverTask")) { // TaskManager.getInstance().submitTask(new MQTTMetaDataRecieverTask(configuration)); // receiverTask = true; // } // if (task.equals("MQTTPublisherTask")) { // TaskManager.getInstance().submitTask(new MQTTPublisherTask(configuration)); // } // if (task.equals("DataGenerationTask")) { // TaskManager.getInstance().submitTask(new DataGenerationTask(configuration, sensorStore)); // } else if (task.equals("MetadataGenerationTask")) { // TaskManager.getInstance().submitTask(new MetadataGenerationTask(configuration)); // } // // } // TaskManager.getInstance().submitTask(new HttpExporterTask(configuration)); // // if (!configuration.getProperty(EXPORTER_TYPE).equals("HTTP")) { // TaskManager.getInstance().submitTask(new ExporterTask(configuration, Store.messageStore())); // } // // // Start Streaming context // // Thread.sleep(Long.parseLong(configuration.getProperty(MithaiProperties.STARTUP_THRESHOLD)) * 1000); // if (receiverTask) { // SparkStreamingObject.streamingContext().start(); // } // // // Stop all tasks and wait 60 seconds to finish them // // TaskManager.getInstance().stopAll(); // } // // protected synchronized void loadDevices() { // sensorStore.getDevices().clear(); // // for (int i = 1; i<= Integer.parseInt(configuration.getProperty(NUMBER_OF_SENSORS)); i++) { // sensorStore.addDevice(new TemperatureSensor("sensor" + i)); // } // } // // protected synchronized void setupHandlers() { // TaskManager.getInstance().addHandler(new MithaiHandler()); // } // // @Override // public void update(Observable observable, Object o) { // // if (observable instanceof ConfigFileObservable) { // loadDevices(); // // // Kick out old data generation task and start new one // TaskManager.getInstance().stop(DataGenerationTask.class); // // try { // TaskManager.getInstance().submitTask(new DataGenerationTask(configuration, sensorStore)); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // private static class ShutDownHook extends Thread { // // @Override // public void run() { // System.out.println("###Shutdown triggered.. Stopping all tasks.."); // try { // TaskManager.getInstance().stopAll(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // Path: src/main/scala/edu/sjsu/mithai/data/AvroSerializationHelper.java import edu.sjsu.mithai.main.Mithai; import org.apache.avro.Schema; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.*; import org.apache.avro.specific.SpecificDatumWriter; import org.apache.log4j.Logger; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Base64; package edu.sjsu.mithai.data; public class AvroSerializationHelper implements SerializationHelper<GenericRecord>{ private Schema schema; private Logger logger = Logger.getLogger(getClass()); public void loadSchema(String schemaFile) throws IOException, URISyntaxException { Schema.Parser parser = new Schema.Parser(); // URL url = getClass().getClassLoader().getResource(schemaFile);
File jarfile = new File(Mithai.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
meethai/mithai
src/main/scala/edu/sjsu/mithai/data/MetadataGenerationTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java // public class MqttService { // private static MQTTPublisher publisher; // // private MqttService() { // } // // public static MQTTPublisher getPublisher(Configuration configuration) { // // if (publisher == null) { // publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER)); // } // // return publisher; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java // public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable { // // protected boolean stop; // // public StoppableExecutableTask() { // this.stop = false; // } // // @Override // public void run() { // do { // execute(); // } while (!stop); // } // // @Override // public void stop() { // stop = true; // } // // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; import edu.sjsu.mithai.mqtt.MQTTPublisher; import edu.sjsu.mithai.mqtt.MqttService; import edu.sjsu.mithai.util.StoppableExecutableTask; import java.util.ArrayList; import java.util.List;
package edu.sjsu.mithai.data; public class MetadataGenerationTask extends StoppableExecutableTask { private static final String TOPIC = "metadata"; private final Gson gson;
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java // public class MqttService { // private static MQTTPublisher publisher; // // private MqttService() { // } // // public static MQTTPublisher getPublisher(Configuration configuration) { // // if (publisher == null) { // publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER)); // } // // return publisher; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java // public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable { // // protected boolean stop; // // public StoppableExecutableTask() { // this.stop = false; // } // // @Override // public void run() { // do { // execute(); // } while (!stop); // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/scala/edu/sjsu/mithai/data/MetadataGenerationTask.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; import edu.sjsu.mithai.mqtt.MQTTPublisher; import edu.sjsu.mithai.mqtt.MqttService; import edu.sjsu.mithai.util.StoppableExecutableTask; import java.util.ArrayList; import java.util.List; package edu.sjsu.mithai.data; public class MetadataGenerationTask extends StoppableExecutableTask { private static final String TOPIC = "metadata"; private final Gson gson;
private Configuration configuration;
meethai/mithai
src/main/scala/edu/sjsu/mithai/data/MetadataGenerationTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java // public class MqttService { // private static MQTTPublisher publisher; // // private MqttService() { // } // // public static MQTTPublisher getPublisher(Configuration configuration) { // // if (publisher == null) { // publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER)); // } // // return publisher; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java // public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable { // // protected boolean stop; // // public StoppableExecutableTask() { // this.stop = false; // } // // @Override // public void run() { // do { // execute(); // } while (!stop); // } // // @Override // public void stop() { // stop = true; // } // // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; import edu.sjsu.mithai.mqtt.MQTTPublisher; import edu.sjsu.mithai.mqtt.MqttService; import edu.sjsu.mithai.util.StoppableExecutableTask; import java.util.ArrayList; import java.util.List;
package edu.sjsu.mithai.data; public class MetadataGenerationTask extends StoppableExecutableTask { private static final String TOPIC = "metadata"; private final Gson gson; private Configuration configuration; private MQTTPublisher publisher; private int sendCount; private AvroMetadataSerializationHelper avro; public MetadataGenerationTask(Configuration configuration) { this.configuration = configuration;
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java // public class MqttService { // private static MQTTPublisher publisher; // // private MqttService() { // } // // public static MQTTPublisher getPublisher(Configuration configuration) { // // if (publisher == null) { // publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER)); // } // // return publisher; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java // public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable { // // protected boolean stop; // // public StoppableExecutableTask() { // this.stop = false; // } // // @Override // public void run() { // do { // execute(); // } while (!stop); // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/scala/edu/sjsu/mithai/data/MetadataGenerationTask.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; import edu.sjsu.mithai.mqtt.MQTTPublisher; import edu.sjsu.mithai.mqtt.MqttService; import edu.sjsu.mithai.util.StoppableExecutableTask; import java.util.ArrayList; import java.util.List; package edu.sjsu.mithai.data; public class MetadataGenerationTask extends StoppableExecutableTask { private static final String TOPIC = "metadata"; private final Gson gson; private Configuration configuration; private MQTTPublisher publisher; private int sendCount; private AvroMetadataSerializationHelper avro; public MetadataGenerationTask(Configuration configuration) { this.configuration = configuration;
this.publisher = MqttService.getPublisher(configuration);
meethai/mithai
src/main/scala/edu/sjsu/mithai/data/MetadataGenerationTask.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java // public class MqttService { // private static MQTTPublisher publisher; // // private MqttService() { // } // // public static MQTTPublisher getPublisher(Configuration configuration) { // // if (publisher == null) { // publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER)); // } // // return publisher; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java // public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable { // // protected boolean stop; // // public StoppableExecutableTask() { // this.stop = false; // } // // @Override // public void run() { // do { // execute(); // } while (!stop); // } // // @Override // public void stop() { // stop = true; // } // // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; import edu.sjsu.mithai.mqtt.MQTTPublisher; import edu.sjsu.mithai.mqtt.MqttService; import edu.sjsu.mithai.util.StoppableExecutableTask; import java.util.ArrayList; import java.util.List;
package edu.sjsu.mithai.data; public class MetadataGenerationTask extends StoppableExecutableTask { private static final String TOPIC = "metadata"; private final Gson gson; private Configuration configuration; private MQTTPublisher publisher; private int sendCount; private AvroMetadataSerializationHelper avro; public MetadataGenerationTask(Configuration configuration) { this.configuration = configuration; this.publisher = MqttService.getPublisher(configuration); this.gson = new Gson(); this.avro = new AvroMetadataSerializationHelper(); } @Override public void execute() {
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java // public class MqttService { // private static MQTTPublisher publisher; // // private MqttService() { // } // // public static MQTTPublisher getPublisher(Configuration configuration) { // // if (publisher == null) { // publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER)); // } // // return publisher; // } // } // // Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java // public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable { // // protected boolean stop; // // public StoppableExecutableTask() { // this.stop = false; // } // // @Override // public void run() { // do { // execute(); // } while (!stop); // } // // @Override // public void stop() { // stop = true; // } // // } // Path: src/main/scala/edu/sjsu/mithai/data/MetadataGenerationTask.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; import edu.sjsu.mithai.mqtt.MQTTPublisher; import edu.sjsu.mithai.mqtt.MqttService; import edu.sjsu.mithai.util.StoppableExecutableTask; import java.util.ArrayList; import java.util.List; package edu.sjsu.mithai.data; public class MetadataGenerationTask extends StoppableExecutableTask { private static final String TOPIC = "metadata"; private final Gson gson; private Configuration configuration; private MQTTPublisher publisher; private int sendCount; private AvroMetadataSerializationHelper avro; public MetadataGenerationTask(Configuration configuration) { this.configuration = configuration; this.publisher = MqttService.getPublisher(configuration); this.gson = new Gson(); this.avro = new AvroMetadataSerializationHelper(); } @Override public void execute() {
if (++sendCount >= Integer.parseInt(configuration.getProperty(MithaiProperties.RESEND_COUNT))) {
meethai/mithai
src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // }
import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties;
package edu.sjsu.mithai.mqtt; public class MqttService { private static MQTTPublisher publisher; private MqttService() { }
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; package edu.sjsu.mithai.mqtt; public class MqttService { private static MQTTPublisher publisher; private MqttService() { }
public static MQTTPublisher getPublisher(Configuration configuration) {
meethai/mithai
src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // }
import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties;
package edu.sjsu.mithai.mqtt; public class MqttService { private static MQTTPublisher publisher; private MqttService() { } public static MQTTPublisher getPublisher(Configuration configuration) { if (publisher == null) {
// Path: src/main/java/edu/sjsu/mithai/config/Configuration.java // public class Configuration { // // protected String propertyFile; // protected Properties properties; // // public Configuration(String propertyFile) throws IOException { // this.propertyFile = propertyFile; // this.properties = new Properties(); // properties.load(new FileReader(propertyFile)); // } // // public String getProperty(String key) { // return properties.getProperty(key); // } // // public void setProperty(String key, String value) { // properties.setProperty(key, value); // } // // public Properties getProperties() { // return properties; // } // // public void setProperties(Properties properties) { // this.properties = properties; // } // // public void setPropertyFile(String propertyFile) { // this.propertyFile = propertyFile; // } // // public String getPropertyFile() { // return propertyFile; // } // // public void reload() throws IOException { // properties.clear(); // properties.load(new FileReader(propertyFile)); // System.out.println("=>" + properties); // } // } // // Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java // public interface MithaiProperties { // // // Self node properties // String IP = "IP"; // String ID = "ID"; // String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS"; // String LOCAL_GRAPH = "LOCAL_GRAPH"; // // // Sensor & Data generation related properties // String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS"; // String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL"; // String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL"; // String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT"; // String RESEND_COUNT = "RESEND_COUNT"; // String STARTUP_THRESHOLD = "STARTUP_THRESHOLD"; // // // INJECTOR PROPERTIES // String MQTT_BROKER = "MQTT_BROKER"; // String MQTT_TOPIC = "MQTT_TOPIC"; // // // Visualization System Properties // String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL"; // // // EXPORTER PROPERTIES // String EXPORTER_TYPE = "EXPORTER_TYPE"; // String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP"; // String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC"; // String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL"; // // // Graphite exporter properties // String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME"; // String GRAPHITE_PORT = "GRAPHITE_PORT"; // // //Graph Processor Tasks // String ENTRY = "ENTRY"; // String TASK_LIST = "TASK_LIST"; // String FUNCTION_LIST = "FUNCTION_LIST"; // // //Store Properties // String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE"; // String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE"; // String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL"; // // } // Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java import edu.sjsu.mithai.config.Configuration; import edu.sjsu.mithai.config.MithaiProperties; package edu.sjsu.mithai.mqtt; public class MqttService { private static MQTTPublisher publisher; private MqttService() { } public static MQTTPublisher getPublisher(Configuration configuration) { if (publisher == null) {
publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER));