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
contentful/discovery-app-android
app/src/main/java/discovery/contentful/adapters/AssetInfoAdapter.java
// Path: app/src/main/java/discovery/contentful/CFApp.java // public class CFApp extends Application { // public static CFApp sInstance; // // @Override // public void onCreate() { // super.onCreate(); // // sInstance = this; // } // // public static CFApp getInstance() { // return sInstance; // } // } // // Path: app/src/main/java/discovery/contentful/ui/FieldViewHolder.java // public class FieldViewHolder { // public @Bind(R.id.tv_title) CFTextView tvTitle; // public @Bind(R.id.tv_value) CFTextView tvValue; // public @Bind(R.id.iv_arrow) ImageView ivArrow; // // public FieldViewHolder(View v) { // ButterKnife.bind(this, v); // } // } // // Path: app/src/main/java/discovery/contentful/utils/ViewHelper.java // public class ViewHelper { // private ViewHelper() { // } // // /** // * Register a callback to be invoked when the global layout state or the visibility of views // * within the view tree changes. // * // * @param v The View. // * @param listener The callback to add. // * @see #removeGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // public static void addGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // // if (observer == null || !observer.isAlive()) { // return; // } // // observer.addOnGlobalLayoutListener(listener); // } // // /** // * Remove a previously installed global layout callback. // * // * @param v The View. // * @param listener The callback to remove. // * @see #addGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static void removeGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // if (observer == null || !observer.isAlive()) { // return; // } // // if (Build.VERSION.SDK_INT < 16) { // observer.removeGlobalOnLayoutListener(listener); // } else { // observer.removeOnGlobalLayoutListener(listener); // } // } // // public static void setVisibility(View v, boolean show) { // if (show) { // v.setVisibility(View.VISIBLE); // } else { // v.setVisibility(View.GONE); // } // } // }
import android.content.Context; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import discovery.contentful.CFApp; import discovery.contentful.R; import discovery.contentful.ui.FieldViewHolder; import discovery.contentful.utils.ViewHelper; import com.contentful.java.cda.CDAAsset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import org.apache.commons.io.FileUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat;
} @Override public Pair<String, String> getItem(int position) { return fields.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { FieldViewHolder vh; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.view_field, parent, false); convertView.setTag(vh = new FieldViewHolder(convertView)); vh.tvValue.setVisibility(View.VISIBLE); } else { vh = new FieldViewHolder(convertView); } Pair<String, String> item = getItem(position); // Title, Value vh.tvTitle.setText(item.first); vh.tvValue.setText(item.second); boolean clickable = CLICKABLE_TITLES.contains(item.first); convertView.setTag(R.id.tag_clickable, clickable);
// Path: app/src/main/java/discovery/contentful/CFApp.java // public class CFApp extends Application { // public static CFApp sInstance; // // @Override // public void onCreate() { // super.onCreate(); // // sInstance = this; // } // // public static CFApp getInstance() { // return sInstance; // } // } // // Path: app/src/main/java/discovery/contentful/ui/FieldViewHolder.java // public class FieldViewHolder { // public @Bind(R.id.tv_title) CFTextView tvTitle; // public @Bind(R.id.tv_value) CFTextView tvValue; // public @Bind(R.id.iv_arrow) ImageView ivArrow; // // public FieldViewHolder(View v) { // ButterKnife.bind(this, v); // } // } // // Path: app/src/main/java/discovery/contentful/utils/ViewHelper.java // public class ViewHelper { // private ViewHelper() { // } // // /** // * Register a callback to be invoked when the global layout state or the visibility of views // * within the view tree changes. // * // * @param v The View. // * @param listener The callback to add. // * @see #removeGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // public static void addGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // // if (observer == null || !observer.isAlive()) { // return; // } // // observer.addOnGlobalLayoutListener(listener); // } // // /** // * Remove a previously installed global layout callback. // * // * @param v The View. // * @param listener The callback to remove. // * @see #addGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static void removeGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // if (observer == null || !observer.isAlive()) { // return; // } // // if (Build.VERSION.SDK_INT < 16) { // observer.removeGlobalOnLayoutListener(listener); // } else { // observer.removeOnGlobalLayoutListener(listener); // } // } // // public static void setVisibility(View v, boolean show) { // if (show) { // v.setVisibility(View.VISIBLE); // } else { // v.setVisibility(View.GONE); // } // } // } // Path: app/src/main/java/discovery/contentful/adapters/AssetInfoAdapter.java import android.content.Context; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import discovery.contentful.CFApp; import discovery.contentful.R; import discovery.contentful.ui.FieldViewHolder; import discovery.contentful.utils.ViewHelper; import com.contentful.java.cda.CDAAsset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import org.apache.commons.io.FileUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; } @Override public Pair<String, String> getItem(int position) { return fields.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { FieldViewHolder vh; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.view_field, parent, false); convertView.setTag(vh = new FieldViewHolder(convertView)); vh.tvValue.setVisibility(View.VISIBLE); } else { vh = new FieldViewHolder(convertView); } Pair<String, String> item = getItem(position); // Title, Value vh.tvTitle.setText(item.first); vh.tvValue.setText(item.second); boolean clickable = CLICKABLE_TITLES.contains(item.first); convertView.setTag(R.id.tag_clickable, clickable);
ViewHelper.setVisibility(vh.ivArrow, clickable);
contentful/discovery-app-android
app/src/main/java/discovery/contentful/activities/MapActivity.java
// Path: app/src/main/java/discovery/contentful/utils/IntentConsts.java // public class IntentConsts { // private IntentConsts() { // } // // public static final String PACKAGE_NAME = CFApp.getInstance().getPackageName(); // // public static final String EXTRA_SPACE = PACKAGE_NAME + ".EXTRA_SPACE"; // public static final String EXTRA_CREDENTIALS = PACKAGE_NAME + ".EXTRA_CREDENTIALS"; // public static final String EXTRA_CONTENT_TYPE = PACKAGE_NAME + ".EXTRA_CONTENT_TYPE"; // public static final String EXTRA_ENTRY = PACKAGE_NAME + ".EXTRA_ENTRY"; // public static final String EXTRA_ASSET = PACKAGE_NAME + ".EXTRA_ASSET"; // public static final String EXTRA_TEXT = PACKAGE_NAME + ".EXTRA_TEXT"; // public static final String EXTRA_LOCATION = PACKAGE_NAME + ".EXTRA_LOCATION"; // public static final String EXTRA_TITLE = PACKAGE_NAME + ".EXTRA_TITLE"; // public static final String EXTRA_LIST = PACKAGE_NAME + ".EXTRA_LIST"; // public static final String EXTRA_URL = PACKAGE_NAME + ".EXTRA_URL"; // public static final String EXTRA_ALLOW_LINKS = PACKAGE_NAME + ".EXTRA_ALLOW_LINKS"; // public static final String EXTRA_CONTENT_TYPES_MAP = PACKAGE_NAME + ".EXTRA_CONTENT_TYPES_MAP"; // // /** // * DBIntentService // */ // public static class DB { // public static final String ACTION_SAVE_CREDENTIALS = PACKAGE_NAME + ".ACTION_SAVE_CREDENTIALS"; // } // }
import android.content.Intent; import android.os.Bundle; import discovery.contentful.R; import discovery.contentful.utils.IntentConsts; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions;
package discovery.contentful.activities; public class MapActivity extends CFFragmentActivity implements OnMapReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.fragment_map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { Intent intent = getIntent();
// Path: app/src/main/java/discovery/contentful/utils/IntentConsts.java // public class IntentConsts { // private IntentConsts() { // } // // public static final String PACKAGE_NAME = CFApp.getInstance().getPackageName(); // // public static final String EXTRA_SPACE = PACKAGE_NAME + ".EXTRA_SPACE"; // public static final String EXTRA_CREDENTIALS = PACKAGE_NAME + ".EXTRA_CREDENTIALS"; // public static final String EXTRA_CONTENT_TYPE = PACKAGE_NAME + ".EXTRA_CONTENT_TYPE"; // public static final String EXTRA_ENTRY = PACKAGE_NAME + ".EXTRA_ENTRY"; // public static final String EXTRA_ASSET = PACKAGE_NAME + ".EXTRA_ASSET"; // public static final String EXTRA_TEXT = PACKAGE_NAME + ".EXTRA_TEXT"; // public static final String EXTRA_LOCATION = PACKAGE_NAME + ".EXTRA_LOCATION"; // public static final String EXTRA_TITLE = PACKAGE_NAME + ".EXTRA_TITLE"; // public static final String EXTRA_LIST = PACKAGE_NAME + ".EXTRA_LIST"; // public static final String EXTRA_URL = PACKAGE_NAME + ".EXTRA_URL"; // public static final String EXTRA_ALLOW_LINKS = PACKAGE_NAME + ".EXTRA_ALLOW_LINKS"; // public static final String EXTRA_CONTENT_TYPES_MAP = PACKAGE_NAME + ".EXTRA_CONTENT_TYPES_MAP"; // // /** // * DBIntentService // */ // public static class DB { // public static final String ACTION_SAVE_CREDENTIALS = PACKAGE_NAME + ".ACTION_SAVE_CREDENTIALS"; // } // } // Path: app/src/main/java/discovery/contentful/activities/MapActivity.java import android.content.Intent; import android.os.Bundle; import discovery.contentful.R; import discovery.contentful.utils.IntentConsts; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; package discovery.contentful.activities; public class MapActivity extends CFFragmentActivity implements OnMapReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.fragment_map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { Intent intent = getIntent();
LatLng latLng = intent.getParcelableExtra(IntentConsts.EXTRA_LOCATION);
contentful/discovery-app-android
app/src/main/java/discovery/contentful/preview/PreviewViewFactory.java
// Path: app/src/main/java/discovery/contentful/ui/DisplayItem.java // public class DisplayItem { // public String key; // public String displayValue; // public String fieldType; // public CDAResource resource; // public String imageURI; // public LatLng location; // // // Array // public List<Object> array; // public String arrayItemType; // public String arrayLinkType; // }
import android.content.Context; import android.support.annotation.LayoutRes; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import discovery.contentful.ui.DisplayItem;
package discovery.contentful.preview; public abstract class PreviewViewFactory<T extends AbsViewHolder> { @SuppressWarnings("unchecked")
// Path: app/src/main/java/discovery/contentful/ui/DisplayItem.java // public class DisplayItem { // public String key; // public String displayValue; // public String fieldType; // public CDAResource resource; // public String imageURI; // public LatLng location; // // // Array // public List<Object> array; // public String arrayItemType; // public String arrayLinkType; // } // Path: app/src/main/java/discovery/contentful/preview/PreviewViewFactory.java import android.content.Context; import android.support.annotation.LayoutRes; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import discovery.contentful.ui.DisplayItem; package discovery.contentful.preview; public abstract class PreviewViewFactory<T extends AbsViewHolder> { @SuppressWarnings("unchecked")
public T getView(Context context, View convertView, ViewGroup parent, DisplayItem displayItem,
contentful/discovery-app-android
app/src/main/java/discovery/contentful/loaders/ResourceArrayLoader.java
// Path: app/src/main/java/discovery/contentful/api/ResourceList.java // public class ResourceList { // public List<CDAResource> resources; // public Map<String, CDAContentType> contentTypes; // }
import discovery.contentful.api.ResourceList; import com.contentful.java.cda.CDAClient; import com.contentful.java.cda.CDAResource; import java.util.ArrayList;
package discovery.contentful.loaders; public class ResourceArrayLoader extends AbsResourceListLoader { private final ArrayList<Object> resources; public ResourceArrayLoader(ArrayList<Object> resources) { super(); this.resources = resources; }
// Path: app/src/main/java/discovery/contentful/api/ResourceList.java // public class ResourceList { // public List<CDAResource> resources; // public Map<String, CDAContentType> contentTypes; // } // Path: app/src/main/java/discovery/contentful/loaders/ResourceArrayLoader.java import discovery.contentful.api.ResourceList; import com.contentful.java.cda.CDAClient; import com.contentful.java.cda.CDAResource; import java.util.ArrayList; package discovery.contentful.loaders; public class ResourceArrayLoader extends AbsResourceListLoader { private final ArrayList<Object> resources; public ResourceArrayLoader(ArrayList<Object> resources) { super(); this.resources = resources; }
@Override protected ResourceList performLoad(CDAClient client) {
contentful/discovery-app-android
app/src/main/java/discovery/contentful/adapters/TutorialAdapter.java
// Path: app/src/main/java/discovery/contentful/loaders/TutorialLoader.java // public class TutorialLoader extends AbsAsyncTaskLoader<TutorialLoader.Tutorial> { // @Override protected Tutorial performLoad() { // try { // Tutorial tmp = new Tutorial(); // CDAEntry entry = CFDiscoveryClient.getClient().fetch(CDAEntry.class) // .one(CFApp.getInstance().getResources().getString(R.string.discovery_space_tutorial_id)); // // CDAAsset bgAsset = entry.getField("backgroundImageIPad"); // // // Background image // tmp.backgroundImageUrl = "http:" + bgAsset.url(); // // // Pages // tmp.pages = new ArrayList<>(); // ArrayList<?> pages = entry.getField("pages"); // for (Object p : pages) { // if (p instanceof CDAEntry) { // CDAEntry pageEntry = (CDAEntry) p; // tmp.pages.add(getPageForEntry(pageEntry)); // } // } // // return tmp; // } catch (RetrofitError e) { // e.printStackTrace(); // } // // return null; // } // // private static Tutorial.Page getPageForEntry(CDAEntry entry) { // Tutorial.Page page = new Tutorial.Page(); // page.headline = entry.getField("headline"); // page.content = entry.getField("content"); // page.asset = entry.getField("asset"); // return page; // } // // public static class Tutorial { // public String backgroundImageUrl; // public ArrayList<Page> pages; // // public static class Page { // public String headline; // public String content; // public CDAAsset asset; // } // } // } // // Path: app/src/main/java/discovery/contentful/ui/TutorialView.java // public class TutorialView extends LinearLayout { // @Bind(R.id.tv_headline) TextView tvHeadline; // @Bind(R.id.iv_photo) ImageView ivPhoto; // @Bind(R.id.tv_content) TextView tvContent; // @BindDimen(R.dimen.view_tutorial_padding) int padding; // // public TutorialView(Context context) { // super(context); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs) { // super(context, attrs); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context); // } // // private void init(Context context) { // setOrientation(VERTICAL); // View.inflate(context, R.layout.view_tutorial, this); // ButterKnife.bind(this); // setPadding(padding, 0, padding, padding); // } // // public void setPage(TutorialLoader.Tutorial.Page page) { // // Headline // tvHeadline.setText(page.headline); // // // Photo // Picasso.with(getContext()) // .load("http:" + page.asset.url()) // .fit() // .centerInside() // .into(ivPhoto); // // // Content // tvContent.setText(page.content.trim()); // } // }
import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import discovery.contentful.loaders.TutorialLoader; import discovery.contentful.ui.TutorialView;
package discovery.contentful.adapters; public class TutorialAdapter extends PagerAdapter { private static final int POS_VIDEO = 0; private Context context;
// Path: app/src/main/java/discovery/contentful/loaders/TutorialLoader.java // public class TutorialLoader extends AbsAsyncTaskLoader<TutorialLoader.Tutorial> { // @Override protected Tutorial performLoad() { // try { // Tutorial tmp = new Tutorial(); // CDAEntry entry = CFDiscoveryClient.getClient().fetch(CDAEntry.class) // .one(CFApp.getInstance().getResources().getString(R.string.discovery_space_tutorial_id)); // // CDAAsset bgAsset = entry.getField("backgroundImageIPad"); // // // Background image // tmp.backgroundImageUrl = "http:" + bgAsset.url(); // // // Pages // tmp.pages = new ArrayList<>(); // ArrayList<?> pages = entry.getField("pages"); // for (Object p : pages) { // if (p instanceof CDAEntry) { // CDAEntry pageEntry = (CDAEntry) p; // tmp.pages.add(getPageForEntry(pageEntry)); // } // } // // return tmp; // } catch (RetrofitError e) { // e.printStackTrace(); // } // // return null; // } // // private static Tutorial.Page getPageForEntry(CDAEntry entry) { // Tutorial.Page page = new Tutorial.Page(); // page.headline = entry.getField("headline"); // page.content = entry.getField("content"); // page.asset = entry.getField("asset"); // return page; // } // // public static class Tutorial { // public String backgroundImageUrl; // public ArrayList<Page> pages; // // public static class Page { // public String headline; // public String content; // public CDAAsset asset; // } // } // } // // Path: app/src/main/java/discovery/contentful/ui/TutorialView.java // public class TutorialView extends LinearLayout { // @Bind(R.id.tv_headline) TextView tvHeadline; // @Bind(R.id.iv_photo) ImageView ivPhoto; // @Bind(R.id.tv_content) TextView tvContent; // @BindDimen(R.dimen.view_tutorial_padding) int padding; // // public TutorialView(Context context) { // super(context); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs) { // super(context, attrs); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context); // } // // private void init(Context context) { // setOrientation(VERTICAL); // View.inflate(context, R.layout.view_tutorial, this); // ButterKnife.bind(this); // setPadding(padding, 0, padding, padding); // } // // public void setPage(TutorialLoader.Tutorial.Page page) { // // Headline // tvHeadline.setText(page.headline); // // // Photo // Picasso.with(getContext()) // .load("http:" + page.asset.url()) // .fit() // .centerInside() // .into(ivPhoto); // // // Content // tvContent.setText(page.content.trim()); // } // } // Path: app/src/main/java/discovery/contentful/adapters/TutorialAdapter.java import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import discovery.contentful.loaders.TutorialLoader; import discovery.contentful.ui.TutorialView; package discovery.contentful.adapters; public class TutorialAdapter extends PagerAdapter { private static final int POS_VIDEO = 0; private Context context;
private TutorialLoader.Tutorial tutorial;
contentful/discovery-app-android
app/src/main/java/discovery/contentful/adapters/TutorialAdapter.java
// Path: app/src/main/java/discovery/contentful/loaders/TutorialLoader.java // public class TutorialLoader extends AbsAsyncTaskLoader<TutorialLoader.Tutorial> { // @Override protected Tutorial performLoad() { // try { // Tutorial tmp = new Tutorial(); // CDAEntry entry = CFDiscoveryClient.getClient().fetch(CDAEntry.class) // .one(CFApp.getInstance().getResources().getString(R.string.discovery_space_tutorial_id)); // // CDAAsset bgAsset = entry.getField("backgroundImageIPad"); // // // Background image // tmp.backgroundImageUrl = "http:" + bgAsset.url(); // // // Pages // tmp.pages = new ArrayList<>(); // ArrayList<?> pages = entry.getField("pages"); // for (Object p : pages) { // if (p instanceof CDAEntry) { // CDAEntry pageEntry = (CDAEntry) p; // tmp.pages.add(getPageForEntry(pageEntry)); // } // } // // return tmp; // } catch (RetrofitError e) { // e.printStackTrace(); // } // // return null; // } // // private static Tutorial.Page getPageForEntry(CDAEntry entry) { // Tutorial.Page page = new Tutorial.Page(); // page.headline = entry.getField("headline"); // page.content = entry.getField("content"); // page.asset = entry.getField("asset"); // return page; // } // // public static class Tutorial { // public String backgroundImageUrl; // public ArrayList<Page> pages; // // public static class Page { // public String headline; // public String content; // public CDAAsset asset; // } // } // } // // Path: app/src/main/java/discovery/contentful/ui/TutorialView.java // public class TutorialView extends LinearLayout { // @Bind(R.id.tv_headline) TextView tvHeadline; // @Bind(R.id.iv_photo) ImageView ivPhoto; // @Bind(R.id.tv_content) TextView tvContent; // @BindDimen(R.dimen.view_tutorial_padding) int padding; // // public TutorialView(Context context) { // super(context); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs) { // super(context, attrs); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context); // } // // private void init(Context context) { // setOrientation(VERTICAL); // View.inflate(context, R.layout.view_tutorial, this); // ButterKnife.bind(this); // setPadding(padding, 0, padding, padding); // } // // public void setPage(TutorialLoader.Tutorial.Page page) { // // Headline // tvHeadline.setText(page.headline); // // // Photo // Picasso.with(getContext()) // .load("http:" + page.asset.url()) // .fit() // .centerInside() // .into(ivPhoto); // // // Content // tvContent.setText(page.content.trim()); // } // }
import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import discovery.contentful.loaders.TutorialLoader; import discovery.contentful.ui.TutorialView;
package discovery.contentful.adapters; public class TutorialAdapter extends PagerAdapter { private static final int POS_VIDEO = 0; private Context context; private TutorialLoader.Tutorial tutorial; private Listener listener; public interface Listener { void onVideoClicked(); } public TutorialAdapter(Context context) { this.context = context; } @Override public int getCount() { if (tutorial == null) { return 0; } return tutorial.pages.size(); } @Override public Object instantiateItem(ViewGroup container, int position) {
// Path: app/src/main/java/discovery/contentful/loaders/TutorialLoader.java // public class TutorialLoader extends AbsAsyncTaskLoader<TutorialLoader.Tutorial> { // @Override protected Tutorial performLoad() { // try { // Tutorial tmp = new Tutorial(); // CDAEntry entry = CFDiscoveryClient.getClient().fetch(CDAEntry.class) // .one(CFApp.getInstance().getResources().getString(R.string.discovery_space_tutorial_id)); // // CDAAsset bgAsset = entry.getField("backgroundImageIPad"); // // // Background image // tmp.backgroundImageUrl = "http:" + bgAsset.url(); // // // Pages // tmp.pages = new ArrayList<>(); // ArrayList<?> pages = entry.getField("pages"); // for (Object p : pages) { // if (p instanceof CDAEntry) { // CDAEntry pageEntry = (CDAEntry) p; // tmp.pages.add(getPageForEntry(pageEntry)); // } // } // // return tmp; // } catch (RetrofitError e) { // e.printStackTrace(); // } // // return null; // } // // private static Tutorial.Page getPageForEntry(CDAEntry entry) { // Tutorial.Page page = new Tutorial.Page(); // page.headline = entry.getField("headline"); // page.content = entry.getField("content"); // page.asset = entry.getField("asset"); // return page; // } // // public static class Tutorial { // public String backgroundImageUrl; // public ArrayList<Page> pages; // // public static class Page { // public String headline; // public String content; // public CDAAsset asset; // } // } // } // // Path: app/src/main/java/discovery/contentful/ui/TutorialView.java // public class TutorialView extends LinearLayout { // @Bind(R.id.tv_headline) TextView tvHeadline; // @Bind(R.id.iv_photo) ImageView ivPhoto; // @Bind(R.id.tv_content) TextView tvContent; // @BindDimen(R.dimen.view_tutorial_padding) int padding; // // public TutorialView(Context context) { // super(context); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs) { // super(context, attrs); // init(context); // } // // public TutorialView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context); // } // // private void init(Context context) { // setOrientation(VERTICAL); // View.inflate(context, R.layout.view_tutorial, this); // ButterKnife.bind(this); // setPadding(padding, 0, padding, padding); // } // // public void setPage(TutorialLoader.Tutorial.Page page) { // // Headline // tvHeadline.setText(page.headline); // // // Photo // Picasso.with(getContext()) // .load("http:" + page.asset.url()) // .fit() // .centerInside() // .into(ivPhoto); // // // Content // tvContent.setText(page.content.trim()); // } // } // Path: app/src/main/java/discovery/contentful/adapters/TutorialAdapter.java import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import discovery.contentful.loaders.TutorialLoader; import discovery.contentful.ui.TutorialView; package discovery.contentful.adapters; public class TutorialAdapter extends PagerAdapter { private static final int POS_VIDEO = 0; private Context context; private TutorialLoader.Tutorial tutorial; private Listener listener; public interface Listener { void onVideoClicked(); } public TutorialAdapter(Context context) { this.context = context; } @Override public int getCount() { if (tutorial == null) { return 0; } return tutorial.pages.size(); } @Override public Object instantiateItem(ViewGroup container, int position) {
TutorialView tutorialView = new TutorialView(context);
contentful/discovery-app-android
app/src/main/java/discovery/contentful/loaders/AbsResourceListLoader.java
// Path: app/src/main/java/discovery/contentful/api/CFClient.java // public class CFClient { // private static CDAClient sInstance; // private static String locale; // // private CFClient() { // } // // /** // * Initialize this client. // * // * @param space String representing the Space key. // * @param token String representing the access token required to log in to the Space. // * @return {@link com.contentful.java.cda.CDAClient} instance. // */ // public synchronized static CDAClient init(String space, String token) { // SharedPreferences prefs = CFPrefs.getInstance(); // // prefs.edit() // .putString(CFPrefs.KEY_SPACE, space) // .putString(CFPrefs.KEY_ACCESS_TOKEN, token) // .apply(); // // sInstance = CDAClient.builder().setSpace(space).setToken(token).build(); // // locale = null; // // return sInstance; // } // // public synchronized static CDAClient getClient() { // if (sInstance == null) { // SharedPreferences prefs = CFPrefs.getInstance(); // // String space = prefs.getString(CFPrefs.KEY_SPACE, null); // String token = prefs.getString(CFPrefs.KEY_ACCESS_TOKEN, null); // // if (StringUtils.isBlank(space) || StringUtils.isBlank(token)) { // throw new IllegalStateException("Uninitialized client."); // } // // return init(space, token); // } // // return sInstance; // } // // /** // * Set the locale for this client. // * // * @param locale String representing the Locale code. // */ // public synchronized static void setLocale(String locale) { // CFClient.locale = locale; // } // // /** // * Gets the current locale defined for this client. // * // * @return String representing the current configured locale, null in case the default // * locale is being used. // */ // public static String getLocale() { // return locale; // } // } // // Path: app/src/main/java/discovery/contentful/api/ResourceList.java // public class ResourceList { // public List<CDAResource> resources; // public Map<String, CDAContentType> contentTypes; // }
import discovery.contentful.api.CFClient; import discovery.contentful.api.ResourceList; import com.contentful.java.cda.CDAArray; import com.contentful.java.cda.CDAClient; import com.contentful.java.cda.CDAContentType; import com.contentful.java.cda.CDAResource; import java.util.HashMap; import retrofit.RetrofitError;
package discovery.contentful.loaders; public abstract class AbsResourceListLoader extends AbsAsyncTaskLoader<ResourceList> { @Override protected ResourceList performLoad() {
// Path: app/src/main/java/discovery/contentful/api/CFClient.java // public class CFClient { // private static CDAClient sInstance; // private static String locale; // // private CFClient() { // } // // /** // * Initialize this client. // * // * @param space String representing the Space key. // * @param token String representing the access token required to log in to the Space. // * @return {@link com.contentful.java.cda.CDAClient} instance. // */ // public synchronized static CDAClient init(String space, String token) { // SharedPreferences prefs = CFPrefs.getInstance(); // // prefs.edit() // .putString(CFPrefs.KEY_SPACE, space) // .putString(CFPrefs.KEY_ACCESS_TOKEN, token) // .apply(); // // sInstance = CDAClient.builder().setSpace(space).setToken(token).build(); // // locale = null; // // return sInstance; // } // // public synchronized static CDAClient getClient() { // if (sInstance == null) { // SharedPreferences prefs = CFPrefs.getInstance(); // // String space = prefs.getString(CFPrefs.KEY_SPACE, null); // String token = prefs.getString(CFPrefs.KEY_ACCESS_TOKEN, null); // // if (StringUtils.isBlank(space) || StringUtils.isBlank(token)) { // throw new IllegalStateException("Uninitialized client."); // } // // return init(space, token); // } // // return sInstance; // } // // /** // * Set the locale for this client. // * // * @param locale String representing the Locale code. // */ // public synchronized static void setLocale(String locale) { // CFClient.locale = locale; // } // // /** // * Gets the current locale defined for this client. // * // * @return String representing the current configured locale, null in case the default // * locale is being used. // */ // public static String getLocale() { // return locale; // } // } // // Path: app/src/main/java/discovery/contentful/api/ResourceList.java // public class ResourceList { // public List<CDAResource> resources; // public Map<String, CDAContentType> contentTypes; // } // Path: app/src/main/java/discovery/contentful/loaders/AbsResourceListLoader.java import discovery.contentful.api.CFClient; import discovery.contentful.api.ResourceList; import com.contentful.java.cda.CDAArray; import com.contentful.java.cda.CDAClient; import com.contentful.java.cda.CDAContentType; import com.contentful.java.cda.CDAResource; import java.util.HashMap; import retrofit.RetrofitError; package discovery.contentful.loaders; public abstract class AbsResourceListLoader extends AbsAsyncTaskLoader<ResourceList> { @Override protected ResourceList performLoad() {
CDAClient client = CFClient.getClient();
contentful/discovery-app-android
app/src/main/java/discovery/contentful/loaders/AssetsLoader.java
// Path: app/src/main/java/discovery/contentful/api/CFClient.java // public class CFClient { // private static CDAClient sInstance; // private static String locale; // // private CFClient() { // } // // /** // * Initialize this client. // * // * @param space String representing the Space key. // * @param token String representing the access token required to log in to the Space. // * @return {@link com.contentful.java.cda.CDAClient} instance. // */ // public synchronized static CDAClient init(String space, String token) { // SharedPreferences prefs = CFPrefs.getInstance(); // // prefs.edit() // .putString(CFPrefs.KEY_SPACE, space) // .putString(CFPrefs.KEY_ACCESS_TOKEN, token) // .apply(); // // sInstance = CDAClient.builder().setSpace(space).setToken(token).build(); // // locale = null; // // return sInstance; // } // // public synchronized static CDAClient getClient() { // if (sInstance == null) { // SharedPreferences prefs = CFPrefs.getInstance(); // // String space = prefs.getString(CFPrefs.KEY_SPACE, null); // String token = prefs.getString(CFPrefs.KEY_ACCESS_TOKEN, null); // // if (StringUtils.isBlank(space) || StringUtils.isBlank(token)) { // throw new IllegalStateException("Uninitialized client."); // } // // return init(space, token); // } // // return sInstance; // } // // /** // * Set the locale for this client. // * // * @param locale String representing the Locale code. // */ // public synchronized static void setLocale(String locale) { // CFClient.locale = locale; // } // // /** // * Gets the current locale defined for this client. // * // * @return String representing the current configured locale, null in case the default // * locale is being used. // */ // public static String getLocale() { // return locale; // } // }
import discovery.contentful.api.CFClient; import com.contentful.java.cda.CDAAsset; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import retrofit.RetrofitError;
package discovery.contentful.loaders; public class AssetsLoader extends AbsAsyncTaskLoader<ArrayList<CDAAsset>> { private static Gson gson; public AssetsLoader() { super(); if (gson == null) { gson = new GsonBuilder().create(); } } @Override protected ArrayList<CDAAsset> performLoad() { try {
// Path: app/src/main/java/discovery/contentful/api/CFClient.java // public class CFClient { // private static CDAClient sInstance; // private static String locale; // // private CFClient() { // } // // /** // * Initialize this client. // * // * @param space String representing the Space key. // * @param token String representing the access token required to log in to the Space. // * @return {@link com.contentful.java.cda.CDAClient} instance. // */ // public synchronized static CDAClient init(String space, String token) { // SharedPreferences prefs = CFPrefs.getInstance(); // // prefs.edit() // .putString(CFPrefs.KEY_SPACE, space) // .putString(CFPrefs.KEY_ACCESS_TOKEN, token) // .apply(); // // sInstance = CDAClient.builder().setSpace(space).setToken(token).build(); // // locale = null; // // return sInstance; // } // // public synchronized static CDAClient getClient() { // if (sInstance == null) { // SharedPreferences prefs = CFPrefs.getInstance(); // // String space = prefs.getString(CFPrefs.KEY_SPACE, null); // String token = prefs.getString(CFPrefs.KEY_ACCESS_TOKEN, null); // // if (StringUtils.isBlank(space) || StringUtils.isBlank(token)) { // throw new IllegalStateException("Uninitialized client."); // } // // return init(space, token); // } // // return sInstance; // } // // /** // * Set the locale for this client. // * // * @param locale String representing the Locale code. // */ // public synchronized static void setLocale(String locale) { // CFClient.locale = locale; // } // // /** // * Gets the current locale defined for this client. // * // * @return String representing the current configured locale, null in case the default // * locale is being used. // */ // public static String getLocale() { // return locale; // } // } // Path: app/src/main/java/discovery/contentful/loaders/AssetsLoader.java import discovery.contentful.api.CFClient; import com.contentful.java.cda.CDAAsset; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import retrofit.RetrofitError; package discovery.contentful.loaders; public class AssetsLoader extends AbsAsyncTaskLoader<ArrayList<CDAAsset>> { private static Gson gson; public AssetsLoader() { super(); if (gson == null) { gson = new GsonBuilder().create(); } } @Override protected ArrayList<CDAAsset> performLoad() { try {
return new ArrayList<>(CFClient.getClient().fetch(CDAAsset.class).all().assets().values());
contentful/discovery-app-android
app/src/main/java/discovery/contentful/preview/EntryListAdapter.java
// Path: app/src/main/java/discovery/contentful/ui/FieldViewHolder.java // public class FieldViewHolder { // public @Bind(R.id.tv_title) CFTextView tvTitle; // public @Bind(R.id.tv_value) CFTextView tvValue; // public @Bind(R.id.iv_arrow) ImageView ivArrow; // // public FieldViewHolder(View v) { // ButterKnife.bind(this, v); // } // } // // Path: app/src/main/java/discovery/contentful/utils/ViewHelper.java // public class ViewHelper { // private ViewHelper() { // } // // /** // * Register a callback to be invoked when the global layout state or the visibility of views // * within the view tree changes. // * // * @param v The View. // * @param listener The callback to add. // * @see #removeGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // public static void addGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // // if (observer == null || !observer.isAlive()) { // return; // } // // observer.addOnGlobalLayoutListener(listener); // } // // /** // * Remove a previously installed global layout callback. // * // * @param v The View. // * @param listener The callback to remove. // * @see #addGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static void removeGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // if (observer == null || !observer.isAlive()) { // return; // } // // if (Build.VERSION.SDK_INT < 16) { // observer.removeGlobalOnLayoutListener(listener); // } else { // observer.removeOnGlobalLayoutListener(listener); // } // } // // public static void setVisibility(View v, boolean show) { // if (show) { // v.setVisibility(View.VISIBLE); // } else { // v.setVisibility(View.GONE); // } // } // }
import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import discovery.contentful.R; import discovery.contentful.ui.FieldViewHolder; import discovery.contentful.utils.ViewHelper; import com.contentful.java.cda.CDAContentType; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAField; import java.util.List; import java.util.Locale; import java.util.Map;
package discovery.contentful.preview; public class EntryListAdapter extends BaseAdapter { private final Context context; private final CDAEntry entry; private final List<CDAField> contentTypeFields; public EntryListAdapter(Context context, CDAEntry entry, CDAContentType contentType) { this.context = context; this.entry = entry; this.contentTypeFields = contentType.fields(); } @Override public int getCount() { return contentTypeFields.size(); } @Override public CDAField getItem(int position) { return contentTypeFields.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) {
// Path: app/src/main/java/discovery/contentful/ui/FieldViewHolder.java // public class FieldViewHolder { // public @Bind(R.id.tv_title) CFTextView tvTitle; // public @Bind(R.id.tv_value) CFTextView tvValue; // public @Bind(R.id.iv_arrow) ImageView ivArrow; // // public FieldViewHolder(View v) { // ButterKnife.bind(this, v); // } // } // // Path: app/src/main/java/discovery/contentful/utils/ViewHelper.java // public class ViewHelper { // private ViewHelper() { // } // // /** // * Register a callback to be invoked when the global layout state or the visibility of views // * within the view tree changes. // * // * @param v The View. // * @param listener The callback to add. // * @see #removeGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // public static void addGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // // if (observer == null || !observer.isAlive()) { // return; // } // // observer.addOnGlobalLayoutListener(listener); // } // // /** // * Remove a previously installed global layout callback. // * // * @param v The View. // * @param listener The callback to remove. // * @see #addGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static void removeGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // if (observer == null || !observer.isAlive()) { // return; // } // // if (Build.VERSION.SDK_INT < 16) { // observer.removeGlobalOnLayoutListener(listener); // } else { // observer.removeOnGlobalLayoutListener(listener); // } // } // // public static void setVisibility(View v, boolean show) { // if (show) { // v.setVisibility(View.VISIBLE); // } else { // v.setVisibility(View.GONE); // } // } // } // Path: app/src/main/java/discovery/contentful/preview/EntryListAdapter.java import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import discovery.contentful.R; import discovery.contentful.ui.FieldViewHolder; import discovery.contentful.utils.ViewHelper; import com.contentful.java.cda.CDAContentType; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAField; import java.util.List; import java.util.Locale; import java.util.Map; package discovery.contentful.preview; public class EntryListAdapter extends BaseAdapter { private final Context context; private final CDAEntry entry; private final List<CDAField> contentTypeFields; public EntryListAdapter(Context context, CDAEntry entry, CDAContentType contentType) { this.context = context; this.entry = entry; this.contentTypeFields = contentType.fields(); } @Override public int getCount() { return contentTypeFields.size(); } @Override public CDAField getItem(int position) { return contentTypeFields.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) {
FieldViewHolder vh;
contentful/discovery-app-android
app/src/main/java/discovery/contentful/preview/EntryListAdapter.java
// Path: app/src/main/java/discovery/contentful/ui/FieldViewHolder.java // public class FieldViewHolder { // public @Bind(R.id.tv_title) CFTextView tvTitle; // public @Bind(R.id.tv_value) CFTextView tvValue; // public @Bind(R.id.iv_arrow) ImageView ivArrow; // // public FieldViewHolder(View v) { // ButterKnife.bind(this, v); // } // } // // Path: app/src/main/java/discovery/contentful/utils/ViewHelper.java // public class ViewHelper { // private ViewHelper() { // } // // /** // * Register a callback to be invoked when the global layout state or the visibility of views // * within the view tree changes. // * // * @param v The View. // * @param listener The callback to add. // * @see #removeGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // public static void addGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // // if (observer == null || !observer.isAlive()) { // return; // } // // observer.addOnGlobalLayoutListener(listener); // } // // /** // * Remove a previously installed global layout callback. // * // * @param v The View. // * @param listener The callback to remove. // * @see #addGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static void removeGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // if (observer == null || !observer.isAlive()) { // return; // } // // if (Build.VERSION.SDK_INT < 16) { // observer.removeGlobalOnLayoutListener(listener); // } else { // observer.removeOnGlobalLayoutListener(listener); // } // } // // public static void setVisibility(View v, boolean show) { // if (show) { // v.setVisibility(View.VISIBLE); // } else { // v.setVisibility(View.GONE); // } // } // }
import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import discovery.contentful.R; import discovery.contentful.ui.FieldViewHolder; import discovery.contentful.utils.ViewHelper; import com.contentful.java.cda.CDAContentType; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAField; import java.util.List; import java.util.Locale; import java.util.Map;
@Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { FieldViewHolder vh; if (convertView == null) { convertView = View.inflate(context, R.layout.view_field, null); convertView.setTag(vh = new FieldViewHolder(convertView)); } else { vh = (FieldViewHolder) convertView.getTag(); } CDAField item = getItem(position); Object value = entry.getField(item.id()); String fieldType = item.type(); // Title vh.tvTitle.setText(item.name()); // Value if (value != null && isDisplayableFieldType(fieldType)) { vh.tvValue.setText(normalizeDisplayValue(fieldType, value)); vh.tvValue.setVisibility(View.VISIBLE); } else { vh.tvValue.setVisibility(View.GONE); } // Arrow
// Path: app/src/main/java/discovery/contentful/ui/FieldViewHolder.java // public class FieldViewHolder { // public @Bind(R.id.tv_title) CFTextView tvTitle; // public @Bind(R.id.tv_value) CFTextView tvValue; // public @Bind(R.id.iv_arrow) ImageView ivArrow; // // public FieldViewHolder(View v) { // ButterKnife.bind(this, v); // } // } // // Path: app/src/main/java/discovery/contentful/utils/ViewHelper.java // public class ViewHelper { // private ViewHelper() { // } // // /** // * Register a callback to be invoked when the global layout state or the visibility of views // * within the view tree changes. // * // * @param v The View. // * @param listener The callback to add. // * @see #removeGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // public static void addGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // // if (observer == null || !observer.isAlive()) { // return; // } // // observer.addOnGlobalLayoutListener(listener); // } // // /** // * Remove a previously installed global layout callback. // * // * @param v The View. // * @param listener The callback to remove. // * @see #addGlobalLayoutListener(View, ViewTreeObserver.OnGlobalLayoutListener). // */ // @SuppressWarnings("deprecation") // @SuppressLint("NewApi") // public static void removeGlobalLayoutListener(View v, // ViewTreeObserver.OnGlobalLayoutListener listener) { // ViewTreeObserver observer = v.getViewTreeObserver(); // if (observer == null || !observer.isAlive()) { // return; // } // // if (Build.VERSION.SDK_INT < 16) { // observer.removeGlobalOnLayoutListener(listener); // } else { // observer.removeOnGlobalLayoutListener(listener); // } // } // // public static void setVisibility(View v, boolean show) { // if (show) { // v.setVisibility(View.VISIBLE); // } else { // v.setVisibility(View.GONE); // } // } // } // Path: app/src/main/java/discovery/contentful/preview/EntryListAdapter.java import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import discovery.contentful.R; import discovery.contentful.ui.FieldViewHolder; import discovery.contentful.utils.ViewHelper; import com.contentful.java.cda.CDAContentType; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAField; import java.util.List; import java.util.Locale; import java.util.Map; @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { FieldViewHolder vh; if (convertView == null) { convertView = View.inflate(context, R.layout.view_field, null); convertView.setTag(vh = new FieldViewHolder(convertView)); } else { vh = (FieldViewHolder) convertView.getTag(); } CDAField item = getItem(position); Object value = entry.getField(item.id()); String fieldType = item.type(); // Title vh.tvTitle.setText(item.name()); // Value if (value != null && isDisplayableFieldType(fieldType)) { vh.tvValue.setText(normalizeDisplayValue(fieldType, value)); vh.tvValue.setVisibility(View.VISIBLE); } else { vh.tvValue.setVisibility(View.GONE); } // Arrow
ViewHelper.setVisibility(vh.ivArrow, value != null && isClickableFieldType(fieldType));
ghillert/botanic-ng
src/main/java/com/hillert/botanic/service/DefaultPictureService.java
// Path: src/main/java/com/hillert/botanic/dao/ImageRepository.java // public interface ImageRepository extends CrudRepository<Image, Long>, ImageRepositoryCustom { // } // // Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.hillert.botanic.dao.ImageRepository; import com.hillert.botanic.model.Image;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.service; /** * * @author Gunnar Hillert * @since 1.0 * */ @Service public class DefaultPictureService implements PictureService { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPictureService.class); @Autowired private SimpMessageSendingOperations messagingTemplate; @Autowired
// Path: src/main/java/com/hillert/botanic/dao/ImageRepository.java // public interface ImageRepository extends CrudRepository<Image, Long>, ImageRepositoryCustom { // } // // Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // } // Path: src/main/java/com/hillert/botanic/service/DefaultPictureService.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.hillert.botanic.dao.ImageRepository; import com.hillert.botanic.model.Image; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.service; /** * * @author Gunnar Hillert * @since 1.0 * */ @Service public class DefaultPictureService implements PictureService { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPictureService.class); @Autowired private SimpMessageSendingOperations messagingTemplate; @Autowired
private ImageRepository imageRepository;
ghillert/botanic-ng
src/main/java/com/hillert/botanic/service/DefaultPictureService.java
// Path: src/main/java/com/hillert/botanic/dao/ImageRepository.java // public interface ImageRepository extends CrudRepository<Image, Long>, ImageRepositoryCustom { // } // // Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.hillert.botanic.dao.ImageRepository; import com.hillert.botanic.model.Image;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.service; /** * * @author Gunnar Hillert * @since 1.0 * */ @Service public class DefaultPictureService implements PictureService { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPictureService.class); @Autowired private SimpMessageSendingOperations messagingTemplate; @Autowired private ImageRepository imageRepository; public DefaultPictureService() { super(); } @Scheduled(fixedRate=10000) @Override public void sendRandomPicture() {
// Path: src/main/java/com/hillert/botanic/dao/ImageRepository.java // public interface ImageRepository extends CrudRepository<Image, Long>, ImageRepositoryCustom { // } // // Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // } // Path: src/main/java/com/hillert/botanic/service/DefaultPictureService.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.hillert.botanic.dao.ImageRepository; import com.hillert.botanic.model.Image; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.service; /** * * @author Gunnar Hillert * @since 1.0 * */ @Service public class DefaultPictureService implements PictureService { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPictureService.class); @Autowired private SimpMessageSendingOperations messagingTemplate; @Autowired private ImageRepository imageRepository; public DefaultPictureService() { super(); } @Scheduled(fixedRate=10000) @Override public void sendRandomPicture() {
final Image image = imageRepository.findRandomImage();
ghillert/botanic-ng
src/main/java/com/hillert/botanic/controller/AuthenticationController.java
// Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // super(); // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * @return the password // */ // public String getPassword() { // return password; // } // // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationToken.java // public class AuthenticationToken { // // private String username; // private Map<String, Boolean> roles; // private String[] roles2; // // public AuthenticationToken() { // super(); // } // // public AuthenticationToken(String username, List<String> roles) { // Map<String, Boolean> mapOfRoles = new ConcurrentHashMap<String, Boolean>(); // for (String k : roles) { // mapOfRoles.put(k, true); // } // this.roles = mapOfRoles; // this.roles2 = roles.toArray(new String[roles.size()]); // this.username = username; // } // // public Map<String, Boolean> getRoles() { // return this.roles; // } // // public String[] getRoles2() { // return this.roles2; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // }
import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.hillert.botanic.controller.dto.AuthenticationRequest; import com.hillert.botanic.controller.dto.AuthenticationToken;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.controller; /** * This controller generates the {@link AuthenticationToken} that must be present * in subsequent REST invocations. * * @author Gunnar Hillert * @since 1.0 * */ @RestController public class AuthenticationController { private final AuthenticationManager authenticationManager; private final UserDetailsService userDetailsService; @Autowired public AuthenticationController(AuthenticationManager am, UserDetailsService userDetailsService) { this.authenticationManager = am; this.userDetailsService = userDetailsService; } @RequestMapping("/api/logout") @ResponseStatus(HttpStatus.NO_CONTENT) public void logout(HttpSession session) { session.invalidate(); } @RequestMapping(value = "/api/info", method = { RequestMethod.GET })
// Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // super(); // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * @return the password // */ // public String getPassword() { // return password; // } // // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationToken.java // public class AuthenticationToken { // // private String username; // private Map<String, Boolean> roles; // private String[] roles2; // // public AuthenticationToken() { // super(); // } // // public AuthenticationToken(String username, List<String> roles) { // Map<String, Boolean> mapOfRoles = new ConcurrentHashMap<String, Boolean>(); // for (String k : roles) { // mapOfRoles.put(k, true); // } // this.roles = mapOfRoles; // this.roles2 = roles.toArray(new String[roles.size()]); // this.username = username; // } // // public Map<String, Boolean> getRoles() { // return this.roles; // } // // public String[] getRoles2() { // return this.roles2; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // } // Path: src/main/java/com/hillert/botanic/controller/AuthenticationController.java import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.hillert.botanic.controller.dto.AuthenticationRequest; import com.hillert.botanic.controller.dto.AuthenticationToken; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.controller; /** * This controller generates the {@link AuthenticationToken} that must be present * in subsequent REST invocations. * * @author Gunnar Hillert * @since 1.0 * */ @RestController public class AuthenticationController { private final AuthenticationManager authenticationManager; private final UserDetailsService userDetailsService; @Autowired public AuthenticationController(AuthenticationManager am, UserDetailsService userDetailsService) { this.authenticationManager = am; this.userDetailsService = userDetailsService; } @RequestMapping("/api/logout") @ResponseStatus(HttpStatus.NO_CONTENT) public void logout(HttpSession session) { session.invalidate(); } @RequestMapping(value = "/api/info", method = { RequestMethod.GET })
public AuthenticationToken info() {
ghillert/botanic-ng
src/main/java/com/hillert/botanic/controller/AuthenticationController.java
// Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // super(); // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * @return the password // */ // public String getPassword() { // return password; // } // // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationToken.java // public class AuthenticationToken { // // private String username; // private Map<String, Boolean> roles; // private String[] roles2; // // public AuthenticationToken() { // super(); // } // // public AuthenticationToken(String username, List<String> roles) { // Map<String, Boolean> mapOfRoles = new ConcurrentHashMap<String, Boolean>(); // for (String k : roles) { // mapOfRoles.put(k, true); // } // this.roles = mapOfRoles; // this.roles2 = roles.toArray(new String[roles.size()]); // this.username = username; // } // // public Map<String, Boolean> getRoles() { // return this.roles; // } // // public String[] getRoles2() { // return this.roles2; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // }
import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.hillert.botanic.controller.dto.AuthenticationRequest; import com.hillert.botanic.controller.dto.AuthenticationToken;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.controller; /** * This controller generates the {@link AuthenticationToken} that must be present * in subsequent REST invocations. * * @author Gunnar Hillert * @since 1.0 * */ @RestController public class AuthenticationController { private final AuthenticationManager authenticationManager; private final UserDetailsService userDetailsService; @Autowired public AuthenticationController(AuthenticationManager am, UserDetailsService userDetailsService) { this.authenticationManager = am; this.userDetailsService = userDetailsService; } @RequestMapping("/api/logout") @ResponseStatus(HttpStatus.NO_CONTENT) public void logout(HttpSession session) { session.invalidate(); } @RequestMapping(value = "/api/info", method = { RequestMethod.GET }) public AuthenticationToken info() { final String username = SecurityContextHolder.getContext().getAuthentication().getName(); final UserDetails details = this.userDetailsService.loadUserByUsername(username); final List<String> roles = new ArrayList<>(); for (GrantedAuthority authority : details.getAuthorities()) { roles.add(authority.toString()); } return new AuthenticationToken(details.getUsername(), roles); } @RequestMapping(value = "/api/authenticate", method = { RequestMethod.POST }) public AuthenticationToken authorize(
// Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationRequest.java // public class AuthenticationRequest { // // private String username; // private String password; // // public AuthenticationRequest() { // super(); // } // // public AuthenticationRequest(String username, String password) { // this.username = username; // this.password = password; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // /** // * @return the password // */ // public String getPassword() { // return password; // } // // /** // * @param password the password to set // */ // public void setPassword(String password) { // this.password = password; // } // // } // // Path: src/main/java/com/hillert/botanic/controller/dto/AuthenticationToken.java // public class AuthenticationToken { // // private String username; // private Map<String, Boolean> roles; // private String[] roles2; // // public AuthenticationToken() { // super(); // } // // public AuthenticationToken(String username, List<String> roles) { // Map<String, Boolean> mapOfRoles = new ConcurrentHashMap<String, Boolean>(); // for (String k : roles) { // mapOfRoles.put(k, true); // } // this.roles = mapOfRoles; // this.roles2 = roles.toArray(new String[roles.size()]); // this.username = username; // } // // public Map<String, Boolean> getRoles() { // return this.roles; // } // // public String[] getRoles2() { // return this.roles2; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(String username) { // this.username = username; // } // // } // Path: src/main/java/com/hillert/botanic/controller/AuthenticationController.java import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.hillert.botanic.controller.dto.AuthenticationRequest; import com.hillert.botanic.controller.dto.AuthenticationToken; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.controller; /** * This controller generates the {@link AuthenticationToken} that must be present * in subsequent REST invocations. * * @author Gunnar Hillert * @since 1.0 * */ @RestController public class AuthenticationController { private final AuthenticationManager authenticationManager; private final UserDetailsService userDetailsService; @Autowired public AuthenticationController(AuthenticationManager am, UserDetailsService userDetailsService) { this.authenticationManager = am; this.userDetailsService = userDetailsService; } @RequestMapping("/api/logout") @ResponseStatus(HttpStatus.NO_CONTENT) public void logout(HttpSession session) { session.invalidate(); } @RequestMapping(value = "/api/info", method = { RequestMethod.GET }) public AuthenticationToken info() { final String username = SecurityContextHolder.getContext().getAuthentication().getName(); final UserDetails details = this.userDetailsService.loadUserByUsername(username); final List<String> roles = new ArrayList<>(); for (GrantedAuthority authority : details.getAuthorities()) { roles.add(authority.toString()); } return new AuthenticationToken(details.getUsername(), roles); } @RequestMapping(value = "/api/authenticate", method = { RequestMethod.POST }) public AuthenticationToken authorize(
@RequestBody AuthenticationRequest authenticationRequest,
ghillert/botanic-ng
src/main/java/com/hillert/botanic/dao/jpa/ImageRepositoryImpl.java
// Path: src/main/java/com/hillert/botanic/dao/ImageRepositoryCustom.java // @NoRepositoryBean // public interface ImageRepositoryCustom { // // Image findRandomImage(); // // } // // Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // }
import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.hillert.botanic.dao.ImageRepositoryCustom; import com.hillert.botanic.model.Image;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.dao.jpa; /** * * @author Gunnar Hillert * @since 1.0 * */ @Repository public class ImageRepositoryImpl implements ImageRepositoryCustom { @PersistenceContext private EntityManager entityManager; @Override
// Path: src/main/java/com/hillert/botanic/dao/ImageRepositoryCustom.java // @NoRepositoryBean // public interface ImageRepositoryCustom { // // Image findRandomImage(); // // } // // Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // } // Path: src/main/java/com/hillert/botanic/dao/jpa/ImageRepositoryImpl.java import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.hillert.botanic.dao.ImageRepositoryCustom; import com.hillert.botanic.model.Image; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.dao.jpa; /** * * @author Gunnar Hillert * @since 1.0 * */ @Repository public class ImageRepositoryImpl implements ImageRepositoryCustom { @PersistenceContext private EntityManager entityManager; @Override
public Image findRandomImage() {
ghillert/botanic-ng
src/test/java/com/hillert/botanic/controller/BaseControllerTests.java
// Path: src/main/java/com/hillert/botanic/MainApp.java // @SpringBootApplication // public class MainApp { // // public static final String GZIP_COMPRESSION_MIME_TYPES = // MediaType.APPLICATION_JSON_VALUE + "," + "application/javascript" + "," + "text/css"; // // @Bean // public RepositoryRestConfigurer repositoryRestConfigurer() { // return new RepositoryRestConfigurerAdapter() { // @Override // public void configureRepositoryRestConfiguration( // RepositoryRestConfiguration config) { // config.exposeIdsFor(Plant.class, Image.class, Garden.class); // config.setBasePath("/api"); // } // }; // } // // /** // * Main class initializes the Spring Application Context and populates seed // * data using {@link SeedDataService}. // * // * @param args Not used. // */ // public static void main(String[] args) { // final ConfigurableApplicationContext context = SpringApplication.run(MainApp.class, args); // final SeedDataService seedDataService = context.getBean(SeedDataService.class); // seedDataService.populateSeedData(); // } // // @Bean // public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() { // return new Jackson2ObjectMapperBuilderCustomizer() { // // @Override // public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) { // jacksonObjectMapperBuilder.dateFormat(new ISO8601DateFormatWithMilliSeconds()); // } // // }; // } // // } // // Path: src/main/java/com/hillert/botanic/service/SeedDataService.java // public interface SeedDataService { // // void populateSeedData(); // // }
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.hillert.botanic.MainApp; import com.hillert.botanic.service.SeedDataService;
/* * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.controller; /** * * @author Gunnar Hillert * @since 1.0 * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = MainApp.class) @WebAppConfiguration public abstract class BaseControllerTests { protected MockMvc mockMvc; @Autowired private WebApplicationContext wac; @Autowired
// Path: src/main/java/com/hillert/botanic/MainApp.java // @SpringBootApplication // public class MainApp { // // public static final String GZIP_COMPRESSION_MIME_TYPES = // MediaType.APPLICATION_JSON_VALUE + "," + "application/javascript" + "," + "text/css"; // // @Bean // public RepositoryRestConfigurer repositoryRestConfigurer() { // return new RepositoryRestConfigurerAdapter() { // @Override // public void configureRepositoryRestConfiguration( // RepositoryRestConfiguration config) { // config.exposeIdsFor(Plant.class, Image.class, Garden.class); // config.setBasePath("/api"); // } // }; // } // // /** // * Main class initializes the Spring Application Context and populates seed // * data using {@link SeedDataService}. // * // * @param args Not used. // */ // public static void main(String[] args) { // final ConfigurableApplicationContext context = SpringApplication.run(MainApp.class, args); // final SeedDataService seedDataService = context.getBean(SeedDataService.class); // seedDataService.populateSeedData(); // } // // @Bean // public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() { // return new Jackson2ObjectMapperBuilderCustomizer() { // // @Override // public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) { // jacksonObjectMapperBuilder.dateFormat(new ISO8601DateFormatWithMilliSeconds()); // } // // }; // } // // } // // Path: src/main/java/com/hillert/botanic/service/SeedDataService.java // public interface SeedDataService { // // void populateSeedData(); // // } // Path: src/test/java/com/hillert/botanic/controller/BaseControllerTests.java import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.hillert.botanic.MainApp; import com.hillert.botanic.service.SeedDataService; /* * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.controller; /** * * @author Gunnar Hillert * @since 1.0 * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = MainApp.class) @WebAppConfiguration public abstract class BaseControllerTests { protected MockMvc mockMvc; @Autowired private WebApplicationContext wac; @Autowired
SeedDataService seedDataService;
ghillert/botanic-ng
src/main/java/com/hillert/botanic/config/SecurityConfig.java
// Path: src/main/java/com/hillert/botanic/service/DefaultUserDetailsService.java // public class DefaultUserDetailsService implements UserDetailsService { // public static final String ROLE_ADMIN = "ADMIN"; // public static final String ROLE_USER = "USER"; // // @SuppressWarnings("serial") // static class SimpleUserDetails implements UserDetails { // // private String username; // private String password; // private boolean enabled = true; // private Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); // // public SimpleUserDetails(String username, String pw, String... extraRoles) { // this.username = username; // this.password = pw; // // // setup roles // Set<String> roles = new HashSet<String>(); // roles.addAll(Arrays.<String>asList(null == extraRoles ? new String[0] : extraRoles)); // // // export them as part of authorities // for (String r : roles) { // authorities.add(new SimpleGrantedAuthority(role(r))); // } // // } // // public String toString() { // return "{enabled:" + isEnabled() + ", username:'" + getUsername() + "', password:'" + getPassword() + "'}"; // } // // @Override // public boolean isEnabled() { // return this.enabled; // } // // @Override // public boolean isCredentialsNonExpired() { // return this.enabled; // } // // @Override // public boolean isAccountNonLocked() { // return this.enabled; // } // // @Override // public boolean isAccountNonExpired() { // return this.enabled; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public String getPassword() { // return this.password; // } // // private String role(String i) { // return "ROLE_" + i; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return this.authorities; // } // } // // List<UserDetails> details = Arrays.<UserDetails>asList(new SimpleUserDetails("user", "{noop}user", ROLE_USER), new SimpleUserDetails("admin", "{noop}admin", ROLE_USER, ROLE_ADMIN)); // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // for (UserDetails details : this.details) { // if (details.getUsername().equalsIgnoreCase(username)) { // return details; // } // } // throw new UsernameNotFoundException("No user found for username " + username); // } // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import com.hillert.botanic.service.DefaultUserDetailsService;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.config; /** * * @author Gunnar Hillert * @since 1.0 * */ @EnableWebSecurity @Configuration @Order class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http //.addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class) .csrf().disable(); //http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Path: src/main/java/com/hillert/botanic/service/DefaultUserDetailsService.java // public class DefaultUserDetailsService implements UserDetailsService { // public static final String ROLE_ADMIN = "ADMIN"; // public static final String ROLE_USER = "USER"; // // @SuppressWarnings("serial") // static class SimpleUserDetails implements UserDetails { // // private String username; // private String password; // private boolean enabled = true; // private Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); // // public SimpleUserDetails(String username, String pw, String... extraRoles) { // this.username = username; // this.password = pw; // // // setup roles // Set<String> roles = new HashSet<String>(); // roles.addAll(Arrays.<String>asList(null == extraRoles ? new String[0] : extraRoles)); // // // export them as part of authorities // for (String r : roles) { // authorities.add(new SimpleGrantedAuthority(role(r))); // } // // } // // public String toString() { // return "{enabled:" + isEnabled() + ", username:'" + getUsername() + "', password:'" + getPassword() + "'}"; // } // // @Override // public boolean isEnabled() { // return this.enabled; // } // // @Override // public boolean isCredentialsNonExpired() { // return this.enabled; // } // // @Override // public boolean isAccountNonLocked() { // return this.enabled; // } // // @Override // public boolean isAccountNonExpired() { // return this.enabled; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public String getPassword() { // return this.password; // } // // private String role(String i) { // return "ROLE_" + i; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return this.authorities; // } // } // // List<UserDetails> details = Arrays.<UserDetails>asList(new SimpleUserDetails("user", "{noop}user", ROLE_USER), new SimpleUserDetails("admin", "{noop}admin", ROLE_USER, ROLE_ADMIN)); // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // for (UserDetails details : this.details) { // if (details.getUsername().equalsIgnoreCase(username)) { // return details; // } // } // throw new UsernameNotFoundException("No user found for username " + username); // } // } // Path: src/main/java/com/hillert/botanic/config/SecurityConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import com.hillert.botanic.service.DefaultUserDetailsService; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.config; /** * * @author Gunnar Hillert * @since 1.0 * */ @EnableWebSecurity @Configuration @Order class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http //.addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class) .csrf().disable(); //http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/info/**").hasRole(DefaultUserDetailsService.ROLE_USER);
ghillert/botanic-ng
src/main/java/com/hillert/botanic/dao/ImageRepositoryCustom.java
// Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // }
import org.springframework.data.repository.NoRepositoryBean; import com.hillert.botanic.model.Image;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.dao; /** * @author Gunnar Hillert * @since 1.0 */ @NoRepositoryBean public interface ImageRepositoryCustom {
// Path: src/main/java/com/hillert/botanic/model/Image.java // @Entity // public class Image extends BaseModelObject { // // private String name; // // @Lob // private byte[] image; // // @ManyToOne // private Plant plant; // // public Image(String name, Resource data, Plant plant) { // super(); // this.name = name; // this.plant = plant; // // InputStream is = null; // try { // is = data.getInputStream(); // this.image = StreamUtils.copyToByteArray(is); // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // public Image() { // super(); // } // // /** // * @return the name // */ // public String getName() { // return name; // } // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the image // */ // public byte[] getImage() { // return image; // } // /** // * @param image the image to set // */ // public void setImage(byte[] image) { // this.image = image; // } // // /** // * @return the plant // */ // public Plant getPlant() { // return plant; // } // /** // * @param plant the plant to set // */ // public void setPlant(Plant plant) { // this.plant = plant; // } // // } // Path: src/main/java/com/hillert/botanic/dao/ImageRepositoryCustom.java import org.springframework.data.repository.NoRepositoryBean; import com.hillert.botanic.model.Image; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic.dao; /** * @author Gunnar Hillert * @since 1.0 */ @NoRepositoryBean public interface ImageRepositoryCustom {
Image findRandomImage();
ghillert/botanic-ng
src/test/java/com/hillert/botanic/ErrorMesssageTests.java
// Path: src/main/java/com/hillert/botanic/controller/ErrorMessage.java // public class ErrorMessage { // // private final Date timestamp; // private final int status; // private final String exception; // private final String message; // // public ErrorMessage(Date timestamp, int status, String exception, // String message) { // super(); // this.timestamp = timestamp; // this.status = status; // this.exception = exception; // this.message = message; // } // // /** // * @return the timestamp // */ // public Date getTimestamp() { // return timestamp; // } // // /** // * @return the status // */ // public int getStatus() { // return status; // } // // /** // * @return the exception // */ // public String getException() { // return exception; // } // // /** // * @return the message // */ // public String getMessage() { // return message; // } // // }
import java.util.Date; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hillert.botanic.controller.ErrorMessage;
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic; /** * * @author Gunnar Hillert * @since 1.0 * */ public class ErrorMesssageTests { @Test public void testErrorMessageSerialization() throws JsonProcessingException { final ObjectMapper objectMapper = new ObjectMapper();
// Path: src/main/java/com/hillert/botanic/controller/ErrorMessage.java // public class ErrorMessage { // // private final Date timestamp; // private final int status; // private final String exception; // private final String message; // // public ErrorMessage(Date timestamp, int status, String exception, // String message) { // super(); // this.timestamp = timestamp; // this.status = status; // this.exception = exception; // this.message = message; // } // // /** // * @return the timestamp // */ // public Date getTimestamp() { // return timestamp; // } // // /** // * @return the status // */ // public int getStatus() { // return status; // } // // /** // * @return the exception // */ // public String getException() { // return exception; // } // // /** // * @return the message // */ // public String getMessage() { // return message; // } // // } // Path: src/test/java/com/hillert/botanic/ErrorMesssageTests.java import java.util.Date; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hillert.botanic.controller.ErrorMessage; /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hillert.botanic; /** * * @author Gunnar Hillert * @since 1.0 * */ public class ErrorMesssageTests { @Test public void testErrorMessageSerialization() throws JsonProcessingException { final ObjectMapper objectMapper = new ObjectMapper();
ErrorMessage errorMessage = new ErrorMessage(new Date(), 404, "NotFoundException", "We did not find it.");
tfg13/LanXchange
modules/swing/src/main/java/de/tobifleig/lxc/plaf/swing/OptionsDialog.java
// Path: modules/core/src/main/java/de/tobifleig/lxc/Configuration.java // public class Configuration { // // /** // * the backing Hashmap // */ // private static final HashMap<String, String> map = new HashMap<String, String>(); // // /** // * private constructor // */ // private Configuration() { // } // // /** // * Reads a Setting, returns its value as long. // * // * @param setting the setting to read // * @return the saved value, or 0 (default) // */ // public static long getLongSetting(String setting) { // long ret = 0; // try { // ret = Long.parseLong(map.get(setting)); // } catch (Exception ex) { // } // return ret; // } // // /** // * Reads a Settings, returns its value as String // * // * @param setting the setting to read // * @return the saved value, or null (default) // */ // public static String getStringSetting(String setting) { // String ret = null; // try { // ret = map.get(setting); // } catch (Exception ex) { // } // return ret; // } // // /** // * Puts a long-setting. // * overrides previous stored settings // * // * @param setting the key // * @param value the value // */ // public static void putLongSetting(String setting, long value) { // putStringSetting(setting, String.valueOf(value)); // } // // /** // * Puts a String-setting. // * overrides previous stored settings // * // * @param setting the key // * @param value the value // */ // public static void putStringSetting(String setting, String value) { // map.put(setting, value); // } // // /** // * Returns true, if the given setting is contained in this configuration. // * // * @param setting the key // * @return true, if set // */ // public static boolean containsKey(String setting) { // return map.containsKey(setting); // } // // /** // * Returns an Iterator over all keys contained in this configuration. // * // * @return an Iterator over all keys contained in this configuration // */ // public static Iterator<String> getKeyIterator() { // return map.keySet().iterator(); // } // }
import de.tobifleig.lxc.Configuration; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.io.File; import javax.swing.*;
/* * Copyright 2009, 2010, 2011, 2012, 2013, 2014 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.swing; /** * Options-Dialog. * Created by the NetBeans-GuiBuilder. * * @author Tobias Fleig <tobifleig googlemail com> */ public class OptionsDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; /** * Creates new form LXCOptionsDialog * * @param parent * @param modal */ public OptionsDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { setVisible(false); } }); // close help window on ESC getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); getRootPane().getActionMap().put("cancel", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); } }); } /** * Displays this dialog and block until it is closed. */ public void showAndWait() { // Read settings:
// Path: modules/core/src/main/java/de/tobifleig/lxc/Configuration.java // public class Configuration { // // /** // * the backing Hashmap // */ // private static final HashMap<String, String> map = new HashMap<String, String>(); // // /** // * private constructor // */ // private Configuration() { // } // // /** // * Reads a Setting, returns its value as long. // * // * @param setting the setting to read // * @return the saved value, or 0 (default) // */ // public static long getLongSetting(String setting) { // long ret = 0; // try { // ret = Long.parseLong(map.get(setting)); // } catch (Exception ex) { // } // return ret; // } // // /** // * Reads a Settings, returns its value as String // * // * @param setting the setting to read // * @return the saved value, or null (default) // */ // public static String getStringSetting(String setting) { // String ret = null; // try { // ret = map.get(setting); // } catch (Exception ex) { // } // return ret; // } // // /** // * Puts a long-setting. // * overrides previous stored settings // * // * @param setting the key // * @param value the value // */ // public static void putLongSetting(String setting, long value) { // putStringSetting(setting, String.valueOf(value)); // } // // /** // * Puts a String-setting. // * overrides previous stored settings // * // * @param setting the key // * @param value the value // */ // public static void putStringSetting(String setting, String value) { // map.put(setting, value); // } // // /** // * Returns true, if the given setting is contained in this configuration. // * // * @param setting the key // * @return true, if set // */ // public static boolean containsKey(String setting) { // return map.containsKey(setting); // } // // /** // * Returns an Iterator over all keys contained in this configuration. // * // * @return an Iterator over all keys contained in this configuration // */ // public static Iterator<String> getKeyIterator() { // return map.keySet().iterator(); // } // } // Path: modules/swing/src/main/java/de/tobifleig/lxc/plaf/swing/OptionsDialog.java import de.tobifleig.lxc.Configuration; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.io.File; import javax.swing.*; /* * Copyright 2009, 2010, 2011, 2012, 2013, 2014 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.swing; /** * Options-Dialog. * Created by the NetBeans-GuiBuilder. * * @author Tobias Fleig <tobifleig googlemail com> */ public class OptionsDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; /** * Creates new form LXCOptionsDialog * * @param parent * @param modal */ public OptionsDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { setVisible(false); } }); // close help window on ESC getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); getRootPane().getActionMap().put("cancel", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); } }); } /** * Displays this dialog and block until it is closed. */ public void showAndWait() { // Read settings:
if (!Configuration.containsKey("defaulttarget") || "unset".equals(Configuration.getStringSetting("defaulttarget"))) {
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // }
import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Lists all files and running transfers. */ public class ListCommand extends BackendCommand { public ListCommand() {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Lists all files and running transfers. */ public class ListCommand extends BackendCommand { public ListCommand() {
super(BackendCommandType.LIST);
tfg13/LanXchange
modules/swing/src/main/java/de/tobifleig/lxc/plaf/swing/OverallProgressManager.java
// Path: modules/core/src/main/java/de/tobifleig/lxc/data/LXCJob.java // public class LXCJob { // // /** // * If this job represents a running upload (true) or download (false). // */ // private boolean isSeeder = false; // /** // * The remote LXCInstance. // */ // private final LXCInstance remote; // /** // * The corresponding Transceiver. // */ // private final Transceiver trans; // // /** // * Creates a new LXCJob with the given parameters. // * // * @param trans the running transceiver that transfers the data // * @param remote the connected remote // */ // public LXCJob(Transceiver trans, LXCInstance remote) { // this.trans = trans; // this.remote = remote; // isSeeder = trans instanceof Seeder; // } // // /** // * Returns true, if this job represents a running upload. // * // * @return true if upload, false if download // */ // public boolean isIsSeeder() { // return isSeeder; // } // // /** // * Returns the remote LXCInstance. // * // * @return the remote LXCInstance // */ // public LXCInstance getRemote() { // return remote; // } // // /** // * Returns the running Transceiver. // * // * @return the Transceiver // */ // public Transceiver getTrans() { // return trans; // } // // /** // * Immediately aborts the transfer. // */ // public void abortTransfer() { // trans.abort(); // } // } // // Path: modules/core/src/main/java/de/tobifleig/lxc/plaf/ProgressIndicator.java // public interface ProgressIndicator { // /** // * This method is called by running transfers to indicate progess. // * This method can be called very frequently. // * // * @param percentage progress in percent // */ // public void update(int percentage); // // }
import de.tobifleig.lxc.data.LXCJob; import de.tobifleig.lxc.plaf.ProgressIndicator;
/* * Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.swing; /** * Replaces the ProgressIndicator of managed Jobs, * computes a global average (arithmetic mean) of all managed jobs * and offers notifications for changes in both global and * single (per-job) percentages. * <p> * Thread-safe (concurrent percentage updates), fast, all operations run in constant time. */ public abstract class OverallProgressManager { private float overallProgress = 0; private int numberOfTrackedProgresses = 0; private int lastOverallProgressInt = 0;
// Path: modules/core/src/main/java/de/tobifleig/lxc/data/LXCJob.java // public class LXCJob { // // /** // * If this job represents a running upload (true) or download (false). // */ // private boolean isSeeder = false; // /** // * The remote LXCInstance. // */ // private final LXCInstance remote; // /** // * The corresponding Transceiver. // */ // private final Transceiver trans; // // /** // * Creates a new LXCJob with the given parameters. // * // * @param trans the running transceiver that transfers the data // * @param remote the connected remote // */ // public LXCJob(Transceiver trans, LXCInstance remote) { // this.trans = trans; // this.remote = remote; // isSeeder = trans instanceof Seeder; // } // // /** // * Returns true, if this job represents a running upload. // * // * @return true if upload, false if download // */ // public boolean isIsSeeder() { // return isSeeder; // } // // /** // * Returns the remote LXCInstance. // * // * @return the remote LXCInstance // */ // public LXCInstance getRemote() { // return remote; // } // // /** // * Returns the running Transceiver. // * // * @return the Transceiver // */ // public Transceiver getTrans() { // return trans; // } // // /** // * Immediately aborts the transfer. // */ // public void abortTransfer() { // trans.abort(); // } // } // // Path: modules/core/src/main/java/de/tobifleig/lxc/plaf/ProgressIndicator.java // public interface ProgressIndicator { // /** // * This method is called by running transfers to indicate progess. // * This method can be called very frequently. // * // * @param percentage progress in percent // */ // public void update(int percentage); // // } // Path: modules/swing/src/main/java/de/tobifleig/lxc/plaf/swing/OverallProgressManager.java import de.tobifleig.lxc.data.LXCJob; import de.tobifleig.lxc.plaf.ProgressIndicator; /* * Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.swing; /** * Replaces the ProgressIndicator of managed Jobs, * computes a global average (arithmetic mean) of all managed jobs * and offers notifications for changes in both global and * single (per-job) percentages. * <p> * Thread-safe (concurrent percentage updates), fast, all operations run in constant time. */ public abstract class OverallProgressManager { private float overallProgress = 0; private int numberOfTrackedProgresses = 0; private int lastOverallProgressInt = 0;
public void handleNewJob(final LXCJob job) {
tfg13/LanXchange
modules/swing/src/main/java/de/tobifleig/lxc/plaf/swing/OverallProgressManager.java
// Path: modules/core/src/main/java/de/tobifleig/lxc/data/LXCJob.java // public class LXCJob { // // /** // * If this job represents a running upload (true) or download (false). // */ // private boolean isSeeder = false; // /** // * The remote LXCInstance. // */ // private final LXCInstance remote; // /** // * The corresponding Transceiver. // */ // private final Transceiver trans; // // /** // * Creates a new LXCJob with the given parameters. // * // * @param trans the running transceiver that transfers the data // * @param remote the connected remote // */ // public LXCJob(Transceiver trans, LXCInstance remote) { // this.trans = trans; // this.remote = remote; // isSeeder = trans instanceof Seeder; // } // // /** // * Returns true, if this job represents a running upload. // * // * @return true if upload, false if download // */ // public boolean isIsSeeder() { // return isSeeder; // } // // /** // * Returns the remote LXCInstance. // * // * @return the remote LXCInstance // */ // public LXCInstance getRemote() { // return remote; // } // // /** // * Returns the running Transceiver. // * // * @return the Transceiver // */ // public Transceiver getTrans() { // return trans; // } // // /** // * Immediately aborts the transfer. // */ // public void abortTransfer() { // trans.abort(); // } // } // // Path: modules/core/src/main/java/de/tobifleig/lxc/plaf/ProgressIndicator.java // public interface ProgressIndicator { // /** // * This method is called by running transfers to indicate progess. // * This method can be called very frequently. // * // * @param percentage progress in percent // */ // public void update(int percentage); // // }
import de.tobifleig.lxc.data.LXCJob; import de.tobifleig.lxc.plaf.ProgressIndicator;
/* * Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.swing; /** * Replaces the ProgressIndicator of managed Jobs, * computes a global average (arithmetic mean) of all managed jobs * and offers notifications for changes in both global and * single (per-job) percentages. * <p> * Thread-safe (concurrent percentage updates), fast, all operations run in constant time. */ public abstract class OverallProgressManager { private float overallProgress = 0; private int numberOfTrackedProgresses = 0; private int lastOverallProgressInt = 0; public void handleNewJob(final LXCJob job) {
// Path: modules/core/src/main/java/de/tobifleig/lxc/data/LXCJob.java // public class LXCJob { // // /** // * If this job represents a running upload (true) or download (false). // */ // private boolean isSeeder = false; // /** // * The remote LXCInstance. // */ // private final LXCInstance remote; // /** // * The corresponding Transceiver. // */ // private final Transceiver trans; // // /** // * Creates a new LXCJob with the given parameters. // * // * @param trans the running transceiver that transfers the data // * @param remote the connected remote // */ // public LXCJob(Transceiver trans, LXCInstance remote) { // this.trans = trans; // this.remote = remote; // isSeeder = trans instanceof Seeder; // } // // /** // * Returns true, if this job represents a running upload. // * // * @return true if upload, false if download // */ // public boolean isIsSeeder() { // return isSeeder; // } // // /** // * Returns the remote LXCInstance. // * // * @return the remote LXCInstance // */ // public LXCInstance getRemote() { // return remote; // } // // /** // * Returns the running Transceiver. // * // * @return the Transceiver // */ // public Transceiver getTrans() { // return trans; // } // // /** // * Immediately aborts the transfer. // */ // public void abortTransfer() { // trans.abort(); // } // } // // Path: modules/core/src/main/java/de/tobifleig/lxc/plaf/ProgressIndicator.java // public interface ProgressIndicator { // /** // * This method is called by running transfers to indicate progess. // * This method can be called very frequently. // * // * @param percentage progress in percent // */ // public void update(int percentage); // // } // Path: modules/swing/src/main/java/de/tobifleig/lxc/plaf/swing/OverallProgressManager.java import de.tobifleig.lxc.data.LXCJob; import de.tobifleig.lxc.plaf.ProgressIndicator; /* * Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.swing; /** * Replaces the ProgressIndicator of managed Jobs, * computes a global average (arithmetic mean) of all managed jobs * and offers notifications for changes in both global and * single (per-job) percentages. * <p> * Thread-safe (concurrent percentage updates), fast, all operations run in constant time. */ public abstract class OverallProgressManager { private float overallProgress = 0; private int numberOfTrackedProgresses = 0; private int lastOverallProgressInt = 0; public void handleNewJob(final LXCJob job) {
job.getTrans().setProgressIndicator(new ProgressIndicator() {
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Queries if the backend is running without starting it automatically. */ public class StatusCommand extends BackendCommand { public StatusCommand() {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Queries if the backend is running without starting it automatically. */ public class StatusCommand extends BackendCommand { public StatusCommand() {
super(BackendCommandType.NOP);
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Queries if the backend is running without starting it automatically. */ public class StatusCommand extends BackendCommand { public StatusCommand() { super(BackendCommandType.NOP); } @Override public boolean startBackendOnSendError() { return false; } @Override public void onFrontendResult(boolean deliveredToBackend) { if (deliveredToBackend) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Queries if the backend is running without starting it automatically. */ public class StatusCommand extends BackendCommand { public StatusCommand() { super(BackendCommandType.NOP); } @Override public boolean startBackendOnSendError() { return false; } @Override public void onFrontendResult(boolean deliveredToBackend) { if (deliveredToBackend) {
CLITools.out.println("LanXchange is running in the background.");
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // }
import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Used by the frontend to find out if the backend is running. */ public class StartCommand extends BackendCommand { /** * Whether the backend was started for this command. * (If not, the backend prints a "already running" message. */ private final boolean backendLaunched; public StartCommand(boolean backendLaunched) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Used by the frontend to find out if the backend is running. */ public class StartCommand extends BackendCommand { /** * Whether the backend was started for this command. * (If not, the backend prints a "already running" message. */ private final boolean backendLaunched; public StartCommand(boolean backendLaunched) {
super(BackendCommandType.START);
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Command to stop the backend and shut down LanXchange. */ public class StopCommand extends BackendCommand { private final boolean force; public StopCommand(boolean force) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Command to stop the backend and shut down LanXchange. */ public class StopCommand extends BackendCommand { private final boolean force; public StopCommand(boolean force) {
super(BackendCommandType.STOP);
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Command to stop the backend and shut down LanXchange. */ public class StopCommand extends BackendCommand { private final boolean force; public StopCommand(boolean force) { super(BackendCommandType.STOP); this.force = force; } public boolean isForce() { return force; } @Override public boolean startBackendOnSendError() { return false; } @Override public void onFrontendResult(boolean deliveredToBackend) { if (!deliveredToBackend) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommand.java // public abstract class BackendCommand implements Serializable { // // private final BackendCommandType type; // // private final List<String> data; // // public BackendCommand(BackendCommandType type) { // this.type = type; // data = new ArrayList<>(); // } // // public void addData(String d) { // data.add(d); // } // // public BackendCommandType getType() { // return type; // } // // /** // * Tells the frontend if an attempt should be made to start the backend if sending the command initially fails. // * With this, commands like stop can avoid re-starting already stopped backends. // * @return true, if backend should be started // */ // public boolean startBackendOnSendError() { // return true; // } // // /** // * Called by the frontend after the attempt to deliver the command to the backend. // * Some commands may want to act on the result. // * Default action is nop. // * @param deliveredToBackend true if command was successfully delivered to backend, false otherwise // */ // public void onFrontendResult(boolean deliveredToBackend) {} // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/BackendCommandType.java // public enum BackendCommandType { // // START, // pseudo-command does nothing, but is used by the frontend to test whether the backend is already running // STOP, // stops LanXchange // LIST, // lists files and transfers // GET, // downloads a file // SHARE, // offers a file // ABORT, // aborts a transfer // VERSION, // displays version info // NOP, // used for frontend-handled commands like STATUS // // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java import de.tobifleig.lxc.plaf.cli.BackendCommand; import de.tobifleig.lxc.plaf.cli.BackendCommandType; import de.tobifleig.lxc.plaf.cli.ui.CLITools; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli.cmds; /** * Command to stop the backend and shut down LanXchange. */ public class StopCommand extends BackendCommand { private final boolean force; public StopCommand(boolean force) { super(BackendCommandType.STOP); this.force = force; } public boolean isForce() { return force; } @Override public boolean startBackendOnSendError() { return false; } @Override public void onFrontendResult(boolean deliveredToBackend) { if (!deliveredToBackend) {
CLITools.out.println("Not running.");
tfg13/LanXchange
modules/android/src/main/java/de/tobifleig/lxc/plaf/android/activity/KeepServiceRunningActivity.java
// Path: modules/android/src/main/java/de/tobifleig/lxc/plaf/android/service/AndroidSingleton.java // public class AndroidSingleton { // // private static boolean running = false; // private static MainActivity activity; // private static AndroidGuiListener guiListener; // private static GuiInterfaceBridge genericBridge = new GuiInterfaceBridge() { // // @Override // public void update() { // // do nothing // } // // @Override // public void notifyFileChange(int fileOrigin, int operation, int firstIndex, int numberOfFiles, List<LXCFile> affectedFiles) { // // do nothing // } // // @Override // public void notifyJobChange(int operation, LXCFile file, int index) { // // do nothing // } // // @Override // public boolean confirmCloseWithTransfersRunning() { // // no gui = no one to ask = no not close // return false; // } // // @Override // public void showError(Context context, String error) { // // no gui = do nothing // // maybe consider creating a notification in the future // NotificationCompat.Builder builder = new NotificationCompat.Builder(context); // builder.setSmallIcon(R.drawable.ic_lxc_running); // builder.setContentTitle(context.getResources().getString(R.string.notification_error_title)); // builder.setContentText(context.getResources().getString(R.string.notification_error_text)); // builder.setAutoCancel(true); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // builder.setCategory(Notification.CATEGORY_ERROR); // } // builder.setPriority(Notification.PRIORITY_HIGH); // builder.setTicker(context.getResources().getString(R.string.notification_error_title)); // // Intent showErrorIntent = new Intent(); // showErrorIntent.setAction(MainActivity.ACTION_SHOW_ERROR); // showErrorIntent.putExtra(Intent.EXTRA_TEXT, error); // showErrorIntent.setClass(context.getApplicationContext(), MainActivity.class); // explicit intent! // // builder.setContentIntent(PendingIntent.getActivity(context, 0, showErrorIntent, 0)); // // ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(2, builder.build()); // } // }; // private static GuiInterfaceBridge currentBridge = genericBridge; // private static List<VirtualFile> quickShare; // // private AndroidSingleton() { // } // // /** // * Call this when the main activity is created. Handles initialization in a // * way that it is only run if needed. // */ // public static void onCreateMainActivity(MainActivity activity, GuiInterfaceBridge bridge, List<VirtualFile> quickShare) { // if (quickShare != null) { // AndroidSingleton.quickShare = quickShare; // } // AndroidSingleton.activity = activity; // AndroidSingleton.currentBridge = bridge; // if (!running) { // running = true; // activity.startService(new Intent(activity, de.tobifleig.lxc.plaf.android.service.LXCService.class)); // } // if (guiListener != null) { // activity.setGuiListener(guiListener); // sendQuickShare(); // } // } // // /** // * Call this when the main activity becomes visible (again). // */ // public static void onMainActivityVisible(int depth) { // if (guiListener != null) { // guiListener.guiVisible(depth); // } // } // // /** // * Call this when the main activity is being destroyed. If the main activity // * is not re-created soon, the service will be stopped, if there are no // * running jobs left. // */ // public static void onMainActivityHidden(int depth) { // currentBridge = genericBridge; // if (guiListener != null) { // guiListener.guiHidden(depth); // } // AndroidSingleton.activity = null; // } // // /** // * Call this to stop the LXC service. // * // */ // public static void onRealDestroy() { // if (running) { // running = false; // guiListener = null; // } // } // // /** // * Called by the main activity if a share-intent was received, // * but the service is not ready yet (no guilistener available). // * Effectively a setter for quickShare // * @param quickShare the files to share once the service becomes available // */ // public static void onEarlyShareIntent(List<VirtualFile> quickShare) { // AndroidSingleton.quickShare = quickShare; // } // // /** // * Called by the Service on self-stop. // */ // public static void serviceStopping() { // running = false; // } // // /** // * Called by the Service when LXC is up and running. // */ // public static void serviceReady(AndroidGuiListener guiListener, int errorCode) { // AndroidSingleton.guiListener = guiListener; // if (activity != null) { // activity.setGuiListener(guiListener); // sendQuickShare(); // if (errorCode != 0) { // activity.onErrorCode(errorCode); // } // } // } // // public static GuiInterfaceBridge getInterfaceBridge() { // return currentBridge; // } // // private static void sendQuickShare() { // if (activity != null && quickShare != null) { // activity.quickShare(quickShare); // quickShare = null; // } // } // }
import de.tobifleig.lxc.plaf.android.service.AndroidSingleton; import android.app.Activity; import android.support.v7.app.AppCompatActivity;
/* * Copyright 2009, 2010, 2011, 2012, 2013, 2014 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.android.activity; public class KeepServiceRunningActivity extends AppCompatActivity { @Override public void onPause() { super.onPause();
// Path: modules/android/src/main/java/de/tobifleig/lxc/plaf/android/service/AndroidSingleton.java // public class AndroidSingleton { // // private static boolean running = false; // private static MainActivity activity; // private static AndroidGuiListener guiListener; // private static GuiInterfaceBridge genericBridge = new GuiInterfaceBridge() { // // @Override // public void update() { // // do nothing // } // // @Override // public void notifyFileChange(int fileOrigin, int operation, int firstIndex, int numberOfFiles, List<LXCFile> affectedFiles) { // // do nothing // } // // @Override // public void notifyJobChange(int operation, LXCFile file, int index) { // // do nothing // } // // @Override // public boolean confirmCloseWithTransfersRunning() { // // no gui = no one to ask = no not close // return false; // } // // @Override // public void showError(Context context, String error) { // // no gui = do nothing // // maybe consider creating a notification in the future // NotificationCompat.Builder builder = new NotificationCompat.Builder(context); // builder.setSmallIcon(R.drawable.ic_lxc_running); // builder.setContentTitle(context.getResources().getString(R.string.notification_error_title)); // builder.setContentText(context.getResources().getString(R.string.notification_error_text)); // builder.setAutoCancel(true); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // builder.setCategory(Notification.CATEGORY_ERROR); // } // builder.setPriority(Notification.PRIORITY_HIGH); // builder.setTicker(context.getResources().getString(R.string.notification_error_title)); // // Intent showErrorIntent = new Intent(); // showErrorIntent.setAction(MainActivity.ACTION_SHOW_ERROR); // showErrorIntent.putExtra(Intent.EXTRA_TEXT, error); // showErrorIntent.setClass(context.getApplicationContext(), MainActivity.class); // explicit intent! // // builder.setContentIntent(PendingIntent.getActivity(context, 0, showErrorIntent, 0)); // // ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(2, builder.build()); // } // }; // private static GuiInterfaceBridge currentBridge = genericBridge; // private static List<VirtualFile> quickShare; // // private AndroidSingleton() { // } // // /** // * Call this when the main activity is created. Handles initialization in a // * way that it is only run if needed. // */ // public static void onCreateMainActivity(MainActivity activity, GuiInterfaceBridge bridge, List<VirtualFile> quickShare) { // if (quickShare != null) { // AndroidSingleton.quickShare = quickShare; // } // AndroidSingleton.activity = activity; // AndroidSingleton.currentBridge = bridge; // if (!running) { // running = true; // activity.startService(new Intent(activity, de.tobifleig.lxc.plaf.android.service.LXCService.class)); // } // if (guiListener != null) { // activity.setGuiListener(guiListener); // sendQuickShare(); // } // } // // /** // * Call this when the main activity becomes visible (again). // */ // public static void onMainActivityVisible(int depth) { // if (guiListener != null) { // guiListener.guiVisible(depth); // } // } // // /** // * Call this when the main activity is being destroyed. If the main activity // * is not re-created soon, the service will be stopped, if there are no // * running jobs left. // */ // public static void onMainActivityHidden(int depth) { // currentBridge = genericBridge; // if (guiListener != null) { // guiListener.guiHidden(depth); // } // AndroidSingleton.activity = null; // } // // /** // * Call this to stop the LXC service. // * // */ // public static void onRealDestroy() { // if (running) { // running = false; // guiListener = null; // } // } // // /** // * Called by the main activity if a share-intent was received, // * but the service is not ready yet (no guilistener available). // * Effectively a setter for quickShare // * @param quickShare the files to share once the service becomes available // */ // public static void onEarlyShareIntent(List<VirtualFile> quickShare) { // AndroidSingleton.quickShare = quickShare; // } // // /** // * Called by the Service on self-stop. // */ // public static void serviceStopping() { // running = false; // } // // /** // * Called by the Service when LXC is up and running. // */ // public static void serviceReady(AndroidGuiListener guiListener, int errorCode) { // AndroidSingleton.guiListener = guiListener; // if (activity != null) { // activity.setGuiListener(guiListener); // sendQuickShare(); // if (errorCode != 0) { // activity.onErrorCode(errorCode); // } // } // } // // public static GuiInterfaceBridge getInterfaceBridge() { // return currentBridge; // } // // private static void sendQuickShare() { // if (activity != null && quickShare != null) { // activity.quickShare(quickShare); // quickShare = null; // } // } // } // Path: modules/android/src/main/java/de/tobifleig/lxc/plaf/android/activity/KeepServiceRunningActivity.java import de.tobifleig.lxc.plaf.android.service.AndroidSingleton; import android.app.Activity; import android.support.v7.app.AppCompatActivity; /* * Copyright 2009, 2010, 2011, 2012, 2013, 2014 Tobias Fleig (tobifleig gmail com) * * All rights reserved. * * This file is part of LanXchange. * * LanXchange is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LanXchange is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LanXchange. If not, see <http://www.gnu.org/licenses/>. */ package de.tobifleig.lxc.plaf.android.activity; public class KeepServiceRunningActivity extends AppCompatActivity { @Override public void onPause() { super.onPause();
AndroidSingleton.onMainActivityHidden(1);
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli; /** * The frontend, mostly submits commands to the backend. */ public class CLIFrontend { private static int EXITCODE_REQUEST_BACKEND_START = 7; private static int RECONNECT_DELAY_MS_INITIAL = 100; private static int RECONNECT_DELAY_MS_MAX = 6400; public static void main(String[] args) { // this should only be called by lxcc (the cli launch script) if (args.length == 0 || !args[0].equals("-cli")) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.cli; /** * The frontend, mostly submits commands to the backend. */ public class CLIFrontend { private static int EXITCODE_REQUEST_BACKEND_START = 7; private static int RECONNECT_DELAY_MS_INITIAL = 100; private static int RECONNECT_DELAY_MS_MAX = 6400; public static void main(String[] args) { // this should only be called by lxcc (the cli launch script) if (args.length == 0 || !args[0].equals("-cli")) {
CLITools.out.println("Please use the script \"lxcc\" to interact with the CLI version of LanXchange. " +
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket;
int reconnectDelay = RECONNECT_DELAY_MS_INITIAL; do { try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), CLIBackend.LANXCHANGE_DAEMON_PORT)) { ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); output.writeObject(command); output.flush(); CLITools.out.println("DEBUG: Command submission to backend OK"); return true; } catch (ConnectException e) { // backend might be in startup, retry with exponential backoff CLITools.out.println("DEBUG: Submisson failed, retry in " + reconnectDelay); try { Thread.sleep(reconnectDelay); } catch (InterruptedException e1) { // ignore } reconnectDelay *= 2; } catch (IOException e) { // unexpected // TODO! return false; } } while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; int reconnectDelay = RECONNECT_DELAY_MS_INITIAL; do { try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), CLIBackend.LANXCHANGE_DAEMON_PORT)) { ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); output.writeObject(command); output.flush(); CLITools.out.println("DEBUG: Command submission to backend OK"); return true; } catch (ConnectException e) { // backend might be in startup, retry with exponential backoff CLITools.out.println("DEBUG: Submisson failed, retry in " + reconnectDelay); try { Thread.sleep(reconnectDelay); } catch (InterruptedException e1) { // ignore } reconnectDelay *= 2; } catch (IOException e) { // unexpected // TODO! return false; } } while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) {
return new ListCommand();
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket;
return true; } catch (ConnectException e) { // backend might be in startup, retry with exponential backoff CLITools.out.println("DEBUG: Submisson failed, retry in " + reconnectDelay); try { Thread.sleep(reconnectDelay); } catch (InterruptedException e1) { // ignore } reconnectDelay *= 2; } catch (IOException e) { // unexpected // TODO! return false; } } while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new ListCommand(); } return null; } private static BackendCommand parseStart(String[] data, boolean alreadyStarted) { if (verifyCommandLength(data, 0, 0)) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; return true; } catch (ConnectException e) { // backend might be in startup, retry with exponential backoff CLITools.out.println("DEBUG: Submisson failed, retry in " + reconnectDelay); try { Thread.sleep(reconnectDelay); } catch (InterruptedException e1) { // ignore } reconnectDelay *= 2; } catch (IOException e) { // unexpected // TODO! return false; } } while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new ListCommand(); } return null; } private static BackendCommand parseStart(String[] data, boolean alreadyStarted) { if (verifyCommandLength(data, 0, 0)) {
return new StartCommand(alreadyStarted);
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket;
// ignore } reconnectDelay *= 2; } catch (IOException e) { // unexpected // TODO! return false; } } while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new ListCommand(); } return null; } private static BackendCommand parseStart(String[] data, boolean alreadyStarted) { if (verifyCommandLength(data, 0, 0)) { return new StartCommand(alreadyStarted); } return null; } private static BackendCommand parseStatus(String[] data) { if (verifyCommandLength(data, 0, 0)) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; // ignore } reconnectDelay *= 2; } catch (IOException e) { // unexpected // TODO! return false; } } while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new ListCommand(); } return null; } private static BackendCommand parseStart(String[] data, boolean alreadyStarted) { if (verifyCommandLength(data, 0, 0)) { return new StartCommand(alreadyStarted); } return null; } private static BackendCommand parseStatus(String[] data) { if (verifyCommandLength(data, 0, 0)) {
return new StatusCommand();
tfg13/LanXchange
modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // }
import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket;
} while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new ListCommand(); } return null; } private static BackendCommand parseStart(String[] data, boolean alreadyStarted) { if (verifyCommandLength(data, 0, 0)) { return new StartCommand(alreadyStarted); } return null; } private static BackendCommand parseStatus(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new StatusCommand(); } return null; } private static BackendCommand parseStop(String[] data) { if (verifyCommandLength(data, 0, 1)) { if (data.length == 1) {
// Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/ListCommand.java // public class ListCommand extends BackendCommand { // // public ListCommand() { // super(BackendCommandType.LIST); // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StartCommand.java // public class StartCommand extends BackendCommand { // // /** // * Whether the backend was started for this command. // * (If not, the backend prints a "already running" message. // */ // private final boolean backendLaunched; // // public StartCommand(boolean backendLaunched) { // super(BackendCommandType.START); // this.backendLaunched = backendLaunched; // } // // public boolean isBackendLaunched() { // return backendLaunched; // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StatusCommand.java // public class StatusCommand extends BackendCommand { // // public StatusCommand() { // super(BackendCommandType.NOP); // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (deliveredToBackend) { // CLITools.out.println("LanXchange is running in the background."); // } else { // CLITools.out.println("LanXchange backend is NOT running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/cmds/StopCommand.java // public class StopCommand extends BackendCommand { // // private final boolean force; // // public StopCommand(boolean force) { // super(BackendCommandType.STOP); // this.force = force; // } // // public boolean isForce() { // return force; // } // // @Override // public boolean startBackendOnSendError() { // return false; // } // // @Override // public void onFrontendResult(boolean deliveredToBackend) { // if (!deliveredToBackend) { // CLITools.out.println("Not running."); // } // } // } // // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/ui/CLITools.java // public final class CLITools { // // /** // * This is the original System.out out. // * LanXchange may change System.out for logging purposes, but the cli gui must still be able to print to stdout. // */ // public static final PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out)); // } // Path: modules/cli/src/main/java/de/tobifleig/lxc/plaf/cli/CLIFrontend.java import de.tobifleig.lxc.plaf.cli.cmds.ListCommand; import de.tobifleig.lxc.plaf.cli.cmds.StartCommand; import de.tobifleig.lxc.plaf.cli.cmds.StatusCommand; import de.tobifleig.lxc.plaf.cli.cmds.StopCommand; import de.tobifleig.lxc.plaf.cli.ui.CLITools; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; } while (awaitBackendStartup && reconnectDelay <= RECONNECT_DELAY_MS_MAX); // TODO unreachable even after waiting quite a while! CLITools.out.println("DEBUG: Submission failed, retry time limit exceeded - giving up."); return false; } private static BackendCommand parseList(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new ListCommand(); } return null; } private static BackendCommand parseStart(String[] data, boolean alreadyStarted) { if (verifyCommandLength(data, 0, 0)) { return new StartCommand(alreadyStarted); } return null; } private static BackendCommand parseStatus(String[] data) { if (verifyCommandLength(data, 0, 0)) { return new StatusCommand(); } return null; } private static BackendCommand parseStop(String[] data) { if (verifyCommandLength(data, 0, 1)) { if (data.length == 1) {
return new StopCommand(false);
tfg13/LanXchange
modules/android/src/main/java/de/tobifleig/lxc/plaf/android/ui/DownloadPathPreference.java
// Path: modules/android/src/main/java/de/tobifleig/lxc/plaf/android/activity/SettingsActivity.java // public class SettingsActivity extends KeepServiceRunningActivity implements CancelablePermissionPromptActivity { // // private DownloadPathPreference permissionDownloadPathPref; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // load layout // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // display the fragment as the main content. // getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); // } // // @Override // public void cancelPermissionPromptAction() { // permissionDownloadPathPref = null; // Snackbar.make(findViewById(android.R.id.content), R.string.snackbar_action_cancelled_permission_storage_missing, Snackbar.LENGTH_LONG).show(); // } // // @Override // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // if (requestCode == MainActivity.RETURNCODE_PERMISSION_PROMPT_STORAGE) { // if (grantResults.length == 0) { // // cancelled, try again // PermissionTools.verifyStoragePermission(this, this); // return; // } // if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // // continue what the user tried to do when the permission dialog fired // Thread t = new Thread(new Runnable() { // @Override // public void run() { // if (permissionDownloadPathPref != null) { // permissionDownloadPathPref.prompt(); // permissionDownloadPathPref = null; // } // } // }); // t.setName("lxc_helper_useraction"); // t.setDaemon(true); // t.start(); // } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) { // cancelPermissionPromptAction(); // } // } // } // // public boolean verifyStoragePermission(DownloadPathPreference pref) { // permissionDownloadPathPref = pref; // boolean result = PermissionTools.verifyStoragePermission(this, this); // if (result) { // // delete action cache on success // permissionDownloadPathPref = null; // } // return result; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.os.Environment; import android.os.Parcel; import android.os.Parcelable; import android.preference.Preference; import android.support.annotation.NonNull; import android.util.AttributeSet; import de.tobifleig.lxc.plaf.android.activity.SettingsActivity; import net.rdrei.android.dirchooser.DirectoryChooserConfig; import net.rdrei.android.dirchooser.DirectoryChooserFragment;
/* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.android.ui; /** * Custom preference to select the download target directory. * Currently, this only supports the internal storage (no external sd cards). */ public class DownloadPathPreference extends Preference { private DirectoryChooserFragment dialog; private String downloadPath; public DownloadPathPreference(Context context, AttributeSet attrs) { super(context, attrs); } public void prompt() { // super ugly cast
// Path: modules/android/src/main/java/de/tobifleig/lxc/plaf/android/activity/SettingsActivity.java // public class SettingsActivity extends KeepServiceRunningActivity implements CancelablePermissionPromptActivity { // // private DownloadPathPreference permissionDownloadPathPref; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // load layout // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // display the fragment as the main content. // getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); // } // // @Override // public void cancelPermissionPromptAction() { // permissionDownloadPathPref = null; // Snackbar.make(findViewById(android.R.id.content), R.string.snackbar_action_cancelled_permission_storage_missing, Snackbar.LENGTH_LONG).show(); // } // // @Override // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // if (requestCode == MainActivity.RETURNCODE_PERMISSION_PROMPT_STORAGE) { // if (grantResults.length == 0) { // // cancelled, try again // PermissionTools.verifyStoragePermission(this, this); // return; // } // if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // // continue what the user tried to do when the permission dialog fired // Thread t = new Thread(new Runnable() { // @Override // public void run() { // if (permissionDownloadPathPref != null) { // permissionDownloadPathPref.prompt(); // permissionDownloadPathPref = null; // } // } // }); // t.setName("lxc_helper_useraction"); // t.setDaemon(true); // t.start(); // } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) { // cancelPermissionPromptAction(); // } // } // } // // public boolean verifyStoragePermission(DownloadPathPreference pref) { // permissionDownloadPathPref = pref; // boolean result = PermissionTools.verifyStoragePermission(this, this); // if (result) { // // delete action cache on success // permissionDownloadPathPref = null; // } // return result; // } // } // Path: modules/android/src/main/java/de/tobifleig/lxc/plaf/android/ui/DownloadPathPreference.java import android.content.Context; import android.content.res.TypedArray; import android.os.Environment; import android.os.Parcel; import android.os.Parcelable; import android.preference.Preference; import android.support.annotation.NonNull; import android.util.AttributeSet; import de.tobifleig.lxc.plaf.android.activity.SettingsActivity; import net.rdrei.android.dirchooser.DirectoryChooserConfig; import net.rdrei.android.dirchooser.DirectoryChooserFragment; /* * Copyright 2017 Tobias Fleig (tobifleig gmail com) * All rights reserved. * * Usage of this source code is governed by the GNU GENERAL PUBLIC LICENSE version 3 or (at your option) any later version. * For the full license text see the file COPYING or https://github.com/tfg13/LanXchange/blob/master/COPYING */ package de.tobifleig.lxc.plaf.android.ui; /** * Custom preference to select the download target directory. * Currently, this only supports the internal storage (no external sd cards). */ public class DownloadPathPreference extends Preference { private DirectoryChooserFragment dialog; private String downloadPath; public DownloadPathPreference(Context context, AttributeSet attrs) { super(context, attrs); } public void prompt() { // super ugly cast
SettingsActivity myActivity = (SettingsActivity) getContext();
tfg13/LanXchange
modules/core/src/main/java/de/tobifleig/lxc/log/LXCLogBackend.java
// Path: modules/core/src/main/java/de/tobifleig/lxc/util/ByteLimitOutputStream.java // public class ByteLimitOutputStream extends FilterOutputStream { // // private int bytesLeft; // private Runnable limitReachedAction; // // public ByteLimitOutputStream(OutputStream out, int byteLimit, Runnable limitReachedAction) { // super(out); // this.bytesLeft = byteLimit; // this.limitReachedAction = limitReachedAction; // } // // @Override // public void write(int b) throws IOException { // if (bytesLeft <= 0) { // limitReachedAction.run(); // return; // } // super.write(b); // bytesLeft -= 1; // } // // @Override // public void write(byte[] b, int off, int len) throws IOException { // if (bytesLeft < len) { // bytesLeft = 0; // prevent retry with smaller buffer // limitReachedAction.run(); // return; // } // int leftPreSuper = bytesLeft; // super.write(b, off, len); // // subclass may call write(int) multiple times, avoid subtracting the limit multiple times // if (bytesLeft != leftPreSuper - len) { // bytesLeft -= len; // } // } // }
import de.tobifleig.lxc.util.ByteLimitOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream;
File rotateVictim = new File(targetDir,"lxc_oldlog" + (i + 1) + ".log"); if (rotateDown.exists()) { if (rotateVictim.exists()) { rotateVictim.delete(); } rotateDown.renameTo(rotateVictim); } } File previous = new File(targetDir,"lxc_oldlog1.log"); if (previous.exists()) { previous.delete(); } current.renameTo(previous); } if (!current.exists()) { try { current.createNewFile(); } catch (IOException ex) { System.err.println("Cannot write to logfile \"lxc.log\""); } } if (!current.canWrite()) { System.err.println("Cannot write to logfile \"lxc.log\""); return null; } return current; } private static PrintStream createSizeLimitPrinter(File logFile) throws FileNotFoundException { final FileOutputStream fileOut = new FileOutputStream(logFile);
// Path: modules/core/src/main/java/de/tobifleig/lxc/util/ByteLimitOutputStream.java // public class ByteLimitOutputStream extends FilterOutputStream { // // private int bytesLeft; // private Runnable limitReachedAction; // // public ByteLimitOutputStream(OutputStream out, int byteLimit, Runnable limitReachedAction) { // super(out); // this.bytesLeft = byteLimit; // this.limitReachedAction = limitReachedAction; // } // // @Override // public void write(int b) throws IOException { // if (bytesLeft <= 0) { // limitReachedAction.run(); // return; // } // super.write(b); // bytesLeft -= 1; // } // // @Override // public void write(byte[] b, int off, int len) throws IOException { // if (bytesLeft < len) { // bytesLeft = 0; // prevent retry with smaller buffer // limitReachedAction.run(); // return; // } // int leftPreSuper = bytesLeft; // super.write(b, off, len); // // subclass may call write(int) multiple times, avoid subtracting the limit multiple times // if (bytesLeft != leftPreSuper - len) { // bytesLeft -= len; // } // } // } // Path: modules/core/src/main/java/de/tobifleig/lxc/log/LXCLogBackend.java import de.tobifleig.lxc.util.ByteLimitOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; File rotateVictim = new File(targetDir,"lxc_oldlog" + (i + 1) + ".log"); if (rotateDown.exists()) { if (rotateVictim.exists()) { rotateVictim.delete(); } rotateDown.renameTo(rotateVictim); } } File previous = new File(targetDir,"lxc_oldlog1.log"); if (previous.exists()) { previous.delete(); } current.renameTo(previous); } if (!current.exists()) { try { current.createNewFile(); } catch (IOException ex) { System.err.println("Cannot write to logfile \"lxc.log\""); } } if (!current.canWrite()) { System.err.println("Cannot write to logfile \"lxc.log\""); return null; } return current; } private static PrintStream createSizeLimitPrinter(File logFile) throws FileNotFoundException { final FileOutputStream fileOut = new FileOutputStream(logFile);
return new PrintStream(new ByteLimitOutputStream(fileOut, byteLimit, new Runnable() {
rsmudge/armitage
src/msf/RpcConnectionImpl.java
// Path: src/armitage/ArmitageBuffer.java // public class ArmitageBuffer { // private static final class Message { // public String message = null; // public Message next = null; // } // // /* store our messages... */ // public Message first = null; // public Message last = null; // public long size = 0; // public long max = 0; // public String prompt = ""; // // /* store indices into this buffer */ // public Map indices = new HashMap(); // // /* setup the buffer?!? :) */ // public ArmitageBuffer(long max) { // this.max = max; // } // // /* store a prompt with this buffer... we're not going to do any indexing magic for now */ // public String getPrompt() { // synchronized (this) { // return prompt; // } // } // // /* set the prompt */ // public void setPrompt(String text) { // synchronized (this) { // prompt = text; // } // } // // /* post a message to this buffer */ // public void put(String text) { // synchronized (this) { // /* create our message */ // Message m = new Message(); // m.message = text; // // /* store our message */ // if (last == null && first == null) { // first = m; // last = m; // } // else { // last.next = m; // last = m; // } // // /* increment number of stored messages */ // size += 1; // // /* limit the total number of past messages to the max size */ // if (size > max) { // first = first.next; // } // } // } // // /* retrieve a set of all clients consuming this buffer */ // public Collection clients() { // synchronized (this) { // LinkedList clients = new LinkedList(indices.keySet()); // return clients; // } // } // // /* free a client */ // public void free(String id) { // synchronized (this) { // indices.remove(id); // } // } // // /* reset our indices too */ // public void reset() { // synchronized (this) { // first = null; // last = null; // indices.clear(); // size = 0; // } // } // // /* retrieve all messages available to the client (if any) */ // public String get(String id) { // synchronized (this) { // /* nadaz */ // if (first == null) // return ""; // // /* get our index into the buffer */ // Message index = null; // if (!indices.containsKey(id)) { // index = first; // } // else { // index = (Message)indices.get(id); // // /* nothing happening */ // if (index.next == null) // return ""; // // index = index.next; // } // // /* now let's walk through it */ // StringBuffer result = new StringBuffer(); // Message temp = index; // while (temp != null) { // result.append(temp.message); // index = temp; // temp = temp.next; // } // // /* store our index */ // indices.put(id, index); // // return result.toString(); // } // } // // public String toString() { // return "[" + size + " messages]"; // } // }
import java.io.*; import java.net.*; import java.text.*; import java.util.*; import javax.xml.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; import armitage.ArmitageBuffer;
catch (Exception ex) { throw new RuntimeException(ex); } } public void execute_async(String methodName) { execute_async(methodName, new Object[]{}, null); } public void execute_async(String methodName, Object[] args) { execute_async(methodName, args, null); } public void execute_async(String methodName, Object[] args, RpcCallback callback) { if (queue == null) { queue = new RpcQueue(this); } queue.execute(methodName, args, callback); } /** Runs command with no args */ public Object execute(String methodName) throws IOException { return execute(methodName, new Object[]{}); } protected HashMap locks = new HashMap(); protected String address = ""; protected HashMap buffers = new HashMap(); /* help implement our remote buffer API for PQS primitives */
// Path: src/armitage/ArmitageBuffer.java // public class ArmitageBuffer { // private static final class Message { // public String message = null; // public Message next = null; // } // // /* store our messages... */ // public Message first = null; // public Message last = null; // public long size = 0; // public long max = 0; // public String prompt = ""; // // /* store indices into this buffer */ // public Map indices = new HashMap(); // // /* setup the buffer?!? :) */ // public ArmitageBuffer(long max) { // this.max = max; // } // // /* store a prompt with this buffer... we're not going to do any indexing magic for now */ // public String getPrompt() { // synchronized (this) { // return prompt; // } // } // // /* set the prompt */ // public void setPrompt(String text) { // synchronized (this) { // prompt = text; // } // } // // /* post a message to this buffer */ // public void put(String text) { // synchronized (this) { // /* create our message */ // Message m = new Message(); // m.message = text; // // /* store our message */ // if (last == null && first == null) { // first = m; // last = m; // } // else { // last.next = m; // last = m; // } // // /* increment number of stored messages */ // size += 1; // // /* limit the total number of past messages to the max size */ // if (size > max) { // first = first.next; // } // } // } // // /* retrieve a set of all clients consuming this buffer */ // public Collection clients() { // synchronized (this) { // LinkedList clients = new LinkedList(indices.keySet()); // return clients; // } // } // // /* free a client */ // public void free(String id) { // synchronized (this) { // indices.remove(id); // } // } // // /* reset our indices too */ // public void reset() { // synchronized (this) { // first = null; // last = null; // indices.clear(); // size = 0; // } // } // // /* retrieve all messages available to the client (if any) */ // public String get(String id) { // synchronized (this) { // /* nadaz */ // if (first == null) // return ""; // // /* get our index into the buffer */ // Message index = null; // if (!indices.containsKey(id)) { // index = first; // } // else { // index = (Message)indices.get(id); // // /* nothing happening */ // if (index.next == null) // return ""; // // index = index.next; // } // // /* now let's walk through it */ // StringBuffer result = new StringBuffer(); // Message temp = index; // while (temp != null) { // result.append(temp.message); // index = temp; // temp = temp.next; // } // // /* store our index */ // indices.put(id, index); // // return result.toString(); // } // } // // public String toString() { // return "[" + size + " messages]"; // } // } // Path: src/msf/RpcConnectionImpl.java import java.io.*; import java.net.*; import java.text.*; import java.util.*; import javax.xml.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; import armitage.ArmitageBuffer; catch (Exception ex) { throw new RuntimeException(ex); } } public void execute_async(String methodName) { execute_async(methodName, new Object[]{}, null); } public void execute_async(String methodName, Object[] args) { execute_async(methodName, args, null); } public void execute_async(String methodName, Object[] args, RpcCallback callback) { if (queue == null) { queue = new RpcQueue(this); } queue.execute(methodName, args, callback); } /** Runs command with no args */ public Object execute(String methodName) throws IOException { return execute(methodName, new Object[]{}); } protected HashMap locks = new HashMap(); protected String address = ""; protected HashMap buffers = new HashMap(); /* help implement our remote buffer API for PQS primitives */
public ArmitageBuffer getABuffer(String key) {
rsmudge/armitage
src/armitage/ArmitageApplication.java
// Path: src/cortana/gui/MenuBuilder.java // public class MenuBuilder { // protected ArmitageApplication armitage; // protected MenuBridge bridge; // // public MenuBuilder(ArmitageApplication a) { // armitage = a; // bridge = new MenuBridge(a); // } // // public Loadable getBridge() { // return bridge; // } // // public void installMenu(MouseEvent ev, String key, Stack argz) { // if (ev.isPopupTrigger() && bridge.isPopulated(key)) { // JPopupMenu menu = new JPopupMenu(); // setupMenu(menu, key, argz); // // /* we check, because it may have changed its mind after setupMenu failed */ // if (bridge.isPopulated(key)) { // menu.show((JComponent)ev.getSource(), ev.getX(), ev.getY()); // ev.consume(); // } // } // } // // public void setupMenu(JComponent parent, String key, Stack argz) { // if (!bridge.isPopulated(key)) // return; // // /* setup the menu */ // bridge.push(parent, argz); // // Iterator i = bridge.getMenus(key).iterator(); // while (i.hasNext()) { // SleepClosure f = (SleepClosure)i.next(); // if (f.getOwner().isLoaded()) { // SleepUtils.runCode(f, key, null, cortana.core.EventManager.shallowCopy(argz)); // } // else { // i.remove(); // } // } // // bridge.pop(); // } // }
import javax.swing.*; import javax.swing.event.*; import java.awt.image.*; import java.awt.*; import java.awt.event.*; import java.util.*; import cortana.gui.MenuBuilder; import java.io.*; import ui.*;
package armitage; public class ArmitageApplication extends JComponent { protected JTabbedPane tabs = null; protected JSplitPane split = null; protected JMenuBar menus = new JMenuBar(); protected ScreenshotManager screens = null; protected KeyBindings keys = new KeyBindings();
// Path: src/cortana/gui/MenuBuilder.java // public class MenuBuilder { // protected ArmitageApplication armitage; // protected MenuBridge bridge; // // public MenuBuilder(ArmitageApplication a) { // armitage = a; // bridge = new MenuBridge(a); // } // // public Loadable getBridge() { // return bridge; // } // // public void installMenu(MouseEvent ev, String key, Stack argz) { // if (ev.isPopupTrigger() && bridge.isPopulated(key)) { // JPopupMenu menu = new JPopupMenu(); // setupMenu(menu, key, argz); // // /* we check, because it may have changed its mind after setupMenu failed */ // if (bridge.isPopulated(key)) { // menu.show((JComponent)ev.getSource(), ev.getX(), ev.getY()); // ev.consume(); // } // } // } // // public void setupMenu(JComponent parent, String key, Stack argz) { // if (!bridge.isPopulated(key)) // return; // // /* setup the menu */ // bridge.push(parent, argz); // // Iterator i = bridge.getMenus(key).iterator(); // while (i.hasNext()) { // SleepClosure f = (SleepClosure)i.next(); // if (f.getOwner().isLoaded()) { // SleepUtils.runCode(f, key, null, cortana.core.EventManager.shallowCopy(argz)); // } // else { // i.remove(); // } // } // // bridge.pop(); // } // } // Path: src/armitage/ArmitageApplication.java import javax.swing.*; import javax.swing.event.*; import java.awt.image.*; import java.awt.*; import java.awt.event.*; import java.util.*; import cortana.gui.MenuBuilder; import java.io.*; import ui.*; package armitage; public class ArmitageApplication extends JComponent { protected JTabbedPane tabs = null; protected JSplitPane split = null; protected JMenuBar menus = new JMenuBar(); protected ScreenshotManager screens = null; protected KeyBindings keys = new KeyBindings();
protected MenuBuilder builder = null;
rsmudge/armitage
src/cortana/metasploit/MeterpreterBridge.java
// Path: src/cortana/Safety.java // public class Safety { // /* should we ask the user what they want in life? */ // public static boolean shouldAsk(ScriptInstance script) { // return (script.getDebugFlags() & Cortana.DEBUG_INTERACT_ASK) == Cortana.DEBUG_INTERACT_ASK; // } // // /* should we log what the script is d oing? */ // public static boolean shouldLog(ScriptInstance script) { // return (script.getDebugFlags() & Cortana.DEBUG_INTERACT_LOG) == Cortana.DEBUG_INTERACT_LOG; // } // // /* let's log what the script is doing... for giggles */ // public static void log(ScriptInstance script, String text) { // script.getScriptEnvironment().showDebugMessage(text); // } // // /* let's prompt the user and act accordingly */ // public static boolean ask(ScriptInstance script, String description, String shortd) { // int result = JOptionPane.showConfirmDialog(null, description, "Approve Script Action?", JOptionPane.YES_NO_CANCEL_OPTION); // if (result == JOptionPane.YES_OPTION) { // return true; // } // else if (result == JOptionPane.NO_OPTION) { // Safety.log(script, "blocked " + shortd); // return false; // } // else if (result == JOptionPane.CANCEL_OPTION) { // //int flags = script.getDebugFlags() & ~Cortana.DEBUG_INTERACT_ASK; // //script.setDebugFlags(flags); // Safety.log(script, "user canceled script"); // script.getScriptEnvironment().flagReturn(SleepUtils.getScalar("user canceled script"), ScriptEnvironment.FLOW_CONTROL_THROW); // return true; // } // // return false; // } // }
import cortana.core.*; import cortana.Safety; import msf.*; import sleep.bridges.*; import sleep.interfaces.*; import sleep.runtime.*; import sleep.engine.*; import java.util.*; import java.io.IOException;
} public MeterpreterBridge(RpcConnection client, RpcConnection dserver, EventManager events, FilterManager filters) { this.client = client; this.dserver = dserver; this.events = events; this.filters = filters; sessions = new HashMap(); } public Scalar evaluate(String name, ScriptInstance script, Stack args) { String sid = BridgeUtilities.getString(args, ""); String command = BridgeUtilities.getString(args, ""); MeterpreterSession session = getSession(sid); MeterpreterToken token = new MeterpreterToken(); token.script = script; token.command = command; if (args.isEmpty()) { token.function = null; } else { SleepClosure f = BridgeUtilities.getFunction(args, script); token.function = f; } /* do the safety stuff */
// Path: src/cortana/Safety.java // public class Safety { // /* should we ask the user what they want in life? */ // public static boolean shouldAsk(ScriptInstance script) { // return (script.getDebugFlags() & Cortana.DEBUG_INTERACT_ASK) == Cortana.DEBUG_INTERACT_ASK; // } // // /* should we log what the script is d oing? */ // public static boolean shouldLog(ScriptInstance script) { // return (script.getDebugFlags() & Cortana.DEBUG_INTERACT_LOG) == Cortana.DEBUG_INTERACT_LOG; // } // // /* let's log what the script is doing... for giggles */ // public static void log(ScriptInstance script, String text) { // script.getScriptEnvironment().showDebugMessage(text); // } // // /* let's prompt the user and act accordingly */ // public static boolean ask(ScriptInstance script, String description, String shortd) { // int result = JOptionPane.showConfirmDialog(null, description, "Approve Script Action?", JOptionPane.YES_NO_CANCEL_OPTION); // if (result == JOptionPane.YES_OPTION) { // return true; // } // else if (result == JOptionPane.NO_OPTION) { // Safety.log(script, "blocked " + shortd); // return false; // } // else if (result == JOptionPane.CANCEL_OPTION) { // //int flags = script.getDebugFlags() & ~Cortana.DEBUG_INTERACT_ASK; // //script.setDebugFlags(flags); // Safety.log(script, "user canceled script"); // script.getScriptEnvironment().flagReturn(SleepUtils.getScalar("user canceled script"), ScriptEnvironment.FLOW_CONTROL_THROW); // return true; // } // // return false; // } // } // Path: src/cortana/metasploit/MeterpreterBridge.java import cortana.core.*; import cortana.Safety; import msf.*; import sleep.bridges.*; import sleep.interfaces.*; import sleep.runtime.*; import sleep.engine.*; import java.util.*; import java.io.IOException; } public MeterpreterBridge(RpcConnection client, RpcConnection dserver, EventManager events, FilterManager filters) { this.client = client; this.dserver = dserver; this.events = events; this.filters = filters; sessions = new HashMap(); } public Scalar evaluate(String name, ScriptInstance script, Stack args) { String sid = BridgeUtilities.getString(args, ""); String command = BridgeUtilities.getString(args, ""); MeterpreterSession session = getSession(sid); MeterpreterToken token = new MeterpreterToken(); token.script = script; token.command = command; if (args.isEmpty()) { token.function = null; } else { SleepClosure f = BridgeUtilities.getFunction(args, script); token.function = f; } /* do the safety stuff */
if (Safety.shouldAsk(script)) {
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/postconstruct/PostConstructTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/test/java/ru/vyarus/guice/ext/log/LogTest.java // public class LogTest { // Injector injector; // // @Before // public void setUp() throws Exception { // injector = Guice.createInjector(new ExtAnnotationsModule()); // } // // @Test // public void testSuccess() throws Exception { // OkBean bean = injector.getInstance(OkBean.class); // assertNotNull(bean.logger); // assertNotNull(bean.logger2); // } // // @Test(expected = ProvisionException.class) // public void testFail() throws Exception { // injector.getInstance(KoBean.class); // } // // public static class OkBean { // @Log // public Logger logger; // @Log // private Logger logger2; // } // // public static class KoBean { // @Log // private java.util.logging.Logger logger2; // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.log.LogTest; import javax.annotation.PostConstruct; import static org.junit.Assert.*;
package ru.vyarus.guice.ext.postconstruct; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PostConstructTest { Injector injector; @Before public void setUp() throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/test/java/ru/vyarus/guice/ext/log/LogTest.java // public class LogTest { // Injector injector; // // @Before // public void setUp() throws Exception { // injector = Guice.createInjector(new ExtAnnotationsModule()); // } // // @Test // public void testSuccess() throws Exception { // OkBean bean = injector.getInstance(OkBean.class); // assertNotNull(bean.logger); // assertNotNull(bean.logger2); // } // // @Test(expected = ProvisionException.class) // public void testFail() throws Exception { // injector.getInstance(KoBean.class); // } // // public static class OkBean { // @Log // public Logger logger; // @Log // private Logger logger2; // } // // public static class KoBean { // @Log // private java.util.logging.Logger logger2; // } // } // Path: src/test/java/ru/vyarus/guice/ext/postconstruct/PostConstructTest.java import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.log.LogTest; import javax.annotation.PostConstruct; import static org.junit.Assert.*; package ru.vyarus.guice.ext.postconstruct; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PostConstructTest { Injector injector; @Before public void setUp() throws Exception {
injector = Guice.createInjector(new ExtAnnotationsModule());
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/generator/support/ctor/GenerifiedConstructorBean.java
// Path: src/main/java/com/google/inject/internal/DynamicSingletonProvider.java // @Singleton // public class DynamicSingletonProvider extends DynamicClassProvider { // // @Inject // public DynamicSingletonProvider(final Injector injector) { // super(injector); // } // // @Override // protected Class<? extends Annotation> getScopeAnnotation() { // return Singleton.class; // } // } // // Path: src/test/java/ru/vyarus/guice/ext/generator/support/ProvidedInterfaceBean.java // @ScopeAnnotation(Singleton.class) // @ProvidedBy(DynamicClassProvider.class) // public interface ProvidedInterfaceBean { // // @CustomAop // String hello(); // // String badMethod(); // }
import com.google.inject.ProvidedBy; import com.google.inject.internal.DynamicSingletonProvider; import ru.vyarus.guice.ext.generator.support.ProvidedInterfaceBean; import javax.inject.Inject; import javax.inject.Provider;
package ru.vyarus.guice.ext.generator.support.ctor; /** * @author Vyacheslav Rusakov * @since 05.01.2015 */ @ProvidedBy(DynamicSingletonProvider.class) public abstract class GenerifiedConstructorBean {
// Path: src/main/java/com/google/inject/internal/DynamicSingletonProvider.java // @Singleton // public class DynamicSingletonProvider extends DynamicClassProvider { // // @Inject // public DynamicSingletonProvider(final Injector injector) { // super(injector); // } // // @Override // protected Class<? extends Annotation> getScopeAnnotation() { // return Singleton.class; // } // } // // Path: src/test/java/ru/vyarus/guice/ext/generator/support/ProvidedInterfaceBean.java // @ScopeAnnotation(Singleton.class) // @ProvidedBy(DynamicClassProvider.class) // public interface ProvidedInterfaceBean { // // @CustomAop // String hello(); // // String badMethod(); // } // Path: src/test/java/ru/vyarus/guice/ext/generator/support/ctor/GenerifiedConstructorBean.java import com.google.inject.ProvidedBy; import com.google.inject.internal.DynamicSingletonProvider; import ru.vyarus.guice.ext.generator.support.ProvidedInterfaceBean; import javax.inject.Inject; import javax.inject.Provider; package ru.vyarus.guice.ext.generator.support.ctor; /** * @author Vyacheslav Rusakov * @since 05.01.2015 */ @ProvidedBy(DynamicSingletonProvider.class) public abstract class GenerifiedConstructorBean {
Provider<ProvidedInterfaceBean> beanProvider;
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/predestroy/PreDestroyTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import static org.junit.Assert.assertEquals;
package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyTest { Injector injector;
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // } // Path: src/test/java/ru/vyarus/guice/ext/predestroy/PreDestroyTest.java import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import static org.junit.Assert.assertEquals; package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyTest { Injector injector;
DestroyableManager manager;
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/predestroy/PreDestroyTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import static org.junit.Assert.assertEquals;
package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyTest { Injector injector; DestroyableManager manager; @Before public void setUp() throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // } // Path: src/test/java/ru/vyarus/guice/ext/predestroy/PreDestroyTest.java import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import static org.junit.Assert.assertEquals; package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyTest { Injector injector; DestroyableManager manager; @Before public void setUp() throws Exception {
injector = Guice.createInjector(new ExtAnnotationsModule());
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/log/InstanceBindingTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // }
import com.google.inject.AbstractModule; import com.google.inject.Guice; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import static org.junit.Assert.assertNotNull;
package ru.vyarus.guice.ext.log; /** * @author Vyacheslav Rusakov * @since 20.12.2014 */ public class InstanceBindingTest { @Test public void testInstanceBinding() throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // Path: src/test/java/ru/vyarus/guice/ext/log/InstanceBindingTest.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import static org.junit.Assert.assertNotNull; package ru.vyarus.guice.ext.log; /** * @author Vyacheslav Rusakov * @since 20.12.2014 */ public class InstanceBindingTest { @Test public void testInstanceBinding() throws Exception {
LogTest.OkBean bean = Guice.createInjector(new ExtAnnotationsModule(), new AbstractModule() {
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/postprocess/TypePostProcessorTest.java
// Path: src/main/java/ru/vyarus/guice/ext/core/type/GeneralTypeListener.java // public class GeneralTypeListener<T> implements TypeListener { // // private final Class<T> typeClass; // private final TypePostProcessor<T> postProcessor; // // public GeneralTypeListener(final Class<T> typeClass, final TypePostProcessor<T> postProcessor) { // this.typeClass = typeClass; // this.postProcessor = postProcessor; // } // // @Override // @SuppressWarnings("unchecked") // public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { // final Class<? super I> actualType = type.getRawType(); // if (!Utils.isPackageValid(actualType)) { // return; // } // if (typeClass.isAssignableFrom(actualType)) { // encounter.register(new InjectionListener<I>() { // @Override // public void afterInjection(final I injectee) { // try { // postProcessor.process((T) injectee); // } catch (Exception ex) { // throw new IllegalStateException( // String.format("Failed to process type %s of class %s", // typeClass.getSimpleName(), injectee.getClass().getSimpleName()), ex); // } // } // }); // } // } // }
import com.google.inject.*; import com.google.inject.matcher.Matchers; import org.junit.Assert; import org.junit.Test; import ru.vyarus.guice.ext.core.type.GeneralTypeListener; import ru.vyarus.guice.ext.postprocess.support.*;
package ru.vyarus.guice.ext.postprocess; /** * @author Vyacheslav Rusakov * @since 06.01.2015 */ public class TypePostProcessorTest { @Test public void testPostProcessingByType() throws Exception { final PostProcessor postProcessor = new PostProcessor(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Bean1.class).asEagerSingleton(); bind(Bean2.class).asEagerSingleton(); bind(Bean3.class).asEagerSingleton(); bindListener(Matchers.any(),
// Path: src/main/java/ru/vyarus/guice/ext/core/type/GeneralTypeListener.java // public class GeneralTypeListener<T> implements TypeListener { // // private final Class<T> typeClass; // private final TypePostProcessor<T> postProcessor; // // public GeneralTypeListener(final Class<T> typeClass, final TypePostProcessor<T> postProcessor) { // this.typeClass = typeClass; // this.postProcessor = postProcessor; // } // // @Override // @SuppressWarnings("unchecked") // public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { // final Class<? super I> actualType = type.getRawType(); // if (!Utils.isPackageValid(actualType)) { // return; // } // if (typeClass.isAssignableFrom(actualType)) { // encounter.register(new InjectionListener<I>() { // @Override // public void afterInjection(final I injectee) { // try { // postProcessor.process((T) injectee); // } catch (Exception ex) { // throw new IllegalStateException( // String.format("Failed to process type %s of class %s", // typeClass.getSimpleName(), injectee.getClass().getSimpleName()), ex); // } // } // }); // } // } // } // Path: src/test/java/ru/vyarus/guice/ext/postprocess/TypePostProcessorTest.java import com.google.inject.*; import com.google.inject.matcher.Matchers; import org.junit.Assert; import org.junit.Test; import ru.vyarus.guice.ext.core.type.GeneralTypeListener; import ru.vyarus.guice.ext.postprocess.support.*; package ru.vyarus.guice.ext.postprocess; /** * @author Vyacheslav Rusakov * @since 06.01.2015 */ public class TypePostProcessorTest { @Test public void testPostProcessingByType() throws Exception { final PostProcessor postProcessor = new PostProcessor(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Bean1.class).asEagerSingleton(); bind(Bean2.class).asEagerSingleton(); bind(Bean3.class).asEagerSingleton(); bindListener(Matchers.any(),
new GeneralTypeListener<AbstractBean>(AbstractBean.class, postProcessor));
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/predestroy/DestroyableTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/Destroyable.java // public interface Destroyable { // // /** // * Called on context shutdown (by default on jvm shutdown), but may be called manually through destroy manager // * {@code ru.vyarus.guice.ext.managed.destroyable.DestroyableManager#destroy()}. // * Will be called one time no matter how many time destroy will be asked by manager. // * It is safe to avoid explicit exception handling (except special cases required by logic). // * // * @throws Exception on any unrecoverable error // */ // void preDestroy() throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.Destroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import static org.junit.Assert.assertEquals;
package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class DestroyableTest { Injector injector;
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/Destroyable.java // public interface Destroyable { // // /** // * Called on context shutdown (by default on jvm shutdown), but may be called manually through destroy manager // * {@code ru.vyarus.guice.ext.managed.destroyable.DestroyableManager#destroy()}. // * Will be called one time no matter how many time destroy will be asked by manager. // * It is safe to avoid explicit exception handling (except special cases required by logic). // * // * @throws Exception on any unrecoverable error // */ // void preDestroy() throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // } // Path: src/test/java/ru/vyarus/guice/ext/predestroy/DestroyableTest.java import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.Destroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import static org.junit.Assert.assertEquals; package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class DestroyableTest { Injector injector;
DestroyableManager manager;
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/predestroy/DestroyableTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/Destroyable.java // public interface Destroyable { // // /** // * Called on context shutdown (by default on jvm shutdown), but may be called manually through destroy manager // * {@code ru.vyarus.guice.ext.managed.destroyable.DestroyableManager#destroy()}. // * Will be called one time no matter how many time destroy will be asked by manager. // * It is safe to avoid explicit exception handling (except special cases required by logic). // * // * @throws Exception on any unrecoverable error // */ // void preDestroy() throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.Destroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import static org.junit.Assert.assertEquals;
package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class DestroyableTest { Injector injector; DestroyableManager manager; @Before public void setUp() throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/Destroyable.java // public interface Destroyable { // // /** // * Called on context shutdown (by default on jvm shutdown), but may be called manually through destroy manager // * {@code ru.vyarus.guice.ext.managed.destroyable.DestroyableManager#destroy()}. // * Will be called one time no matter how many time destroy will be asked by manager. // * It is safe to avoid explicit exception handling (except special cases required by logic). // * // * @throws Exception on any unrecoverable error // */ // void preDestroy() throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // } // Path: src/test/java/ru/vyarus/guice/ext/predestroy/DestroyableTest.java import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.Destroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import static org.junit.Assert.assertEquals; package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class DestroyableTest { Injector injector; DestroyableManager manager; @Before public void setUp() throws Exception {
injector = Guice.createInjector(new ExtAnnotationsModule());
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/predestroy/DestroyableTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/Destroyable.java // public interface Destroyable { // // /** // * Called on context shutdown (by default on jvm shutdown), but may be called manually through destroy manager // * {@code ru.vyarus.guice.ext.managed.destroyable.DestroyableManager#destroy()}. // * Will be called one time no matter how many time destroy will be asked by manager. // * It is safe to avoid explicit exception handling (except special cases required by logic). // * // * @throws Exception on any unrecoverable error // */ // void preDestroy() throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.Destroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import static org.junit.Assert.assertEquals;
package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class DestroyableTest { Injector injector; DestroyableManager manager; @Before public void setUp() throws Exception { injector = Guice.createInjector(new ExtAnnotationsModule()); manager = injector.getInstance(DestroyableManager.class); } @Test public void testCall() throws Exception { Bean bean = injector.getInstance(Bean.class); manager.destroy(); assertEquals(1, bean.counter); }
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/Destroyable.java // public interface Destroyable { // // /** // * Called on context shutdown (by default on jvm shutdown), but may be called manually through destroy manager // * {@code ru.vyarus.guice.ext.managed.destroyable.DestroyableManager#destroy()}. // * Will be called one time no matter how many time destroy will be asked by manager. // * It is safe to avoid explicit exception handling (except special cases required by logic). // * // * @throws Exception on any unrecoverable error // */ // void preDestroy() throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // } // Path: src/test/java/ru/vyarus/guice/ext/predestroy/DestroyableTest.java import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.Before; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import ru.vyarus.guice.ext.managed.destroyable.Destroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import static org.junit.Assert.assertEquals; package ru.vyarus.guice.ext.predestroy; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class DestroyableTest { Injector injector; DestroyableManager manager; @Before public void setUp() throws Exception { injector = Guice.createInjector(new ExtAnnotationsModule()); manager = injector.getInstance(DestroyableManager.class); } @Test public void testCall() throws Exception { Bean bean = injector.getInstance(Bean.class); manager.destroy(); assertEquals(1, bean.counter); }
public static class Bean implements Destroyable {
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/generator/support/ctor/CustomConstructorBean.java
// Path: src/main/java/com/google/inject/internal/DynamicClassProvider.java // @Singleton // public class DynamicClassProvider implements Provider<Object> { // // private final Injector injector; // // @Inject // public DynamicClassProvider(final Injector injector) { // this.injector = injector; // } // // @Override // @SuppressWarnings({"PMD.PreserveStackTrace", "PMD.NullAssignment"}) // public Object get() { // try (InternalContext context = ((InjectorImpl) injector).enterContext()) { // // check if (possibly) child context contains anchor bean definition // final boolean hasAnchor = injector.getExistingBinding(Key.get(AnchorBean.class)) != null; // final Class<?> abstractType = context.getDependency().getKey().getTypeLiteral().getRawType(); // final Class<?> generatedType = DynamicClassGenerator.generate(abstractType, getScopeAnnotation(), // hasAnchor ? AnchorBean.class : null); // return injector.getInstance(generatedType); // } // } // // /** // * Override it to specify different annotation. By default, no annotation specified which will implicitly lead // * to default prototype scope. // * // * @return scope annotation which should be applied to generated class // */ // protected Class<? extends Annotation> getScopeAnnotation() { // return null; // } // } // // Path: src/test/java/ru/vyarus/guice/ext/generator/support/ProvidedInterfaceBean.java // @ScopeAnnotation(Singleton.class) // @ProvidedBy(DynamicClassProvider.class) // public interface ProvidedInterfaceBean { // // @CustomAop // String hello(); // // String badMethod(); // }
import com.google.inject.Inject; import com.google.inject.ProvidedBy; import com.google.inject.internal.DynamicClassProvider; import ru.vyarus.guice.ext.generator.support.ProvidedInterfaceBean;
package ru.vyarus.guice.ext.generator.support.ctor; /** * @author Vyacheslav Rusakov * @since 10.12.2014 */ @ProvidedBy(DynamicClassProvider.class) public abstract class CustomConstructorBean {
// Path: src/main/java/com/google/inject/internal/DynamicClassProvider.java // @Singleton // public class DynamicClassProvider implements Provider<Object> { // // private final Injector injector; // // @Inject // public DynamicClassProvider(final Injector injector) { // this.injector = injector; // } // // @Override // @SuppressWarnings({"PMD.PreserveStackTrace", "PMD.NullAssignment"}) // public Object get() { // try (InternalContext context = ((InjectorImpl) injector).enterContext()) { // // check if (possibly) child context contains anchor bean definition // final boolean hasAnchor = injector.getExistingBinding(Key.get(AnchorBean.class)) != null; // final Class<?> abstractType = context.getDependency().getKey().getTypeLiteral().getRawType(); // final Class<?> generatedType = DynamicClassGenerator.generate(abstractType, getScopeAnnotation(), // hasAnchor ? AnchorBean.class : null); // return injector.getInstance(generatedType); // } // } // // /** // * Override it to specify different annotation. By default, no annotation specified which will implicitly lead // * to default prototype scope. // * // * @return scope annotation which should be applied to generated class // */ // protected Class<? extends Annotation> getScopeAnnotation() { // return null; // } // } // // Path: src/test/java/ru/vyarus/guice/ext/generator/support/ProvidedInterfaceBean.java // @ScopeAnnotation(Singleton.class) // @ProvidedBy(DynamicClassProvider.class) // public interface ProvidedInterfaceBean { // // @CustomAop // String hello(); // // String badMethod(); // } // Path: src/test/java/ru/vyarus/guice/ext/generator/support/ctor/CustomConstructorBean.java import com.google.inject.Inject; import com.google.inject.ProvidedBy; import com.google.inject.internal.DynamicClassProvider; import ru.vyarus.guice.ext.generator.support.ProvidedInterfaceBean; package ru.vyarus.guice.ext.generator.support.ctor; /** * @author Vyacheslav Rusakov * @since 10.12.2014 */ @ProvidedBy(DynamicClassProvider.class) public abstract class CustomConstructorBean {
ProvidedInterfaceBean bean;
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/core/generator/DynamicClassGenerator.java
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // }
import com.google.common.base.Preconditions; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.ProvidedBy; import com.google.inject.internal.Annotations; import javassist.*; import javassist.bytecode.*; import javassist.bytecode.annotation.Annotation; import ru.vyarus.guice.ext.core.util.Utils; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier;
/* * Synchronization is required to avoid double generation and consequent problems. * Very unlikely that this method would be called too often and synchronization become bottleneck. * Using original class as monitor to allow concurrent generation for different classes. */ synchronized (type) { Class<?> targetClass; try { // will work if class was already generated targetClass = classLoader.loadClass(targetClassName); } catch (ClassNotFoundException ex) { targetClass = generateClass(type, targetClassName, classLoader, scope, anchor); } return (Class<T>) targetClass; } } private static Class<?> generateClass(final Class<?> type, final String targetClassName, final ClassLoader classLoader, final Class<? extends java.lang.annotation.Annotation> scope, final Class<?> anchor) { try { // have to use custom pool because original type classloader could be thrown away // and all cached CtClass objects would be stale final ClassPool classPool = new ClassPool(); classPool.appendClassPath(new LoaderClassPath(classLoader)); final CtClass impl = generateCtClass(classPool, targetClassName, type, scope, anchor); // incompatible javassist apis for java 8 and >=9
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // Path: src/main/java/ru/vyarus/guice/ext/core/generator/DynamicClassGenerator.java import com.google.common.base.Preconditions; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.ProvidedBy; import com.google.inject.internal.Annotations; import javassist.*; import javassist.bytecode.*; import javassist.bytecode.annotation.Annotation; import ru.vyarus.guice.ext.core.util.Utils; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; /* * Synchronization is required to avoid double generation and consequent problems. * Very unlikely that this method would be called too often and synchronization become bottleneck. * Using original class as monitor to allow concurrent generation for different classes. */ synchronized (type) { Class<?> targetClass; try { // will work if class was already generated targetClass = classLoader.loadClass(targetClassName); } catch (ClassNotFoundException ex) { targetClass = generateClass(type, targetClassName, classLoader, scope, anchor); } return (Class<T>) targetClass; } } private static Class<?> generateClass(final Class<?> type, final String targetClassName, final ClassLoader classLoader, final Class<? extends java.lang.annotation.Annotation> scope, final Class<?> anchor) { try { // have to use custom pool because original type classloader could be thrown away // and all cached CtClass objects would be stale final ClassPool classPool = new ClassPool(); classPool.appendClassPath(new LoaderClassPath(classLoader)); final CtClass impl = generateCtClass(classPool, targetClassName, type, scope, anchor); // incompatible javassist apis for java 8 and >=9
return Utils.isJava8() ? impl.toClass(classLoader, type.getProtectionDomain()) : impl.toClass(type);
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/generator/GeneratorAnchorsTest.java
// Path: src/main/java/ru/vyarus/guice/ext/core/generator/anchor/GeneratorAnchorModule.java // public class GeneratorAnchorModule extends AbstractModule { // // @Override // protected void configure() { // // providers bound explicitly to tie them to child injector // bind(DynamicClassProvider.class); // bind(DynamicSingletonProvider.class); // // anchor bean used to tie dynamically provided beans to child injector // bind(AnchorBean.class).in(Singleton.class); // } // }
import com.google.inject.*; import com.google.inject.matcher.Matchers; import com.google.inject.name.Names; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.junit.Assert; import org.junit.Test; import ru.vyarus.guice.ext.core.generator.anchor.GeneratorAnchorModule; import ru.vyarus.guice.ext.generator.support.anchor.*; import ru.vyarus.guice.ext.generator.support.aop.CustomAop; import javax.inject.Inject; import javax.inject.Provider;
package ru.vyarus.guice.ext.generator; /** * @author Vyacheslav Rusakov * @since 21.09.2016 */ public class GeneratorAnchorsTest { @Test(expected = AbstractMethodError.class) public void checkChildInjectorFailure() throws Exception { // aop registered in child injector Injector injector = Guice.createInjector().createChildInjector(new ChildAopModule()); // bean will be generated at root injector and so no aop will apply on it injector.getInstance(TestIface.class).hello(); } @Test public void testAnchorModule() throws Exception { // aop registered in child injector with anchor module
// Path: src/main/java/ru/vyarus/guice/ext/core/generator/anchor/GeneratorAnchorModule.java // public class GeneratorAnchorModule extends AbstractModule { // // @Override // protected void configure() { // // providers bound explicitly to tie them to child injector // bind(DynamicClassProvider.class); // bind(DynamicSingletonProvider.class); // // anchor bean used to tie dynamically provided beans to child injector // bind(AnchorBean.class).in(Singleton.class); // } // } // Path: src/test/java/ru/vyarus/guice/ext/generator/GeneratorAnchorsTest.java import com.google.inject.*; import com.google.inject.matcher.Matchers; import com.google.inject.name.Names; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.junit.Assert; import org.junit.Test; import ru.vyarus.guice.ext.core.generator.anchor.GeneratorAnchorModule; import ru.vyarus.guice.ext.generator.support.anchor.*; import ru.vyarus.guice.ext.generator.support.aop.CustomAop; import javax.inject.Inject; import javax.inject.Provider; package ru.vyarus.guice.ext.generator; /** * @author Vyacheslav Rusakov * @since 21.09.2016 */ public class GeneratorAnchorsTest { @Test(expected = AbstractMethodError.class) public void checkChildInjectorFailure() throws Exception { // aop registered in child injector Injector injector = Guice.createInjector().createChildInjector(new ChildAopModule()); // bean will be generated at root injector and so no aop will apply on it injector.getInstance(TestIface.class).hello(); } @Test public void testAnchorModule() throws Exception { // aop registered in child injector with anchor module
Injector injector = Guice.createInjector().createChildInjector(new ChildAopModule(), new GeneratorAnchorModule());
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/core/method/AnnotatedMethodTypeListener.java
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // }
import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import ru.vyarus.guice.ext.core.util.Utils; import java.lang.annotation.Annotation; import java.lang.reflect.Method;
package ru.vyarus.guice.ext.core.method; /** * Generic type listener to process annotated methods after bean instantiation. * * @author Vyacheslav Rusakov * @since 30.06.2014 * @param <T> annotation type */ public class AnnotatedMethodTypeListener<T extends Annotation> implements TypeListener { private final Class<T> annotationClass; private final MethodPostProcessor<T> postProcessor; public AnnotatedMethodTypeListener(final Class<T> annotationClass, final MethodPostProcessor<T> postProcessor) { this.annotationClass = annotationClass; this.postProcessor = postProcessor; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Class<? super I> actualType = type.getRawType();
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // Path: src/main/java/ru/vyarus/guice/ext/core/method/AnnotatedMethodTypeListener.java import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import ru.vyarus.guice.ext.core.util.Utils; import java.lang.annotation.Annotation; import java.lang.reflect.Method; package ru.vyarus.guice.ext.core.method; /** * Generic type listener to process annotated methods after bean instantiation. * * @author Vyacheslav Rusakov * @since 30.06.2014 * @param <T> annotation type */ public class AnnotatedMethodTypeListener<T extends Annotation> implements TypeListener { private final Class<T> annotationClass; private final MethodPostProcessor<T> postProcessor; public AnnotatedMethodTypeListener(final Class<T> annotationClass, final MethodPostProcessor<T> postProcessor) { this.annotationClass = annotationClass; this.postProcessor = postProcessor; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Class<? super I> actualType = type.getRawType();
if (!Utils.isPackageValid(actualType)) {
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/core/type/GeneralTypeListener.java
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // }
import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import ru.vyarus.guice.ext.core.util.Utils;
package ru.vyarus.guice.ext.core.type; /** * Generic type listener for bean types (exact class, by base class or beans annotating interface). * * @param <T> bean type * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class GeneralTypeListener<T> implements TypeListener { private final Class<T> typeClass; private final TypePostProcessor<T> postProcessor; public GeneralTypeListener(final Class<T> typeClass, final TypePostProcessor<T> postProcessor) { this.typeClass = typeClass; this.postProcessor = postProcessor; } @Override @SuppressWarnings("unchecked") public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Class<? super I> actualType = type.getRawType();
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // Path: src/main/java/ru/vyarus/guice/ext/core/type/GeneralTypeListener.java import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import ru.vyarus.guice.ext.core.util.Utils; package ru.vyarus.guice.ext.core.type; /** * Generic type listener for bean types (exact class, by base class or beans annotating interface). * * @param <T> bean type * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class GeneralTypeListener<T> implements TypeListener { private final Class<T> typeClass; private final TypePostProcessor<T> postProcessor; public GeneralTypeListener(final Class<T> typeClass, final TypePostProcessor<T> postProcessor) { this.typeClass = typeClass; this.postProcessor = postProcessor; } @Override @SuppressWarnings("unchecked") public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Class<? super I> actualType = type.getRawType();
if (!Utils.isPackageValid(actualType)) {
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/core/field/AnnotatedFieldTypeListener.java
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // }
import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import ru.vyarus.guice.ext.core.util.Utils; import java.lang.annotation.Annotation; import java.lang.reflect.Field;
package ru.vyarus.guice.ext.core.field; /** * Generic type listener to process annotated fields after bean instantiation. * * @author Vyacheslav Rusakov * @since 30.06.2014 * @param <T> annotation type */ public class AnnotatedFieldTypeListener<T extends Annotation> implements TypeListener { private final Class<T> annotationClass; private final FieldPostProcessor<T> postProcessor; public AnnotatedFieldTypeListener(final Class<T> annotationClass, final FieldPostProcessor<T> postProcessor) { this.annotationClass = annotationClass; this.postProcessor = postProcessor; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Class<? super I> actualType = type.getRawType();
// Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // Path: src/main/java/ru/vyarus/guice/ext/core/field/AnnotatedFieldTypeListener.java import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import ru.vyarus.guice.ext.core.util.Utils; import java.lang.annotation.Annotation; import java.lang.reflect.Field; package ru.vyarus.guice.ext.core.field; /** * Generic type listener to process annotated fields after bean instantiation. * * @author Vyacheslav Rusakov * @since 30.06.2014 * @param <T> annotation type */ public class AnnotatedFieldTypeListener<T extends Annotation> implements TypeListener { private final Class<T> annotationClass; private final FieldPostProcessor<T> postProcessor; public AnnotatedFieldTypeListener(final Class<T> annotationClass, final FieldPostProcessor<T> postProcessor) { this.annotationClass = annotationClass; this.postProcessor = postProcessor; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Class<? super I> actualType = type.getRawType();
if (!Utils.isPackageValid(actualType)) {
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/core/generator/anchor/GeneratorAnchorModule.java
// Path: src/main/java/com/google/inject/internal/DynamicClassProvider.java // @Singleton // public class DynamicClassProvider implements Provider<Object> { // // private final Injector injector; // // @Inject // public DynamicClassProvider(final Injector injector) { // this.injector = injector; // } // // @Override // @SuppressWarnings({"PMD.PreserveStackTrace", "PMD.NullAssignment"}) // public Object get() { // try (InternalContext context = ((InjectorImpl) injector).enterContext()) { // // check if (possibly) child context contains anchor bean definition // final boolean hasAnchor = injector.getExistingBinding(Key.get(AnchorBean.class)) != null; // final Class<?> abstractType = context.getDependency().getKey().getTypeLiteral().getRawType(); // final Class<?> generatedType = DynamicClassGenerator.generate(abstractType, getScopeAnnotation(), // hasAnchor ? AnchorBean.class : null); // return injector.getInstance(generatedType); // } // } // // /** // * Override it to specify different annotation. By default, no annotation specified which will implicitly lead // * to default prototype scope. // * // * @return scope annotation which should be applied to generated class // */ // protected Class<? extends Annotation> getScopeAnnotation() { // return null; // } // } // // Path: src/main/java/com/google/inject/internal/DynamicSingletonProvider.java // @Singleton // public class DynamicSingletonProvider extends DynamicClassProvider { // // @Inject // public DynamicSingletonProvider(final Injector injector) { // super(injector); // } // // @Override // protected Class<? extends Annotation> getScopeAnnotation() { // return Singleton.class; // } // }
import com.google.inject.AbstractModule; import com.google.inject.internal.DynamicClassProvider; import com.google.inject.internal.DynamicSingletonProvider; import javax.inject.Singleton;
package ru.vyarus.guice.ext.core.generator.anchor; /** * Support module used to tie dynamic binding for generated class (generated with {@link DynamicClassProvider}) to * exact injector in injectors hierarchy. Also, allows using JIT resolution for generated classes in private modules * (without binding them explicitly). * <p> * Situation without this module: suppose we have root and child injector and aop interceptors * (which must intercept generated abstract method calls) are registered in child module. If abstract bean * resolved with guice JIT ({@code @ProvidedBy(DynamicClassProvider.class)} then it's binding will be created * in upper-most injector: root injector. As a result, calling any abstract method will fail, because interceptors * are not present in root module (only in child module). * <p> * To fix this problem we need to "tie" generated class binding to child injector. Guice will not bubble it up * only if it depends on some other bean located in child injector. For this purpose, module registers * dummy service {@link AnchorBean} which is only required to "hold" generated been in child injector. * Also, provider classes are explicitly bound to be able to operate with child injector in provider. * Both {@link DynamicClassProvider} and {@link DynamicSingletonProvider} will check first if anchor bean * is available in current injector and inject dependency on this bean into generated class (add new constructor * parameter for abstract class with constructor and generate new constructor for interface implementation or * abstract class without constructor). * <p> * Also, module will prevent improper guice injector usage. For example, anchor module registered in child injector * and some service DynService depends (injects) on abstract class annotated * with {@code ProvidedBy(DynamicClassProvider.class)}. If DynService is not bound in child injector and we try * to create instance of (using JIT binding) it from root injector, then guice will try to obtain DynamicClassProvider * in root context and fail with duplicate binding definition (without anchor module, everything would pass, * but aop will not work, because it was registered in child injector). * <p> * Example usage: * <pre><code> * Injector childInjector = Guice.createInjector() // root injector * .createChildInjector(new GeneratorAnchorModule(), new MyAopModule()); * // JIT binding for MyAbstractService (generated class) will be in child injector and so aop will work * childInjector.getInstance(MyAbstractService.class).someAMethodHandledWithAop(); * </code></pre> * <p> * Private module example: * <pre><code> * public class MyPrivateModule extends PrivateModule { * protected void configure() { * install(new MyAopModule()); * install(new GeneratorAnchorModule()); * } * * {@literal @}Provides @Exposed @Named("myBean") * MyAbstractBean provide(MyAbstractBean bean) { * return bean; * } * } * * Injector injector = Injector.createModule(new MyPrivateModule()); * // obtain exposed named instance outside of private module * // note that abstract bean was not bound and resolved with JIT * injector.getInstance(Key.get(MyAbstractBean.class, Names.named("myBean"))) * </code></pre> * * @author Vyacheslav Rusakov * @since 21.09.2016 */ public class GeneratorAnchorModule extends AbstractModule { @Override protected void configure() { // providers bound explicitly to tie them to child injector
// Path: src/main/java/com/google/inject/internal/DynamicClassProvider.java // @Singleton // public class DynamicClassProvider implements Provider<Object> { // // private final Injector injector; // // @Inject // public DynamicClassProvider(final Injector injector) { // this.injector = injector; // } // // @Override // @SuppressWarnings({"PMD.PreserveStackTrace", "PMD.NullAssignment"}) // public Object get() { // try (InternalContext context = ((InjectorImpl) injector).enterContext()) { // // check if (possibly) child context contains anchor bean definition // final boolean hasAnchor = injector.getExistingBinding(Key.get(AnchorBean.class)) != null; // final Class<?> abstractType = context.getDependency().getKey().getTypeLiteral().getRawType(); // final Class<?> generatedType = DynamicClassGenerator.generate(abstractType, getScopeAnnotation(), // hasAnchor ? AnchorBean.class : null); // return injector.getInstance(generatedType); // } // } // // /** // * Override it to specify different annotation. By default, no annotation specified which will implicitly lead // * to default prototype scope. // * // * @return scope annotation which should be applied to generated class // */ // protected Class<? extends Annotation> getScopeAnnotation() { // return null; // } // } // // Path: src/main/java/com/google/inject/internal/DynamicSingletonProvider.java // @Singleton // public class DynamicSingletonProvider extends DynamicClassProvider { // // @Inject // public DynamicSingletonProvider(final Injector injector) { // super(injector); // } // // @Override // protected Class<? extends Annotation> getScopeAnnotation() { // return Singleton.class; // } // } // Path: src/main/java/ru/vyarus/guice/ext/core/generator/anchor/GeneratorAnchorModule.java import com.google.inject.AbstractModule; import com.google.inject.internal.DynamicClassProvider; import com.google.inject.internal.DynamicSingletonProvider; import javax.inject.Singleton; package ru.vyarus.guice.ext.core.generator.anchor; /** * Support module used to tie dynamic binding for generated class (generated with {@link DynamicClassProvider}) to * exact injector in injectors hierarchy. Also, allows using JIT resolution for generated classes in private modules * (without binding them explicitly). * <p> * Situation without this module: suppose we have root and child injector and aop interceptors * (which must intercept generated abstract method calls) are registered in child module. If abstract bean * resolved with guice JIT ({@code @ProvidedBy(DynamicClassProvider.class)} then it's binding will be created * in upper-most injector: root injector. As a result, calling any abstract method will fail, because interceptors * are not present in root module (only in child module). * <p> * To fix this problem we need to "tie" generated class binding to child injector. Guice will not bubble it up * only if it depends on some other bean located in child injector. For this purpose, module registers * dummy service {@link AnchorBean} which is only required to "hold" generated been in child injector. * Also, provider classes are explicitly bound to be able to operate with child injector in provider. * Both {@link DynamicClassProvider} and {@link DynamicSingletonProvider} will check first if anchor bean * is available in current injector and inject dependency on this bean into generated class (add new constructor * parameter for abstract class with constructor and generate new constructor for interface implementation or * abstract class without constructor). * <p> * Also, module will prevent improper guice injector usage. For example, anchor module registered in child injector * and some service DynService depends (injects) on abstract class annotated * with {@code ProvidedBy(DynamicClassProvider.class)}. If DynService is not bound in child injector and we try * to create instance of (using JIT binding) it from root injector, then guice will try to obtain DynamicClassProvider * in root context and fail with duplicate binding definition (without anchor module, everything would pass, * but aop will not work, because it was registered in child injector). * <p> * Example usage: * <pre><code> * Injector childInjector = Guice.createInjector() // root injector * .createChildInjector(new GeneratorAnchorModule(), new MyAopModule()); * // JIT binding for MyAbstractService (generated class) will be in child injector and so aop will work * childInjector.getInstance(MyAbstractService.class).someAMethodHandledWithAop(); * </code></pre> * <p> * Private module example: * <pre><code> * public class MyPrivateModule extends PrivateModule { * protected void configure() { * install(new MyAopModule()); * install(new GeneratorAnchorModule()); * } * * {@literal @}Provides @Exposed @Named("myBean") * MyAbstractBean provide(MyAbstractBean bean) { * return bean; * } * } * * Injector injector = Injector.createModule(new MyPrivateModule()); * // obtain exposed named instance outside of private module * // note that abstract bean was not bound and resolved with JIT * injector.getInstance(Key.get(MyAbstractBean.class, Names.named("myBean"))) * </code></pre> * * @author Vyacheslav Rusakov * @since 21.09.2016 */ public class GeneratorAnchorModule extends AbstractModule { @Override protected void configure() { // providers bound explicitly to tie them to child injector
bind(DynamicClassProvider.class);
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/core/generator/anchor/GeneratorAnchorModule.java
// Path: src/main/java/com/google/inject/internal/DynamicClassProvider.java // @Singleton // public class DynamicClassProvider implements Provider<Object> { // // private final Injector injector; // // @Inject // public DynamicClassProvider(final Injector injector) { // this.injector = injector; // } // // @Override // @SuppressWarnings({"PMD.PreserveStackTrace", "PMD.NullAssignment"}) // public Object get() { // try (InternalContext context = ((InjectorImpl) injector).enterContext()) { // // check if (possibly) child context contains anchor bean definition // final boolean hasAnchor = injector.getExistingBinding(Key.get(AnchorBean.class)) != null; // final Class<?> abstractType = context.getDependency().getKey().getTypeLiteral().getRawType(); // final Class<?> generatedType = DynamicClassGenerator.generate(abstractType, getScopeAnnotation(), // hasAnchor ? AnchorBean.class : null); // return injector.getInstance(generatedType); // } // } // // /** // * Override it to specify different annotation. By default, no annotation specified which will implicitly lead // * to default prototype scope. // * // * @return scope annotation which should be applied to generated class // */ // protected Class<? extends Annotation> getScopeAnnotation() { // return null; // } // } // // Path: src/main/java/com/google/inject/internal/DynamicSingletonProvider.java // @Singleton // public class DynamicSingletonProvider extends DynamicClassProvider { // // @Inject // public DynamicSingletonProvider(final Injector injector) { // super(injector); // } // // @Override // protected Class<? extends Annotation> getScopeAnnotation() { // return Singleton.class; // } // }
import com.google.inject.AbstractModule; import com.google.inject.internal.DynamicClassProvider; import com.google.inject.internal.DynamicSingletonProvider; import javax.inject.Singleton;
package ru.vyarus.guice.ext.core.generator.anchor; /** * Support module used to tie dynamic binding for generated class (generated with {@link DynamicClassProvider}) to * exact injector in injectors hierarchy. Also, allows using JIT resolution for generated classes in private modules * (without binding them explicitly). * <p> * Situation without this module: suppose we have root and child injector and aop interceptors * (which must intercept generated abstract method calls) are registered in child module. If abstract bean * resolved with guice JIT ({@code @ProvidedBy(DynamicClassProvider.class)} then it's binding will be created * in upper-most injector: root injector. As a result, calling any abstract method will fail, because interceptors * are not present in root module (only in child module). * <p> * To fix this problem we need to "tie" generated class binding to child injector. Guice will not bubble it up * only if it depends on some other bean located in child injector. For this purpose, module registers * dummy service {@link AnchorBean} which is only required to "hold" generated been in child injector. * Also, provider classes are explicitly bound to be able to operate with child injector in provider. * Both {@link DynamicClassProvider} and {@link DynamicSingletonProvider} will check first if anchor bean * is available in current injector and inject dependency on this bean into generated class (add new constructor * parameter for abstract class with constructor and generate new constructor for interface implementation or * abstract class without constructor). * <p> * Also, module will prevent improper guice injector usage. For example, anchor module registered in child injector * and some service DynService depends (injects) on abstract class annotated * with {@code ProvidedBy(DynamicClassProvider.class)}. If DynService is not bound in child injector and we try * to create instance of (using JIT binding) it from root injector, then guice will try to obtain DynamicClassProvider * in root context and fail with duplicate binding definition (without anchor module, everything would pass, * but aop will not work, because it was registered in child injector). * <p> * Example usage: * <pre><code> * Injector childInjector = Guice.createInjector() // root injector * .createChildInjector(new GeneratorAnchorModule(), new MyAopModule()); * // JIT binding for MyAbstractService (generated class) will be in child injector and so aop will work * childInjector.getInstance(MyAbstractService.class).someAMethodHandledWithAop(); * </code></pre> * <p> * Private module example: * <pre><code> * public class MyPrivateModule extends PrivateModule { * protected void configure() { * install(new MyAopModule()); * install(new GeneratorAnchorModule()); * } * * {@literal @}Provides @Exposed @Named("myBean") * MyAbstractBean provide(MyAbstractBean bean) { * return bean; * } * } * * Injector injector = Injector.createModule(new MyPrivateModule()); * // obtain exposed named instance outside of private module * // note that abstract bean was not bound and resolved with JIT * injector.getInstance(Key.get(MyAbstractBean.class, Names.named("myBean"))) * </code></pre> * * @author Vyacheslav Rusakov * @since 21.09.2016 */ public class GeneratorAnchorModule extends AbstractModule { @Override protected void configure() { // providers bound explicitly to tie them to child injector bind(DynamicClassProvider.class);
// Path: src/main/java/com/google/inject/internal/DynamicClassProvider.java // @Singleton // public class DynamicClassProvider implements Provider<Object> { // // private final Injector injector; // // @Inject // public DynamicClassProvider(final Injector injector) { // this.injector = injector; // } // // @Override // @SuppressWarnings({"PMD.PreserveStackTrace", "PMD.NullAssignment"}) // public Object get() { // try (InternalContext context = ((InjectorImpl) injector).enterContext()) { // // check if (possibly) child context contains anchor bean definition // final boolean hasAnchor = injector.getExistingBinding(Key.get(AnchorBean.class)) != null; // final Class<?> abstractType = context.getDependency().getKey().getTypeLiteral().getRawType(); // final Class<?> generatedType = DynamicClassGenerator.generate(abstractType, getScopeAnnotation(), // hasAnchor ? AnchorBean.class : null); // return injector.getInstance(generatedType); // } // } // // /** // * Override it to specify different annotation. By default, no annotation specified which will implicitly lead // * to default prototype scope. // * // * @return scope annotation which should be applied to generated class // */ // protected Class<? extends Annotation> getScopeAnnotation() { // return null; // } // } // // Path: src/main/java/com/google/inject/internal/DynamicSingletonProvider.java // @Singleton // public class DynamicSingletonProvider extends DynamicClassProvider { // // @Inject // public DynamicSingletonProvider(final Injector injector) { // super(injector); // } // // @Override // protected Class<? extends Annotation> getScopeAnnotation() { // return Singleton.class; // } // } // Path: src/main/java/ru/vyarus/guice/ext/core/generator/anchor/GeneratorAnchorModule.java import com.google.inject.AbstractModule; import com.google.inject.internal.DynamicClassProvider; import com.google.inject.internal.DynamicSingletonProvider; import javax.inject.Singleton; package ru.vyarus.guice.ext.core.generator.anchor; /** * Support module used to tie dynamic binding for generated class (generated with {@link DynamicClassProvider}) to * exact injector in injectors hierarchy. Also, allows using JIT resolution for generated classes in private modules * (without binding them explicitly). * <p> * Situation without this module: suppose we have root and child injector and aop interceptors * (which must intercept generated abstract method calls) are registered in child module. If abstract bean * resolved with guice JIT ({@code @ProvidedBy(DynamicClassProvider.class)} then it's binding will be created * in upper-most injector: root injector. As a result, calling any abstract method will fail, because interceptors * are not present in root module (only in child module). * <p> * To fix this problem we need to "tie" generated class binding to child injector. Guice will not bubble it up * only if it depends on some other bean located in child injector. For this purpose, module registers * dummy service {@link AnchorBean} which is only required to "hold" generated been in child injector. * Also, provider classes are explicitly bound to be able to operate with child injector in provider. * Both {@link DynamicClassProvider} and {@link DynamicSingletonProvider} will check first if anchor bean * is available in current injector and inject dependency on this bean into generated class (add new constructor * parameter for abstract class with constructor and generate new constructor for interface implementation or * abstract class without constructor). * <p> * Also, module will prevent improper guice injector usage. For example, anchor module registered in child injector * and some service DynService depends (injects) on abstract class annotated * with {@code ProvidedBy(DynamicClassProvider.class)}. If DynService is not bound in child injector and we try * to create instance of (using JIT binding) it from root injector, then guice will try to obtain DynamicClassProvider * in root context and fail with duplicate binding definition (without anchor module, everything would pass, * but aop will not work, because it was registered in child injector). * <p> * Example usage: * <pre><code> * Injector childInjector = Guice.createInjector() // root injector * .createChildInjector(new GeneratorAnchorModule(), new MyAopModule()); * // JIT binding for MyAbstractService (generated class) will be in child injector and so aop will work * childInjector.getInstance(MyAbstractService.class).someAMethodHandledWithAop(); * </code></pre> * <p> * Private module example: * <pre><code> * public class MyPrivateModule extends PrivateModule { * protected void configure() { * install(new MyAopModule()); * install(new GeneratorAnchorModule()); * } * * {@literal @}Provides @Exposed @Named("myBean") * MyAbstractBean provide(MyAbstractBean bean) { * return bean; * } * } * * Injector injector = Injector.createModule(new MyPrivateModule()); * // obtain exposed named instance outside of private module * // note that abstract bean was not bound and resolved with JIT * injector.getInstance(Key.get(MyAbstractBean.class, Names.named("myBean"))) * </code></pre> * * @author Vyacheslav Rusakov * @since 21.09.2016 */ public class GeneratorAnchorModule extends AbstractModule { @Override protected void configure() { // providers bound explicitly to tie them to child injector bind(DynamicClassProvider.class);
bind(DynamicSingletonProvider.class);
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/postconstruct/InheritanceTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // }
import com.google.inject.Guice; import org.junit.Assert; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import javax.annotation.PostConstruct;
package ru.vyarus.guice.ext.postconstruct; /** * @author Vyacheslav Rusakov * @since 20.12.2014 */ public class InheritanceTest { @Test public void testInheritance() throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // Path: src/test/java/ru/vyarus/guice/ext/postconstruct/InheritanceTest.java import com.google.inject.Guice; import org.junit.Assert; import org.junit.Test; import ru.vyarus.guice.ext.ExtAnnotationsModule; import javax.annotation.PostConstruct; package ru.vyarus.guice.ext.postconstruct; /** * @author Vyacheslav Rusakov * @since 20.12.2014 */ public class InheritanceTest { @Test public void testInheritance() throws Exception {
Bean bean = Guice.createInjector(new ExtAnnotationsModule()).getInstance(Bean.class);
xvik/guice-ext-annotations
src/test/java/ru/vyarus/guice/ext/log/LogTest.java
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // }
import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import ru.vyarus.guice.ext.ExtAnnotationsModule; import static org.junit.Assert.assertNotNull;
package ru.vyarus.guice.ext.log; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class LogTest { Injector injector; @Before public void setUp() throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/ExtAnnotationsModule.java // @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") // public class ExtAnnotationsModule extends AbstractModule { // // private Matcher<Object> typeMatcher; // // /** // * Default module constructor to check annotations on all beans. // */ // public ExtAnnotationsModule() { // this(Matchers.any()); // } // // /** // * Constructs annotation module with annotation scan limited to provided package. // * (used mainly for startup performance optimization) // * // * @param pkg package to limit beans, where annotations processed // */ // public ExtAnnotationsModule(final String pkg) { // this(new ObjectPackageMatcher<Object>(pkg)); // } // // /** // * Constructs annotation module with custom bean matcher for annotations processing. // * // * @param typeMatcher matcher to select beans for annotations processing // */ // public ExtAnnotationsModule(final Matcher<Object> typeMatcher) { // this.typeMatcher = typeMatcher; // } // // @Override // protected void configure() { // final DestroyableManager manager = configureManager(new DestroyableManager()); // // bindListener(typeMatcher, new GeneralTypeListener<Destroyable>( // Destroyable.class, new DestroyableTypeProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PostConstruct>( // PostConstruct.class, new PostConstructAnnotationProcessor())); // // bindListener(typeMatcher, new AnnotatedMethodTypeListener<PreDestroy>( // PreDestroy.class, new PreDestroyAnnotationProcessor(manager))); // // bindListener(typeMatcher, new AnnotatedFieldTypeListener<Log>( // Log.class, new Slf4jLogAnnotationProcessor())); // } // // // /** // * Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown. // * // * @param manager destroyable manager instance // * @return manager instance // */ // protected DestroyableManager configureManager(final DestroyableManager manager) { // bind(DestroyableManager.class).toInstance(manager); // // if logic will not call destroy at least it will be called before jvm shutdown // Runtime.getRuntime().addShutdownHook(new Thread(manager)); // return manager; // } // } // Path: src/test/java/ru/vyarus/guice/ext/log/LogTest.java import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvisionException; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import ru.vyarus.guice.ext.ExtAnnotationsModule; import static org.junit.Assert.assertNotNull; package ru.vyarus.guice.ext.log; /** * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class LogTest { Injector injector; @Before public void setUp() throws Exception {
injector = Guice.createInjector(new ExtAnnotationsModule());
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/managed/PreDestroyAnnotationProcessor.java
// Path: src/main/java/ru/vyarus/guice/ext/core/method/MethodPostProcessor.java // public interface MethodPostProcessor<T extends Annotation> { // // /** // * Called to post process annotated bean method. // * It is safe to avoid explicit exception handling (except special cases required by processor logic). // * // * @param annotation annotation instance // * @param method annotated method // * @param instance bean instance // * @throws Exception on any unrecoverable error // * @see ru.vyarus.guice.ext.core.method.AnnotatedMethodTypeListener // */ // void process(T annotation, Method method, Object instance) throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/AnnotatedMethodDestroyable.java // public class AnnotatedMethodDestroyable implements Destroyable { // // private final Method method; // private final Object instance; // // public AnnotatedMethodDestroyable(final Method method, final Object instance) { // this.method = method; // this.instance = instance; // } // // @Override // public void preDestroy() throws Exception { // method.invoke(instance); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // }
import ru.vyarus.guice.ext.core.method.MethodPostProcessor; import ru.vyarus.guice.ext.core.util.Utils; import ru.vyarus.guice.ext.managed.destroyable.AnnotatedMethodDestroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import java.lang.reflect.Method;
package ru.vyarus.guice.ext.managed; /** * Registers bean methods annotated with @PostConstruct in {@code DestroyableManager} to be called on shutdown. * * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyAnnotationProcessor implements MethodPostProcessor<PreDestroy> { private final DestroyableManager manager; public PreDestroyAnnotationProcessor(final DestroyableManager manager) { this.manager = manager; } @Override public void process(final PreDestroy annotation, final Method method, final Object instance) throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/core/method/MethodPostProcessor.java // public interface MethodPostProcessor<T extends Annotation> { // // /** // * Called to post process annotated bean method. // * It is safe to avoid explicit exception handling (except special cases required by processor logic). // * // * @param annotation annotation instance // * @param method annotated method // * @param instance bean instance // * @throws Exception on any unrecoverable error // * @see ru.vyarus.guice.ext.core.method.AnnotatedMethodTypeListener // */ // void process(T annotation, Method method, Object instance) throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/AnnotatedMethodDestroyable.java // public class AnnotatedMethodDestroyable implements Destroyable { // // private final Method method; // private final Object instance; // // public AnnotatedMethodDestroyable(final Method method, final Object instance) { // this.method = method; // this.instance = instance; // } // // @Override // public void preDestroy() throws Exception { // method.invoke(instance); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // } // Path: src/main/java/ru/vyarus/guice/ext/managed/PreDestroyAnnotationProcessor.java import ru.vyarus.guice.ext.core.method.MethodPostProcessor; import ru.vyarus.guice.ext.core.util.Utils; import ru.vyarus.guice.ext.managed.destroyable.AnnotatedMethodDestroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import java.lang.reflect.Method; package ru.vyarus.guice.ext.managed; /** * Registers bean methods annotated with @PostConstruct in {@code DestroyableManager} to be called on shutdown. * * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyAnnotationProcessor implements MethodPostProcessor<PreDestroy> { private final DestroyableManager manager; public PreDestroyAnnotationProcessor(final DestroyableManager manager) { this.manager = manager; } @Override public void process(final PreDestroy annotation, final Method method, final Object instance) throws Exception {
Utils.checkNoParams(method);
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/managed/PreDestroyAnnotationProcessor.java
// Path: src/main/java/ru/vyarus/guice/ext/core/method/MethodPostProcessor.java // public interface MethodPostProcessor<T extends Annotation> { // // /** // * Called to post process annotated bean method. // * It is safe to avoid explicit exception handling (except special cases required by processor logic). // * // * @param annotation annotation instance // * @param method annotated method // * @param instance bean instance // * @throws Exception on any unrecoverable error // * @see ru.vyarus.guice.ext.core.method.AnnotatedMethodTypeListener // */ // void process(T annotation, Method method, Object instance) throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/AnnotatedMethodDestroyable.java // public class AnnotatedMethodDestroyable implements Destroyable { // // private final Method method; // private final Object instance; // // public AnnotatedMethodDestroyable(final Method method, final Object instance) { // this.method = method; // this.instance = instance; // } // // @Override // public void preDestroy() throws Exception { // method.invoke(instance); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // }
import ru.vyarus.guice.ext.core.method.MethodPostProcessor; import ru.vyarus.guice.ext.core.util.Utils; import ru.vyarus.guice.ext.managed.destroyable.AnnotatedMethodDestroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import java.lang.reflect.Method;
package ru.vyarus.guice.ext.managed; /** * Registers bean methods annotated with @PostConstruct in {@code DestroyableManager} to be called on shutdown. * * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyAnnotationProcessor implements MethodPostProcessor<PreDestroy> { private final DestroyableManager manager; public PreDestroyAnnotationProcessor(final DestroyableManager manager) { this.manager = manager; } @Override public void process(final PreDestroy annotation, final Method method, final Object instance) throws Exception { Utils.checkNoParams(method);
// Path: src/main/java/ru/vyarus/guice/ext/core/method/MethodPostProcessor.java // public interface MethodPostProcessor<T extends Annotation> { // // /** // * Called to post process annotated bean method. // * It is safe to avoid explicit exception handling (except special cases required by processor logic). // * // * @param annotation annotation instance // * @param method annotated method // * @param instance bean instance // * @throws Exception on any unrecoverable error // * @see ru.vyarus.guice.ext.core.method.AnnotatedMethodTypeListener // */ // void process(T annotation, Method method, Object instance) throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/AnnotatedMethodDestroyable.java // public class AnnotatedMethodDestroyable implements Destroyable { // // private final Method method; // private final Object instance; // // public AnnotatedMethodDestroyable(final Method method, final Object instance) { // this.method = method; // this.instance = instance; // } // // @Override // public void preDestroy() throws Exception { // method.invoke(instance); // } // } // // Path: src/main/java/ru/vyarus/guice/ext/managed/destroyable/DestroyableManager.java // public class DestroyableManager implements Runnable { // private final Logger logger = LoggerFactory.getLogger(DestroyableManager.class); // // private final List<Destroyable> destroyListeners = new ArrayList<>(); // // /** // * Register destroyable instance to be called on context shutdown. // * Not thread safe (assuming single thread injector initialization) // * // * @param destroyable destroyable instance // * @see ru.vyarus.guice.ext.managed.PostConstructAnnotationProcessor regsters annotated methods // * @see ru.vyarus.guice.ext.managed.DestroyableTypeProcessor registers beans anootated with {@code Destroyable} // */ // public void register(final Destroyable destroyable) { // // assuming single thread injector creation // destroyListeners.add(destroyable); // } // // /** // * Called on context shutdown to call all registered destroyable instances. // * By default called on jvm shutdown, but may be called manually to synchronise with // * some other container shutdown (e.g. web container) // * Safe to call many times, but all destroy instances will be processed only on first call. // * Thread safe. // */ // public void destroy() { // // just for the case // synchronized (this) { // for (Destroyable destroyable : destroyListeners) { // try { // destroyable.preDestroy(); // } catch (Exception ex) { // logger.error("Failed to properly destroy bean", ex); // } // } // destroyListeners.clear(); // } // } // // @Override // public void run() { // destroy(); // } // } // Path: src/main/java/ru/vyarus/guice/ext/managed/PreDestroyAnnotationProcessor.java import ru.vyarus.guice.ext.core.method.MethodPostProcessor; import ru.vyarus.guice.ext.core.util.Utils; import ru.vyarus.guice.ext.managed.destroyable.AnnotatedMethodDestroyable; import ru.vyarus.guice.ext.managed.destroyable.DestroyableManager; import javax.annotation.PreDestroy; import java.lang.reflect.Method; package ru.vyarus.guice.ext.managed; /** * Registers bean methods annotated with @PostConstruct in {@code DestroyableManager} to be called on shutdown. * * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PreDestroyAnnotationProcessor implements MethodPostProcessor<PreDestroy> { private final DestroyableManager manager; public PreDestroyAnnotationProcessor(final DestroyableManager manager) { this.manager = manager; } @Override public void process(final PreDestroy annotation, final Method method, final Object instance) throws Exception { Utils.checkNoParams(method);
manager.register(new AnnotatedMethodDestroyable(method, instance));
xvik/guice-ext-annotations
src/main/java/ru/vyarus/guice/ext/managed/PostConstructAnnotationProcessor.java
// Path: src/main/java/ru/vyarus/guice/ext/core/method/MethodPostProcessor.java // public interface MethodPostProcessor<T extends Annotation> { // // /** // * Called to post process annotated bean method. // * It is safe to avoid explicit exception handling (except special cases required by processor logic). // * // * @param annotation annotation instance // * @param method annotated method // * @param instance bean instance // * @throws Exception on any unrecoverable error // * @see ru.vyarus.guice.ext.core.method.AnnotatedMethodTypeListener // */ // void process(T annotation, Method method, Object instance) throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // }
import ru.vyarus.guice.ext.core.method.MethodPostProcessor; import ru.vyarus.guice.ext.core.util.Utils; import javax.annotation.PostConstruct; import java.lang.reflect.Method;
package ru.vyarus.guice.ext.managed; /** * Process bean @PostConstruct annotated methods: executes annotated method just after bean initialization. * * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PostConstructAnnotationProcessor implements MethodPostProcessor<PostConstruct> { @Override public void process(final PostConstruct annotation, final Method method, final Object instance) throws Exception {
// Path: src/main/java/ru/vyarus/guice/ext/core/method/MethodPostProcessor.java // public interface MethodPostProcessor<T extends Annotation> { // // /** // * Called to post process annotated bean method. // * It is safe to avoid explicit exception handling (except special cases required by processor logic). // * // * @param annotation annotation instance // * @param method annotated method // * @param instance bean instance // * @throws Exception on any unrecoverable error // * @see ru.vyarus.guice.ext.core.method.AnnotatedMethodTypeListener // */ // void process(T annotation, Method method, Object instance) throws Exception; // } // // Path: src/main/java/ru/vyarus/guice/ext/core/util/Utils.java // public final class Utils { // // private Utils() { // } // // /** // * Important check, because JDK proxies of public interfaces have no package // * (thanks to @binkley https://github.com/99soft/lifegycle/pull/5). // * // * @param type class type to check // * @return true if package could be resolved, false otherwise // */ // public static boolean isPackageValid(final Class type) { // boolean res = false; // if (type != null) { // final Package packaj = type.getPackage(); // res = !(packaj == null || packaj.getName().startsWith("java")); // } // return res; // } // // /** // * Checks that method has no parameters, otherwise throws exception. // * // * @param method method to check // */ // public static void checkNoParams(final Method method) { // if (method.getParameterTypes().length > 0) { // throw new IllegalStateException("Method without parameters required"); // } // } // // /** // * Note: versions below 1.8 are not supported. // * // * @return true if current java is 1.8, otherwise assumed 9 or above // */ // public static boolean isJava8() { // final String version = System.getProperty("java.version"); // return version.startsWith("1.8"); // } // } // Path: src/main/java/ru/vyarus/guice/ext/managed/PostConstructAnnotationProcessor.java import ru.vyarus.guice.ext.core.method.MethodPostProcessor; import ru.vyarus.guice.ext.core.util.Utils; import javax.annotation.PostConstruct; import java.lang.reflect.Method; package ru.vyarus.guice.ext.managed; /** * Process bean @PostConstruct annotated methods: executes annotated method just after bean initialization. * * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class PostConstructAnnotationProcessor implements MethodPostProcessor<PostConstruct> { @Override public void process(final PostConstruct annotation, final Method method, final Object instance) throws Exception {
Utils.checkNoParams(method);
remydb/Poke-A-Droid
Poke-A-Droid/src/main/java/com/os3/pokeadroid/MainActivity.java
// Path: opencv/sdk/java/src/org/opencv/android/OpenCVLoader.java // public class OpenCVLoader // { // /** // * OpenCV Library version 2.4.2. // */ // public static final String OPENCV_VERSION_2_4_2 = "2.4.2"; // // /** // * OpenCV Library version 2.4.3. // */ // public static final String OPENCV_VERSION_2_4_3 = "2.4.3"; // // /** // * OpenCV Library version 2.4.4. // */ // public static final String OPENCV_VERSION_2_4_4 = "2.4.4"; // // /** // * OpenCV Library version 2.4.5. // */ // public static final String OPENCV_VERSION_2_4_5 = "2.4.5"; // // // /** // * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java"). // * @return Returns true is initialization of OpenCV was successful. // */ // public static boolean initDebug() // { // return StaticHelper.initOpenCV(); // } // // /** // * Loads and initializes OpenCV library using OpenCV Engine service. // * @param Version OpenCV library version. // * @param AppContext application context for connecting to the service. // * @param Callback object, that implements LoaderCallbackInterface for handling the connection status. // * @return Returns true if initialization of OpenCV is successful. // */ // public static boolean initAsync(String Version, Context AppContext, // LoaderCallbackInterface Callback) // { // return AsyncServiceHelper.initOpenCV(Version, AppContext, Callback); // } // }
import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.*; import android.util.Log; import android.view.View; import android.widget.*; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.ShutterCallback; import android.app.Dialog; import android.view.View.OnClickListener; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; import java.io.*; import java.lang.Process; import java.util.Timer; import java.util.TimerTask;
@Override protected void onPause() { if (timerRuns == 1) { myTimer.cancel(); myTimer = new Timer(); } if (camera != null) { camera.release(); camera = null; } super.onPause(); } @Override protected void onStop() { if (timerRuns == 1) { myTimer.cancel(); myTimer = new Timer(); } if (camera != null) { camera.release(); camera = null; } super.onStop(); } @Override public void onResume() { super.onResume();
// Path: opencv/sdk/java/src/org/opencv/android/OpenCVLoader.java // public class OpenCVLoader // { // /** // * OpenCV Library version 2.4.2. // */ // public static final String OPENCV_VERSION_2_4_2 = "2.4.2"; // // /** // * OpenCV Library version 2.4.3. // */ // public static final String OPENCV_VERSION_2_4_3 = "2.4.3"; // // /** // * OpenCV Library version 2.4.4. // */ // public static final String OPENCV_VERSION_2_4_4 = "2.4.4"; // // /** // * OpenCV Library version 2.4.5. // */ // public static final String OPENCV_VERSION_2_4_5 = "2.4.5"; // // // /** // * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java"). // * @return Returns true is initialization of OpenCV was successful. // */ // public static boolean initDebug() // { // return StaticHelper.initOpenCV(); // } // // /** // * Loads and initializes OpenCV library using OpenCV Engine service. // * @param Version OpenCV library version. // * @param AppContext application context for connecting to the service. // * @param Callback object, that implements LoaderCallbackInterface for handling the connection status. // * @return Returns true if initialization of OpenCV is successful. // */ // public static boolean initAsync(String Version, Context AppContext, // LoaderCallbackInterface Callback) // { // return AsyncServiceHelper.initOpenCV(Version, AppContext, Callback); // } // } // Path: Poke-A-Droid/src/main/java/com/os3/pokeadroid/MainActivity.java import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.*; import android.util.Log; import android.view.View; import android.widget.*; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.ShutterCallback; import android.app.Dialog; import android.view.View.OnClickListener; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; import java.io.*; import java.lang.Process; import java.util.Timer; import java.util.TimerTask; @Override protected void onPause() { if (timerRuns == 1) { myTimer.cancel(); myTimer = new Timer(); } if (camera != null) { camera.release(); camera = null; } super.onPause(); } @Override protected void onStop() { if (timerRuns == 1) { myTimer.cancel(); myTimer = new Timer(); } if (camera != null) { camera.release(); camera = null; } super.onStop(); } @Override public void onResume() { super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java // public static final String DEFAULT_PREFIX = "/eureka";
import org.springframework.core.env.PropertyResolver; import org.springframework.util.StringUtils; import static org.springframework.cloud.netflix.eureka.EurekaConstants.DEFAULT_PREFIX; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import com.netflix.appinfo.EurekaAccept; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.core.Ordered;
/* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka; /** * Eureka client configuration bean. * * @author Dave Syer * @author Gregor Zurowski */ @ConfigurationProperties(EurekaClientConfigBean.PREFIX) public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { /** * Default prefix for Eureka client config properties. */ public static final String PREFIX = "eureka.client"; /** * Default Eureka URL. */
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java // public static final String DEFAULT_PREFIX = "/eureka"; // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java import org.springframework.core.env.PropertyResolver; import org.springframework.util.StringUtils; import static org.springframework.cloud.netflix.eureka.EurekaConstants.DEFAULT_PREFIX; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import com.netflix.appinfo.EurekaAccept; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.core.Ordered; /* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka; /** * Eureka client configuration bean. * * @author Dave Syer * @author Gregor Zurowski */ @ConfigurationProperties(EurekaClientConfigBean.PREFIX) public class EurekaClientConfigBean implements EurekaClientConfig, Ordered { /** * Default prefix for Eureka client config properties. */ public static final String PREFIX = "eureka.client"; /** * Default Eureka URL. */
public static final String DEFAULT_URL = "http://localhost:8761" + DEFAULT_PREFIX + "/";
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/EurekaLoadBalancerClientConfiguration.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/support/ZoneUtils.java // public final class ZoneUtils { // // private ZoneUtils() { // throw new AssertionError("Must not instantiate utility class."); // } // // /** // * Approximates Eureka zones from a host name. This method approximates the zone to be // * everything after the first "." in the host name. // * @param host The host name to extract the host name from // * @return The approximate zone // */ // public static String extractApproximateZone(String host) { // String[] split = StringUtils.split(host, "."); // return split == null ? host : split[1]; // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/LoadBalancerEurekaAutoConfiguration.java // public static final String LOADBALANCER_ZONE = "spring.cloud.loadbalancer.zone";
import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.discovery.EurekaClientConfig; import jakarta.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.cloud.loadbalancer.config.LoadBalancerZoneConfig; import org.springframework.cloud.netflix.eureka.support.ZoneUtils; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import static org.springframework.cloud.netflix.eureka.loadbalancer.LoadBalancerEurekaAutoConfiguration.LOADBALANCER_ZONE;
/* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.loadbalancer; /** * A configuration for Spring Cloud LoadBalancer that retrieves client instance zone from * Eureka and sets it as a property. Based on * {@link EurekaLoadBalancerClientConfiguration}. * * @author Olga Maciaszek-Sharma * @since 2.2.1 * @see EurekaLoadBalancerClientConfiguration */ @Configuration @ConditionalOnBean({ LoadBalancerZoneConfig.class, EurekaLoadBalancerProperties.class }) public class EurekaLoadBalancerClientConfiguration { private static final Log LOG = LogFactory.getLog(EurekaLoadBalancerClientConfiguration.class); private final EurekaClientConfig clientConfig; private final EurekaInstanceConfig eurekaConfig; private final LoadBalancerZoneConfig zoneConfig; private final EurekaLoadBalancerProperties eurekaLoadBalancerProperties; public EurekaLoadBalancerClientConfiguration(@Autowired(required = false) EurekaClientConfig clientConfig, @Autowired(required = false) EurekaInstanceConfig eurekaInstanceConfig, LoadBalancerZoneConfig zoneConfig, EurekaLoadBalancerProperties eurekaLoadBalancerProperties) { this.clientConfig = clientConfig; this.eurekaConfig = eurekaInstanceConfig; this.zoneConfig = zoneConfig; this.eurekaLoadBalancerProperties = eurekaLoadBalancerProperties; } @PostConstruct public void postprocess() { if (!StringUtils.isEmpty(zoneConfig.getZone())) { return; } String zone = getZoneFromEureka(); if (!StringUtils.isEmpty(zone)) { if (LOG.isDebugEnabled()) {
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/support/ZoneUtils.java // public final class ZoneUtils { // // private ZoneUtils() { // throw new AssertionError("Must not instantiate utility class."); // } // // /** // * Approximates Eureka zones from a host name. This method approximates the zone to be // * everything after the first "." in the host name. // * @param host The host name to extract the host name from // * @return The approximate zone // */ // public static String extractApproximateZone(String host) { // String[] split = StringUtils.split(host, "."); // return split == null ? host : split[1]; // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/LoadBalancerEurekaAutoConfiguration.java // public static final String LOADBALANCER_ZONE = "spring.cloud.loadbalancer.zone"; // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/EurekaLoadBalancerClientConfiguration.java import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.discovery.EurekaClientConfig; import jakarta.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.cloud.loadbalancer.config.LoadBalancerZoneConfig; import org.springframework.cloud.netflix.eureka.support.ZoneUtils; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import static org.springframework.cloud.netflix.eureka.loadbalancer.LoadBalancerEurekaAutoConfiguration.LOADBALANCER_ZONE; /* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.loadbalancer; /** * A configuration for Spring Cloud LoadBalancer that retrieves client instance zone from * Eureka and sets it as a property. Based on * {@link EurekaLoadBalancerClientConfiguration}. * * @author Olga Maciaszek-Sharma * @since 2.2.1 * @see EurekaLoadBalancerClientConfiguration */ @Configuration @ConditionalOnBean({ LoadBalancerZoneConfig.class, EurekaLoadBalancerProperties.class }) public class EurekaLoadBalancerClientConfiguration { private static final Log LOG = LogFactory.getLog(EurekaLoadBalancerClientConfiguration.class); private final EurekaClientConfig clientConfig; private final EurekaInstanceConfig eurekaConfig; private final LoadBalancerZoneConfig zoneConfig; private final EurekaLoadBalancerProperties eurekaLoadBalancerProperties; public EurekaLoadBalancerClientConfiguration(@Autowired(required = false) EurekaClientConfig clientConfig, @Autowired(required = false) EurekaInstanceConfig eurekaInstanceConfig, LoadBalancerZoneConfig zoneConfig, EurekaLoadBalancerProperties eurekaLoadBalancerProperties) { this.clientConfig = clientConfig; this.eurekaConfig = eurekaInstanceConfig; this.zoneConfig = zoneConfig; this.eurekaLoadBalancerProperties = eurekaLoadBalancerProperties; } @PostConstruct public void postprocess() { if (!StringUtils.isEmpty(zoneConfig.getZone())) { return; } String zone = getZoneFromEureka(); if (!StringUtils.isEmpty(zone)) { if (LOG.isDebugEnabled()) {
LOG.debug("Setting the value of '" + LOADBALANCER_ZONE + "' to " + zone);
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/EurekaLoadBalancerClientConfiguration.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/support/ZoneUtils.java // public final class ZoneUtils { // // private ZoneUtils() { // throw new AssertionError("Must not instantiate utility class."); // } // // /** // * Approximates Eureka zones from a host name. This method approximates the zone to be // * everything after the first "." in the host name. // * @param host The host name to extract the host name from // * @return The approximate zone // */ // public static String extractApproximateZone(String host) { // String[] split = StringUtils.split(host, "."); // return split == null ? host : split[1]; // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/LoadBalancerEurekaAutoConfiguration.java // public static final String LOADBALANCER_ZONE = "spring.cloud.loadbalancer.zone";
import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.discovery.EurekaClientConfig; import jakarta.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.cloud.loadbalancer.config.LoadBalancerZoneConfig; import org.springframework.cloud.netflix.eureka.support.ZoneUtils; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import static org.springframework.cloud.netflix.eureka.loadbalancer.LoadBalancerEurekaAutoConfiguration.LOADBALANCER_ZONE;
private final EurekaLoadBalancerProperties eurekaLoadBalancerProperties; public EurekaLoadBalancerClientConfiguration(@Autowired(required = false) EurekaClientConfig clientConfig, @Autowired(required = false) EurekaInstanceConfig eurekaInstanceConfig, LoadBalancerZoneConfig zoneConfig, EurekaLoadBalancerProperties eurekaLoadBalancerProperties) { this.clientConfig = clientConfig; this.eurekaConfig = eurekaInstanceConfig; this.zoneConfig = zoneConfig; this.eurekaLoadBalancerProperties = eurekaLoadBalancerProperties; } @PostConstruct public void postprocess() { if (!StringUtils.isEmpty(zoneConfig.getZone())) { return; } String zone = getZoneFromEureka(); if (!StringUtils.isEmpty(zone)) { if (LOG.isDebugEnabled()) { LOG.debug("Setting the value of '" + LOADBALANCER_ZONE + "' to " + zone); } zoneConfig.setZone(zone); } } private String getZoneFromEureka() { String zone; boolean approximateZoneFromHostname = eurekaLoadBalancerProperties.isApproximateZoneFromHostname(); if (approximateZoneFromHostname && eurekaConfig != null) {
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/support/ZoneUtils.java // public final class ZoneUtils { // // private ZoneUtils() { // throw new AssertionError("Must not instantiate utility class."); // } // // /** // * Approximates Eureka zones from a host name. This method approximates the zone to be // * everything after the first "." in the host name. // * @param host The host name to extract the host name from // * @return The approximate zone // */ // public static String extractApproximateZone(String host) { // String[] split = StringUtils.split(host, "."); // return split == null ? host : split[1]; // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/LoadBalancerEurekaAutoConfiguration.java // public static final String LOADBALANCER_ZONE = "spring.cloud.loadbalancer.zone"; // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/EurekaLoadBalancerClientConfiguration.java import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.discovery.EurekaClientConfig; import jakarta.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.cloud.loadbalancer.config.LoadBalancerZoneConfig; import org.springframework.cloud.netflix.eureka.support.ZoneUtils; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import static org.springframework.cloud.netflix.eureka.loadbalancer.LoadBalancerEurekaAutoConfiguration.LOADBALANCER_ZONE; private final EurekaLoadBalancerProperties eurekaLoadBalancerProperties; public EurekaLoadBalancerClientConfiguration(@Autowired(required = false) EurekaClientConfig clientConfig, @Autowired(required = false) EurekaInstanceConfig eurekaInstanceConfig, LoadBalancerZoneConfig zoneConfig, EurekaLoadBalancerProperties eurekaLoadBalancerProperties) { this.clientConfig = clientConfig; this.eurekaConfig = eurekaInstanceConfig; this.zoneConfig = zoneConfig; this.eurekaLoadBalancerProperties = eurekaLoadBalancerProperties; } @PostConstruct public void postprocess() { if (!StringUtils.isEmpty(zoneConfig.getZone())) { return; } String zone = getZoneFromEureka(); if (!StringUtils.isEmpty(zone)) { if (LOG.isDebugEnabled()) { LOG.debug("Setting the value of '" + LOADBALANCER_ZONE + "' to " + zone); } zoneConfig.setZone(zone); } } private String getZoneFromEureka() { String zone; boolean approximateZoneFromHostname = eurekaLoadBalancerProperties.isApproximateZoneFromHostname(); if (approximateZoneFromHostname && eurekaConfig != null) {
return ZoneUtils.extractApproximateZone(this.eurekaConfig.getHostName(false));
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationNoWebfluxTest.java
// Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // }
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import org.springframework.context.ConfigurableApplicationContext; import static org.assertj.core.api.AssertionsForClassTypes.fail; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
/* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*", "spring-webflux-*" })
// Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // } // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationNoWebfluxTest.java import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import org.springframework.context.ConfigurableApplicationContext; import static org.assertj.core.api.AssertionsForClassTypes.fail; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*", "spring-webflux-*" })
@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java // public final class EurekaConstants { // // /** // * Default Eureka prefix. // */ // public static final String DEFAULT_PREFIX = "/eureka"; // // private EurekaConstants() { // throw new AssertionError("Must not instantiate constant utility class"); // } // // }
import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.ws.rs.Path; import javax.ws.rs.core.Application; import javax.ws.rs.ext.Provider; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.converters.EurekaJacksonCodec; import com.netflix.discovery.converters.wrappers.CodecWrapper; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.eureka.DefaultEurekaServerContext; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; import com.netflix.eureka.transport.JerseyReplicationClient; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import jakarta.servlet.Filter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.cloud.client.actuator.HasFeatures; import org.springframework.cloud.context.environment.EnvironmentChangeEvent; import org.springframework.cloud.netflix.eureka.EurekaConstants; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.util.ClassUtils; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
* @param resourceLoader a {@link ResourceLoader} instance to get classloader from * @return created {@link Application} object */ @Bean public javax.ws.rs.core.Application jerseyApplication(Environment environment, ResourceLoader resourceLoader) { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false, environment); // Filter to include only classes that have a particular annotation. // provider.addIncludeFilter(new AnnotationTypeFilter(Path.class)); provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class)); // Find classes in Eureka packages (or subpackages) // Set<Class<?>> classes = new HashSet<>(); for (String basePackage : EUREKA_PACKAGES) { Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage); for (BeanDefinition bd : beans) { Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(), resourceLoader.getClassLoader()); classes.add(cls); } } // Construct the Jersey ResourceConfig Map<String, Object> propsAndFeatures = new HashMap<>(); propsAndFeatures.put( // Skip static content used by the webapp ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX,
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaConstants.java // public final class EurekaConstants { // // /** // * Default Eureka prefix. // */ // public static final String DEFAULT_PREFIX = "/eureka"; // // private EurekaConstants() { // throw new AssertionError("Must not instantiate constant utility class"); // } // // } // Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.ws.rs.Path; import javax.ws.rs.core.Application; import javax.ws.rs.ext.Provider; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.converters.EurekaJacksonCodec; import com.netflix.discovery.converters.wrappers.CodecWrapper; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.eureka.DefaultEurekaServerContext; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; import com.netflix.eureka.transport.JerseyReplicationClient; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import jakarta.servlet.Filter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.cloud.client.actuator.HasFeatures; import org.springframework.cloud.context.environment.EnvironmentChangeEvent; import org.springframework.cloud.netflix.eureka.EurekaConstants; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.util.ClassUtils; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * @param resourceLoader a {@link ResourceLoader} instance to get classloader from * @return created {@link Application} object */ @Bean public javax.ws.rs.core.Application jerseyApplication(Environment environment, ResourceLoader resourceLoader) { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false, environment); // Filter to include only classes that have a particular annotation. // provider.addIncludeFilter(new AnnotationTypeFilter(Path.class)); provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class)); // Find classes in Eureka packages (or subpackages) // Set<Class<?>> classes = new HashSet<>(); for (String basePackage : EUREKA_PACKAGES) { Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage); for (BeanDefinition bd : beans) { Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(), resourceLoader.getClassLoader()); classes.add(cls); } } // Construct the Jersey ResourceConfig Map<String, Object> propsAndFeatures = new HashMap<>(); propsAndFeatures.put( // Skip static content used by the webapp ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX,
EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*");
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesWithCustomFiltersTests.java
// Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java // static class RefreshablePeerEurekaNodes extends PeerEurekaNodes // implements ApplicationListener<EnvironmentChangeEvent> { // // private ReplicationClientAdditionalFilters replicationClientAdditionalFilters; // // RefreshablePeerEurekaNodes(final PeerAwareInstanceRegistry registry, final EurekaServerConfig serverConfig, // final EurekaClientConfig clientConfig, final ServerCodecs serverCodecs, // final ApplicationInfoManager applicationInfoManager, // final ReplicationClientAdditionalFilters replicationClientAdditionalFilters) { // super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); // this.replicationClientAdditionalFilters = replicationClientAdditionalFilters; // } // // @Override // protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) { // JerseyReplicationClient replicationClient = JerseyReplicationClient.createReplicationClient(serverConfig, // serverCodecs, peerEurekaNodeUrl); // // this.replicationClientAdditionalFilters.getFilters().forEach(replicationClient::addReplicationClientFilter); // // String targetHost = hostFromUrl(peerEurekaNodeUrl); // if (targetHost == null) { // targetHost = "host"; // } // return new PeerEurekaNode(registry, targetHost, peerEurekaNodeUrl, replicationClient, serverConfig); // } // // @Override // public void onApplicationEvent(final EnvironmentChangeEvent event) { // if (shouldUpdate(event.getKeys())) { // updatePeerEurekaNodes(resolvePeerUrls()); // } // } // // /* // * Check whether specific properties have changed. // */ // protected boolean shouldUpdate(final Set<String> changedKeys) { // assert changedKeys != null; // // // if eureka.client.use-dns-for-fetching-service-urls is true, then // // service-url will not be fetched from environment. // if (this.clientConfig.shouldUseDnsForFetchingServiceUrls()) { // return false; // } // // if (changedKeys.contains("eureka.client.region")) { // return true; // } // // for (final String key : changedKeys) { // // property keys are not expected to be null. // if (key.startsWith("eureka.client.service-url.") // || key.startsWith("eureka.client.availability-zones.")) { // return true; // } // } // return false; // } // // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Field; import java.util.Collections; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration.RefreshablePeerEurekaNodes;
/* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; /** * @author Yuxin Bai */ @SpringBootTest(classes = RefreshablePeerEurekaNodesWithCustomFiltersTests.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { "spring.application.name=eureka", "server.contextPath=/context", "management.security.enabled=false" }) class RefreshablePeerEurekaNodesWithCustomFiltersTests { @Autowired private PeerEurekaNodes peerEurekaNodes; @Test void testCustomPeerNodesShouldTakePrecedenceOverDefault() {
// Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerAutoConfiguration.java // static class RefreshablePeerEurekaNodes extends PeerEurekaNodes // implements ApplicationListener<EnvironmentChangeEvent> { // // private ReplicationClientAdditionalFilters replicationClientAdditionalFilters; // // RefreshablePeerEurekaNodes(final PeerAwareInstanceRegistry registry, final EurekaServerConfig serverConfig, // final EurekaClientConfig clientConfig, final ServerCodecs serverCodecs, // final ApplicationInfoManager applicationInfoManager, // final ReplicationClientAdditionalFilters replicationClientAdditionalFilters) { // super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); // this.replicationClientAdditionalFilters = replicationClientAdditionalFilters; // } // // @Override // protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) { // JerseyReplicationClient replicationClient = JerseyReplicationClient.createReplicationClient(serverConfig, // serverCodecs, peerEurekaNodeUrl); // // this.replicationClientAdditionalFilters.getFilters().forEach(replicationClient::addReplicationClientFilter); // // String targetHost = hostFromUrl(peerEurekaNodeUrl); // if (targetHost == null) { // targetHost = "host"; // } // return new PeerEurekaNode(registry, targetHost, peerEurekaNodeUrl, replicationClient, serverConfig); // } // // @Override // public void onApplicationEvent(final EnvironmentChangeEvent event) { // if (shouldUpdate(event.getKeys())) { // updatePeerEurekaNodes(resolvePeerUrls()); // } // } // // /* // * Check whether specific properties have changed. // */ // protected boolean shouldUpdate(final Set<String> changedKeys) { // assert changedKeys != null; // // // if eureka.client.use-dns-for-fetching-service-urls is true, then // // service-url will not be fetched from environment. // if (this.clientConfig.shouldUseDnsForFetchingServiceUrls()) { // return false; // } // // if (changedKeys.contains("eureka.client.region")) { // return true; // } // // for (final String key : changedKeys) { // // property keys are not expected to be null. // if (key.startsWith("eureka.client.service-url.") // || key.startsWith("eureka.client.availability-zones.")) { // return true; // } // } // return false; // } // // } // Path: spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/RefreshablePeerEurekaNodesWithCustomFiltersTests.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Field; import java.util.Collections; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration.RefreshablePeerEurekaNodes; /* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; /** * @author Yuxin Bai */ @SpringBootTest(classes = RefreshablePeerEurekaNodesWithCustomFiltersTests.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { "spring.application.name=eureka", "server.contextPath=/context", "management.security.enabled=false" }) class RefreshablePeerEurekaNodesWithCustomFiltersTests { @Autowired private PeerEurekaNodes peerEurekaNodes; @Test void testCustomPeerNodesShouldTakePrecedenceOverDefault() {
assertThat(peerEurekaNodes instanceof RefreshablePeerEurekaNodes)
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaConfigServerInstanceProvider.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaServiceInstance.java // public class EurekaServiceInstance implements ServiceInstance { // // private InstanceInfo instance; // // public EurekaServiceInstance(InstanceInfo instance) { // Assert.notNull(instance, "Service instance required"); // this.instance = instance; // } // // public InstanceInfo getInstanceInfo() { // return instance; // } // // @Override // public String getInstanceId() { // return this.instance.getId(); // } // // @Override // public String getServiceId() { // return this.instance.getAppName(); // } // // @Override // public String getHost() { // return this.instance.getHostName(); // } // // @Override // public int getPort() { // if (isSecure()) { // return this.instance.getSecurePort(); // } // return this.instance.getPort(); // } // // @Override // public boolean isSecure() { // // assume if secure is enabled, that is the default // return this.instance.isPortEnabled(SECURE); // } // // @Override // public URI getUri() { // return DefaultServiceInstance.getUri(this); // } // // @Override // public Map<String, String> getMetadata() { // return this.instance.getMetadata(); // } // // @Override // public String getScheme() { // return getUri().getScheme(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // EurekaServiceInstance that = (EurekaServiceInstance) o; // return Objects.equals(this.instance, that.instance); // } // // @Override // public int hashCode() { // return Objects.hash(this.instance); // } // // @Override // public String toString() { // return new ToStringCreator(this).append("instance", instance).toString(); // // } // // }
import java.util.ArrayList; import java.util.List; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.netflix.eureka.EurekaServiceInstance; import org.springframework.http.HttpStatus;
/* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; public class EurekaConfigServerInstanceProvider { private final Log log; private final EurekaHttpClient client; private final EurekaClientConfig config; public EurekaConfigServerInstanceProvider(EurekaHttpClient client, EurekaClientConfig config) { this(LogFactory.getLog(EurekaConfigServerInstanceProvider.class), client, config); } public EurekaConfigServerInstanceProvider(Log log, EurekaHttpClient client, EurekaClientConfig config) { this.log = log; this.client = client; this.config = config; } public List<ServiceInstance> getInstances(String serviceId) { if (log.isDebugEnabled()) { log.debug("eurekaConfigServerInstanceProvider finding instances for " + serviceId); } EurekaHttpResponse<Applications> response = client.getApplications(config.getRegion()); List<ServiceInstance> instances = new ArrayList<>(); if (!isSuccessful(response) || response.getEntity() == null) { return instances; } Applications applications = response.getEntity(); applications.shuffleInstances(config.shouldFilterOnlyUpInstances()); List<InstanceInfo> infos = applications.getInstancesByVirtualHostName(serviceId); for (InstanceInfo info : infos) {
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaServiceInstance.java // public class EurekaServiceInstance implements ServiceInstance { // // private InstanceInfo instance; // // public EurekaServiceInstance(InstanceInfo instance) { // Assert.notNull(instance, "Service instance required"); // this.instance = instance; // } // // public InstanceInfo getInstanceInfo() { // return instance; // } // // @Override // public String getInstanceId() { // return this.instance.getId(); // } // // @Override // public String getServiceId() { // return this.instance.getAppName(); // } // // @Override // public String getHost() { // return this.instance.getHostName(); // } // // @Override // public int getPort() { // if (isSecure()) { // return this.instance.getSecurePort(); // } // return this.instance.getPort(); // } // // @Override // public boolean isSecure() { // // assume if secure is enabled, that is the default // return this.instance.isPortEnabled(SECURE); // } // // @Override // public URI getUri() { // return DefaultServiceInstance.getUri(this); // } // // @Override // public Map<String, String> getMetadata() { // return this.instance.getMetadata(); // } // // @Override // public String getScheme() { // return getUri().getScheme(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // EurekaServiceInstance that = (EurekaServiceInstance) o; // return Objects.equals(this.instance, that.instance); // } // // @Override // public int hashCode() { // return Objects.hash(this.instance); // } // // @Override // public String toString() { // return new ToStringCreator(this).append("instance", instance).toString(); // // } // // } // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaConfigServerInstanceProvider.java import java.util.ArrayList; import java.util.List; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.netflix.eureka.EurekaServiceInstance; import org.springframework.http.HttpStatus; /* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; public class EurekaConfigServerInstanceProvider { private final Log log; private final EurekaHttpClient client; private final EurekaClientConfig config; public EurekaConfigServerInstanceProvider(EurekaHttpClient client, EurekaClientConfig config) { this(LogFactory.getLog(EurekaConfigServerInstanceProvider.class), client, config); } public EurekaConfigServerInstanceProvider(Log log, EurekaHttpClient client, EurekaClientConfig config) { this.log = log; this.client = client; this.config = config; } public List<ServiceInstance> getInstances(String serviceId) { if (log.isDebugEnabled()) { log.debug("eurekaConfigServerInstanceProvider finding instances for " + serviceId); } EurekaHttpResponse<Applications> response = client.getApplications(config.getRegion()); List<ServiceInstance> instances = new ArrayList<>(); if (!isSuccessful(response) || response.getEntity() == null) { return instances; } Applications applications = response.getEntity(); applications.shuffleInstances(config.shouldFilterOnlyUpInstances()); List<InstanceInfo> infos = applications.getInstancesByVirtualHostName(serviceId); for (InstanceInfo info : infos) {
instances.add(new EurekaServiceInstance(info));
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java
// Path: spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java // static void setInstance(ApplicationInfoManager infoManager) throws IllegalAccessException { // Field instance = ReflectionUtils.findField(ApplicationInfoManager.class, "instance"); // ReflectionUtils.makeAccessible(instance); // instance.set(null, infoManager); // }
import java.util.HashMap; import java.util.Map; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.eureka.util.StatusInfo; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.springframework.cloud.netflix.eureka.server.EurekaControllerTests.setInstance;
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; class EurekaControllerReplicasTests { String noAuthList1 = "https://test1.com"; String noAuthList2 = noAuthList1 + ",https://test2.com"; String authList1 = "https://user:pwd@test1.com"; String authList2 = authList1 + ",https://user2:pwd2@test2.com"; String combinationAuthList1 = "http://test1.com,http://user2:pwd2@test2.com"; String combinationAuthList2 = "http://test3.com,http://user4:pwd4@test4.com"; String combinationNoAuthList1 = "http://test1.com,http://test2.com"; String combinationNoAuthList2 = "http://test3.com,http://test4.com"; String totalAutoList = combinationAuthList1 + "," + combinationAuthList2; String totalNoAutoList = combinationNoAuthList1 + "," + combinationNoAuthList2; String empty = new String(); private ApplicationInfoManager original; private InstanceInfo instanceInfo; @BeforeEach void setup() throws Exception { this.original = ApplicationInfoManager.getInstance();
// Path: spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerTests.java // static void setInstance(ApplicationInfoManager infoManager) throws IllegalAccessException { // Field instance = ReflectionUtils.findField(ApplicationInfoManager.class, "instance"); // ReflectionUtils.makeAccessible(instance); // instance.set(null, infoManager); // } // Path: spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/EurekaControllerReplicasTests.java import java.util.HashMap; import java.util.Map; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.eureka.util.StatusInfo; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.springframework.cloud.netflix.eureka.server.EurekaControllerTests.setInstance; /* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; class EurekaControllerReplicasTests { String noAuthList1 = "https://test1.com"; String noAuthList2 = noAuthList1 + ",https://test2.com"; String authList1 = "https://user:pwd@test1.com"; String authList2 = authList1 + ",https://user2:pwd2@test2.com"; String combinationAuthList1 = "http://test1.com,http://user2:pwd2@test2.com"; String combinationAuthList2 = "http://test3.com,http://user4:pwd4@test4.com"; String combinationNoAuthList1 = "http://test1.com,http://test2.com"; String combinationNoAuthList2 = "http://test3.com,http://test4.com"; String totalAutoList = combinationAuthList1 + "," + combinationAuthList2; String totalNoAutoList = combinationNoAuthList1 + "," + combinationNoAuthList2; String empty = new String(); private ApplicationInfoManager original; private InstanceInfo instanceInfo; @BeforeEach void setup() throws Exception { this.original = ApplicationInfoManager.getInstance();
setInstance(mock(ApplicationInfoManager.class));
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java // public class EurekaAutoServiceRegistration // implements AutoServiceRegistration, SmartLifecycle, Ordered, SmartApplicationListener { // // private static final Log log = LogFactory.getLog(EurekaAutoServiceRegistration.class); // // private AtomicBoolean running = new AtomicBoolean(false); // // private int order = 0; // // private AtomicInteger port = new AtomicInteger(0); // // private ApplicationContext context; // // private EurekaServiceRegistry serviceRegistry; // // private EurekaRegistration registration; // // public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry, // EurekaRegistration registration) { // this.context = context; // this.serviceRegistry = serviceRegistry; // this.registration = registration; // } // // @Override // public void start() { // // only set the port if the nonSecurePort or securePort is 0 and this.port != 0 // if (this.port.get() != 0) { // if (this.registration.getNonSecurePort() == 0) { // this.registration.setNonSecurePort(this.port.get()); // } // // if (this.registration.getSecurePort() == 0 && this.registration.isSecure()) { // this.registration.setSecurePort(this.port.get()); // } // } // // // only initialize if nonSecurePort is greater than 0 and it isn't already running // // because of containerPortInitializer below // if (!this.running.get() && this.registration.getNonSecurePort() > 0) { // // this.serviceRegistry.register(this.registration); // // this.context.publishEvent(new InstanceRegisteredEvent<>(this, this.registration.getInstanceConfig())); // this.running.set(true); // } // } // // @Override // public void stop() { // this.serviceRegistry.deregister(this.registration); // this.running.set(false); // } // // @Override // public boolean isRunning() { // return this.running.get(); // } // // @Override // public int getPhase() { // return 0; // } // // @Override // public boolean isAutoStartup() { // return true; // } // // @Override // public void stop(Runnable callback) { // stop(); // callback.run(); // } // // @Override // public int getOrder() { // return this.order; // } // // @Override // public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { // return WebServerInitializedEvent.class.isAssignableFrom(eventType) // || ContextClosedEvent.class.isAssignableFrom(eventType); // } // // @Override // public void onApplicationEvent(ApplicationEvent event) { // if (event instanceof WebServerInitializedEvent) { // onApplicationEvent((WebServerInitializedEvent) event); // } // else if (event instanceof ContextClosedEvent) { // onApplicationEvent((ContextClosedEvent) event); // } // } // // public void onApplicationEvent(WebServerInitializedEvent event) { // // TODO: take SSL into account // String contextName = event.getApplicationContext().getServerNamespace(); // if (contextName == null || !contextName.equals("management")) { // int localPort = event.getWebServer().getPort(); // if (this.port.get() == 0) { // log.info("Updating port to " + localPort); // this.port.compareAndSet(0, localPort); // start(); // } // } // } // // public void onApplicationEvent(ContextClosedEvent event) { // if (event.getApplicationContext() == context) { // stop(); // } // } // // }
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.SimpleStatusAggregator; import org.springframework.boot.actuate.health.StatusAggregator; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
@Bean @ConditionalOnMissingBean public EurekaDiscoveryClient discoveryClient(EurekaClient client, EurekaClientConfig clientConfig) { return new EurekaDiscoveryClient(client, clientConfig); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "eureka.client.healthcheck.enabled", matchIfMissing = false) protected static class EurekaHealthCheckHandlerConfiguration { @Autowired(required = false) private StatusAggregator statusAggregator = new SimpleStatusAggregator(); @Bean @ConditionalOnMissingBean(HealthCheckHandler.class) public EurekaHealthCheckHandler eurekaHealthCheckHandler() { return new EurekaHealthCheckHandler(this.statusAggregator); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(RefreshScopeRefreshedEvent.class) protected static class EurekaClientConfigurationRefresher implements ApplicationListener<RefreshScopeRefreshedEvent> { @Autowired(required = false) private EurekaClient eurekaClient; @Autowired(required = false)
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java // public class EurekaAutoServiceRegistration // implements AutoServiceRegistration, SmartLifecycle, Ordered, SmartApplicationListener { // // private static final Log log = LogFactory.getLog(EurekaAutoServiceRegistration.class); // // private AtomicBoolean running = new AtomicBoolean(false); // // private int order = 0; // // private AtomicInteger port = new AtomicInteger(0); // // private ApplicationContext context; // // private EurekaServiceRegistry serviceRegistry; // // private EurekaRegistration registration; // // public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry, // EurekaRegistration registration) { // this.context = context; // this.serviceRegistry = serviceRegistry; // this.registration = registration; // } // // @Override // public void start() { // // only set the port if the nonSecurePort or securePort is 0 and this.port != 0 // if (this.port.get() != 0) { // if (this.registration.getNonSecurePort() == 0) { // this.registration.setNonSecurePort(this.port.get()); // } // // if (this.registration.getSecurePort() == 0 && this.registration.isSecure()) { // this.registration.setSecurePort(this.port.get()); // } // } // // // only initialize if nonSecurePort is greater than 0 and it isn't already running // // because of containerPortInitializer below // if (!this.running.get() && this.registration.getNonSecurePort() > 0) { // // this.serviceRegistry.register(this.registration); // // this.context.publishEvent(new InstanceRegisteredEvent<>(this, this.registration.getInstanceConfig())); // this.running.set(true); // } // } // // @Override // public void stop() { // this.serviceRegistry.deregister(this.registration); // this.running.set(false); // } // // @Override // public boolean isRunning() { // return this.running.get(); // } // // @Override // public int getPhase() { // return 0; // } // // @Override // public boolean isAutoStartup() { // return true; // } // // @Override // public void stop(Runnable callback) { // stop(); // callback.run(); // } // // @Override // public int getOrder() { // return this.order; // } // // @Override // public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { // return WebServerInitializedEvent.class.isAssignableFrom(eventType) // || ContextClosedEvent.class.isAssignableFrom(eventType); // } // // @Override // public void onApplicationEvent(ApplicationEvent event) { // if (event instanceof WebServerInitializedEvent) { // onApplicationEvent((WebServerInitializedEvent) event); // } // else if (event instanceof ContextClosedEvent) { // onApplicationEvent((ContextClosedEvent) event); // } // } // // public void onApplicationEvent(WebServerInitializedEvent event) { // // TODO: take SSL into account // String contextName = event.getApplicationContext().getServerNamespace(); // if (contextName == null || !contextName.equals("management")) { // int localPort = event.getWebServer().getPort(); // if (this.port.get() == 0) { // log.info("Updating port to " + localPort); // this.port.compareAndSet(0, localPort); // start(); // } // } // } // // public void onApplicationEvent(ContextClosedEvent event) { // if (event.getApplicationContext() == context) { // stop(); // } // } // // } // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.SimpleStatusAggregator; import org.springframework.boot.actuate.health.StatusAggregator; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent; @Bean @ConditionalOnMissingBean public EurekaDiscoveryClient discoveryClient(EurekaClient client, EurekaClientConfig clientConfig) { return new EurekaDiscoveryClient(client, clientConfig); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "eureka.client.healthcheck.enabled", matchIfMissing = false) protected static class EurekaHealthCheckHandlerConfiguration { @Autowired(required = false) private StatusAggregator statusAggregator = new SimpleStatusAggregator(); @Bean @ConditionalOnMissingBean(HealthCheckHandler.class) public EurekaHealthCheckHandler eurekaHealthCheckHandler() { return new EurekaHealthCheckHandler(this.statusAggregator); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(RefreshScopeRefreshedEvent.class) protected static class EurekaClientConfigurationRefresher implements ApplicationListener<RefreshScopeRefreshedEvent> { @Autowired(required = false) private EurekaClient eurekaClient; @Autowired(required = false)
private EurekaAutoServiceRegistration autoRegistration;
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java
// Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java // @SuppressWarnings("serial") // public class EurekaRegistryAvailableEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaRegistryAvailableEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // } // // Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java // @SuppressWarnings("serial") // public class EurekaServerStartedEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaServerStartedEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // }
import com.netflix.eureka.EurekaServerConfig; import jakarta.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent; import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.SmartLifecycle; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.context.ServletContextAware;
/* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; /** * @author Dave Syer */ @Configuration(proxyBeanMethods = false) public class EurekaServerInitializerConfiguration implements ServletContextAware, SmartLifecycle, Ordered { private static final Log log = LogFactory.getLog(EurekaServerInitializerConfiguration.class); @Autowired private EurekaServerConfig eurekaServerConfig; private ServletContext servletContext; @Autowired private ApplicationContext applicationContext; @Autowired private EurekaServerBootstrap eurekaServerBootstrap; private boolean running; private int order = 1; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void start() { new Thread(() -> { try { // TODO: is this class even needed now? eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext); log.info("Started Eureka Server");
// Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java // @SuppressWarnings("serial") // public class EurekaRegistryAvailableEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaRegistryAvailableEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // } // // Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java // @SuppressWarnings("serial") // public class EurekaServerStartedEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaServerStartedEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // } // Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java import com.netflix.eureka.EurekaServerConfig; import jakarta.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent; import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.SmartLifecycle; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.context.ServletContextAware; /* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; /** * @author Dave Syer */ @Configuration(proxyBeanMethods = false) public class EurekaServerInitializerConfiguration implements ServletContextAware, SmartLifecycle, Ordered { private static final Log log = LogFactory.getLog(EurekaServerInitializerConfiguration.class); @Autowired private EurekaServerConfig eurekaServerConfig; private ServletContext servletContext; @Autowired private ApplicationContext applicationContext; @Autowired private EurekaServerBootstrap eurekaServerBootstrap; private boolean running; private int order = 1; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void start() { new Thread(() -> { try { // TODO: is this class even needed now? eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext); log.info("Started Eureka Server");
publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig()));
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java
// Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java // @SuppressWarnings("serial") // public class EurekaRegistryAvailableEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaRegistryAvailableEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // } // // Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java // @SuppressWarnings("serial") // public class EurekaServerStartedEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaServerStartedEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // }
import com.netflix.eureka.EurekaServerConfig; import jakarta.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent; import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.SmartLifecycle; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.context.ServletContextAware;
/* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; /** * @author Dave Syer */ @Configuration(proxyBeanMethods = false) public class EurekaServerInitializerConfiguration implements ServletContextAware, SmartLifecycle, Ordered { private static final Log log = LogFactory.getLog(EurekaServerInitializerConfiguration.class); @Autowired private EurekaServerConfig eurekaServerConfig; private ServletContext servletContext; @Autowired private ApplicationContext applicationContext; @Autowired private EurekaServerBootstrap eurekaServerBootstrap; private boolean running; private int order = 1; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void start() { new Thread(() -> { try { // TODO: is this class even needed now? eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext); log.info("Started Eureka Server"); publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig())); EurekaServerInitializerConfiguration.this.running = true;
// Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaRegistryAvailableEvent.java // @SuppressWarnings("serial") // public class EurekaRegistryAvailableEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaRegistryAvailableEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // } // // Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaServerStartedEvent.java // @SuppressWarnings("serial") // public class EurekaServerStartedEvent extends ApplicationEvent { // // /** // * @param eurekaServerConfig {@link EurekaServerConfig} event source // */ // public EurekaServerStartedEvent(EurekaServerConfig eurekaServerConfig) { // super(eurekaServerConfig); // } // // } // Path: spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java import com.netflix.eureka.EurekaServerConfig; import jakarta.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent; import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.SmartLifecycle; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.context.ServletContextAware; /* * Copyright 2013-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; /** * @author Dave Syer */ @Configuration(proxyBeanMethods = false) public class EurekaServerInitializerConfiguration implements ServletContextAware, SmartLifecycle, Ordered { private static final Log log = LogFactory.getLog(EurekaServerInitializerConfiguration.class); @Autowired private EurekaServerConfig eurekaServerConfig; private ServletContext servletContext; @Autowired private ApplicationContext applicationContext; @Autowired private EurekaServerBootstrap eurekaServerBootstrap; private boolean running; private int order = 1; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void start() { new Thread(() -> { try { // TODO: is this class even needed now? eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext); log.info("Started Eureka Server"); publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig())); EurekaServerInitializerConfiguration.this.running = true;
publish(new EurekaServerStartedEvent(getEurekaServerConfig()));
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationTest.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java // public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // protected final EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier; // // public RestTemplateDiscoveryClientOptionalArgs( // EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) { // this.eurekaClientHttpRequestFactorySupplier = eurekaClientHttpRequestFactorySupplier; // setTransportClientFactories(new RestTemplateTransportClientFactories(this)); // } // // /** // * @deprecated - use // * {@link RestTemplateDiscoveryClientOptionalArgs#RestTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier)} // */ // @Deprecated // public RestTemplateDiscoveryClientOptionalArgs() { // this(new DefaultEurekaClientHttpRequestFactorySupplier()); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientDiscoveryClientOptionalArgs.java // public class WebClientDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // public WebClientDiscoveryClientOptionalArgs(Supplier<WebClient.Builder> builder) { // setTransportClientFactories(new WebClientTransportClientFactories(builder)); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
/* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" })
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java // public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // protected final EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier; // // public RestTemplateDiscoveryClientOptionalArgs( // EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) { // this.eurekaClientHttpRequestFactorySupplier = eurekaClientHttpRequestFactorySupplier; // setTransportClientFactories(new RestTemplateTransportClientFactories(this)); // } // // /** // * @deprecated - use // * {@link RestTemplateDiscoveryClientOptionalArgs#RestTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier)} // */ // @Deprecated // public RestTemplateDiscoveryClientOptionalArgs() { // this(new DefaultEurekaClientHttpRequestFactorySupplier()); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientDiscoveryClientOptionalArgs.java // public class WebClientDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // public WebClientDiscoveryClientOptionalArgs(Supplier<WebClient.Builder> builder) { // setTransportClientFactories(new WebClientTransportClientFactories(builder)); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // } // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" })
@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationTest.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java // public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // protected final EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier; // // public RestTemplateDiscoveryClientOptionalArgs( // EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) { // this.eurekaClientHttpRequestFactorySupplier = eurekaClientHttpRequestFactorySupplier; // setTransportClientFactories(new RestTemplateTransportClientFactories(this)); // } // // /** // * @deprecated - use // * {@link RestTemplateDiscoveryClientOptionalArgs#RestTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier)} // */ // @Deprecated // public RestTemplateDiscoveryClientOptionalArgs() { // this(new DefaultEurekaClientHttpRequestFactorySupplier()); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientDiscoveryClientOptionalArgs.java // public class WebClientDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // public WebClientDiscoveryClientOptionalArgs(Supplier<WebClient.Builder> builder) { // setTransportClientFactories(new WebClientTransportClientFactories(builder)); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
/* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" }) @SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class EurekaHttpClientsOptionalArgsConfigurationTest { @Test public void contextLoadsWithRestTemplate() { new WebApplicationContextRunner().withUserConfiguration(EurekaSampleApplication.class) .withPropertyValues("eureka.client.webclient.enabled=false").run(context -> {
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java // public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // protected final EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier; // // public RestTemplateDiscoveryClientOptionalArgs( // EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) { // this.eurekaClientHttpRequestFactorySupplier = eurekaClientHttpRequestFactorySupplier; // setTransportClientFactories(new RestTemplateTransportClientFactories(this)); // } // // /** // * @deprecated - use // * {@link RestTemplateDiscoveryClientOptionalArgs#RestTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier)} // */ // @Deprecated // public RestTemplateDiscoveryClientOptionalArgs() { // this(new DefaultEurekaClientHttpRequestFactorySupplier()); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientDiscoveryClientOptionalArgs.java // public class WebClientDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // public WebClientDiscoveryClientOptionalArgs(Supplier<WebClient.Builder> builder) { // setTransportClientFactories(new WebClientTransportClientFactories(builder)); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // } // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" }) @SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class EurekaHttpClientsOptionalArgsConfigurationTest { @Test public void contextLoadsWithRestTemplate() { new WebApplicationContextRunner().withUserConfiguration(EurekaSampleApplication.class) .withPropertyValues("eureka.client.webclient.enabled=false").run(context -> {
assertThat(context).hasSingleBean(RestTemplateDiscoveryClientOptionalArgs.class);
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationTest.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java // public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // protected final EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier; // // public RestTemplateDiscoveryClientOptionalArgs( // EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) { // this.eurekaClientHttpRequestFactorySupplier = eurekaClientHttpRequestFactorySupplier; // setTransportClientFactories(new RestTemplateTransportClientFactories(this)); // } // // /** // * @deprecated - use // * {@link RestTemplateDiscoveryClientOptionalArgs#RestTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier)} // */ // @Deprecated // public RestTemplateDiscoveryClientOptionalArgs() { // this(new DefaultEurekaClientHttpRequestFactorySupplier()); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientDiscoveryClientOptionalArgs.java // public class WebClientDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // public WebClientDiscoveryClientOptionalArgs(Supplier<WebClient.Builder> builder) { // setTransportClientFactories(new WebClientTransportClientFactories(builder)); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
/* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" }) @SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class EurekaHttpClientsOptionalArgsConfigurationTest { @Test public void contextLoadsWithRestTemplate() { new WebApplicationContextRunner().withUserConfiguration(EurekaSampleApplication.class) .withPropertyValues("eureka.client.webclient.enabled=false").run(context -> { assertThat(context).hasSingleBean(RestTemplateDiscoveryClientOptionalArgs.class);
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateDiscoveryClientOptionalArgs.java // public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // protected final EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier; // // public RestTemplateDiscoveryClientOptionalArgs( // EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) { // this.eurekaClientHttpRequestFactorySupplier = eurekaClientHttpRequestFactorySupplier; // setTransportClientFactories(new RestTemplateTransportClientFactories(this)); // } // // /** // * @deprecated - use // * {@link RestTemplateDiscoveryClientOptionalArgs#RestTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier)} // */ // @Deprecated // public RestTemplateDiscoveryClientOptionalArgs() { // this(new DefaultEurekaClientHttpRequestFactorySupplier()); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientDiscoveryClientOptionalArgs.java // public class WebClientDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> { // // public WebClientDiscoveryClientOptionalArgs(Supplier<WebClient.Builder> builder) { // setTransportClientFactories(new WebClientTransportClientFactories(builder)); // } // // } // // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/EurekaSampleApplication.java // @Configuration(proxyBeanMethods = false) // @ComponentScan // @EnableAutoConfiguration // @RestController // public class EurekaSampleApplication implements ApplicationContextAware, Closeable { // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ServiceRegistry<EurekaRegistration> serviceRegistry; // // @Autowired // private InetUtils inetUtils; // // @Autowired // private EurekaClientConfigBean clientConfig; // // private ApplicationContext context; // // private EurekaRegistration registration; // // @Bean // public HealthCheckHandler healthCheckHandler() { // return currentStatus -> InstanceInfo.InstanceStatus.UP; // } // // @RequestMapping("/") // public String home() { // return "Hello world " + registration.getUri(); // } // // @Override // public void setApplicationContext(ApplicationContext context) throws BeansException { // this.context = context; // } // // @RequestMapping(path = "/register", method = POST) // public String register() { // EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(inetUtils); // String appname = "customapp"; // config.setIpAddress("127.0.0.1"); // config.setHostname("localhost"); // config.setAppname(appname); // config.setVirtualHostName(appname); // config.setSecureVirtualHostName(appname); // config.setNonSecurePort(4444); // config.setInstanceId("127.0.0.1:customapp:4444"); // // this.registration = EurekaRegistration.builder(config).with(this.clientConfig, this.context).build(); // // this.serviceRegistry.register(this.registration); // return config.getInstanceId(); // } // // @RequestMapping(path = "/deregister", method = POST) // public String deregister() { // this.serviceRegistry.deregister(this.registration); // return "deregister"; // } // // @Override // public void close() throws IOException { // deregister(); // } // // } // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/config/EurekaHttpClientsOptionalArgsConfigurationTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs; import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.config; /** * @author Daniel Lavoie */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" }) @SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class EurekaHttpClientsOptionalArgsConfigurationTest { @Test public void contextLoadsWithRestTemplate() { new WebApplicationContextRunner().withUserConfiguration(EurekaSampleApplication.class) .withPropertyValues("eureka.client.webclient.enabled=false").run(context -> { assertThat(context).hasSingleBean(RestTemplateDiscoveryClientOptionalArgs.class);
assertThat(context).doesNotHaveBean(WebClientDiscoveryClientOptionalArgs.class);
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/reactive/EurekaReactiveDiscoveryClient.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaServiceInstance.java // public class EurekaServiceInstance implements ServiceInstance { // // private InstanceInfo instance; // // public EurekaServiceInstance(InstanceInfo instance) { // Assert.notNull(instance, "Service instance required"); // this.instance = instance; // } // // public InstanceInfo getInstanceInfo() { // return instance; // } // // @Override // public String getInstanceId() { // return this.instance.getId(); // } // // @Override // public String getServiceId() { // return this.instance.getAppName(); // } // // @Override // public String getHost() { // return this.instance.getHostName(); // } // // @Override // public int getPort() { // if (isSecure()) { // return this.instance.getSecurePort(); // } // return this.instance.getPort(); // } // // @Override // public boolean isSecure() { // // assume if secure is enabled, that is the default // return this.instance.isPortEnabled(SECURE); // } // // @Override // public URI getUri() { // return DefaultServiceInstance.getUri(this); // } // // @Override // public Map<String, String> getMetadata() { // return this.instance.getMetadata(); // } // // @Override // public String getScheme() { // return getUri().getScheme(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // EurekaServiceInstance that = (EurekaServiceInstance) o; // return Objects.equals(this.instance, that.instance); // } // // @Override // public int hashCode() { // return Objects.hash(this.instance); // } // // @Override // public String toString() { // return new ToStringCreator(this).append("instance", instance).toString(); // // } // // }
import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.netflix.eureka.EurekaServiceInstance; import org.springframework.core.Ordered;
/* * Copyright 2019-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.reactive; /** * A {@link ReactiveDiscoveryClient} implementation for Eureka. * * @author Tim Ysewyn */ public class EurekaReactiveDiscoveryClient implements ReactiveDiscoveryClient { private final EurekaClient eurekaClient; private final EurekaClientConfig clientConfig; public EurekaReactiveDiscoveryClient(EurekaClient eurekaClient, EurekaClientConfig clientConfig) { this.eurekaClient = eurekaClient; this.clientConfig = clientConfig; } @Override public String description() { return "Spring Cloud Eureka Reactive Discovery Client"; } @Override public Flux<ServiceInstance> getInstances(String serviceId) { return Flux.defer(() -> Flux.fromIterable(eurekaClient.getInstancesByVipAddress(serviceId, false)))
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaServiceInstance.java // public class EurekaServiceInstance implements ServiceInstance { // // private InstanceInfo instance; // // public EurekaServiceInstance(InstanceInfo instance) { // Assert.notNull(instance, "Service instance required"); // this.instance = instance; // } // // public InstanceInfo getInstanceInfo() { // return instance; // } // // @Override // public String getInstanceId() { // return this.instance.getId(); // } // // @Override // public String getServiceId() { // return this.instance.getAppName(); // } // // @Override // public String getHost() { // return this.instance.getHostName(); // } // // @Override // public int getPort() { // if (isSecure()) { // return this.instance.getSecurePort(); // } // return this.instance.getPort(); // } // // @Override // public boolean isSecure() { // // assume if secure is enabled, that is the default // return this.instance.isPortEnabled(SECURE); // } // // @Override // public URI getUri() { // return DefaultServiceInstance.getUri(this); // } // // @Override // public Map<String, String> getMetadata() { // return this.instance.getMetadata(); // } // // @Override // public String getScheme() { // return getUri().getScheme(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // EurekaServiceInstance that = (EurekaServiceInstance) o; // return Objects.equals(this.instance, that.instance); // } // // @Override // public int hashCode() { // return Objects.hash(this.instance); // } // // @Override // public String toString() { // return new ToStringCreator(this).append("instance", instance).toString(); // // } // // } // Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/reactive/EurekaReactiveDiscoveryClient.java import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.netflix.eureka.EurekaServiceInstance; import org.springframework.core.Ordered; /* * Copyright 2019-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.reactive; /** * A {@link ReactiveDiscoveryClient} implementation for Eureka. * * @author Tim Ysewyn */ public class EurekaReactiveDiscoveryClient implements ReactiveDiscoveryClient { private final EurekaClient eurekaClient; private final EurekaClientConfig clientConfig; public EurekaReactiveDiscoveryClient(EurekaClient eurekaClient, EurekaClientConfig clientConfig) { this.eurekaClient = eurekaClient; this.clientConfig = clientConfig; } @Override public String description() { return "Spring Cloud Eureka Reactive Discovery Client"; } @Override public Flux<ServiceInstance> getInstances(String serviceId) { return Flux.defer(() -> Flux.fromIterable(eurekaClient.getInstancesByVipAddress(serviceId, false)))
.map(EurekaServiceInstance::new);
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java // public class CloudEurekaClient extends DiscoveryClient { // // private static final Log log = LogFactory.getLog(CloudEurekaClient.class); // // private final AtomicLong cacheRefreshedCount = new AtomicLong(0); // // private ApplicationEventPublisher publisher; // // private Field eurekaTransportField; // // private ApplicationInfoManager applicationInfoManager; // // private AtomicReference<EurekaHttpClient> eurekaHttpClient = new AtomicReference<>(); // // public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, // ApplicationEventPublisher publisher) { // this(applicationInfoManager, config, null, publisher); // } // // public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, // AbstractDiscoveryClientOptionalArgs<?> args, ApplicationEventPublisher publisher) { // super(applicationInfoManager, config, args); // this.applicationInfoManager = applicationInfoManager; // this.publisher = publisher; // this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport"); // ReflectionUtils.makeAccessible(this.eurekaTransportField); // } // // public ApplicationInfoManager getApplicationInfoManager() { // return applicationInfoManager; // } // // public void cancelOverrideStatus(InstanceInfo info) { // getEurekaHttpClient().deleteStatusOverride(info.getAppName(), info.getId(), info); // } // // public InstanceInfo getInstanceInfo(String appname, String instanceId) { // EurekaHttpResponse<InstanceInfo> response = getEurekaHttpClient().getInstance(appname, instanceId); // HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusCode()); // if (httpStatus.is2xxSuccessful() && response.getEntity() != null) { // return response.getEntity(); // } // return null; // } // // EurekaHttpClient getEurekaHttpClient() { // if (this.eurekaHttpClient.get() == null) { // try { // Object eurekaTransport = this.eurekaTransportField.get(this); // Field registrationClientField = ReflectionUtils.findField(eurekaTransport.getClass(), // "registrationClient"); // ReflectionUtils.makeAccessible(registrationClientField); // this.eurekaHttpClient.compareAndSet(null, // (EurekaHttpClient) registrationClientField.get(eurekaTransport)); // } // catch (IllegalAccessException e) { // log.error("error getting EurekaHttpClient", e); // } // } // return this.eurekaHttpClient.get(); // } // // public void setStatus(InstanceStatus newStatus, InstanceInfo info) { // getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus, info); // } // // @Override // protected void onCacheRefreshed() { // super.onCacheRefreshed(); // // if (this.cacheRefreshedCount != null) { // might be called during construction and // // will be null // long newCount = this.cacheRefreshedCount.incrementAndGet(); // log.trace("onCacheRefreshed called with count: " + newCount); // this.publisher.publishEvent(new HeartbeatEvent(this, newCount)); // } // } // // }
import com.netflix.discovery.EurekaClient; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.netflix.eureka.CloudEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.RestController; import static org.mockito.Mockito.mock;
/* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.sample; /** * @author Ryan Baxter */ @SpringBootConfiguration(proxyBeanMethods = false) @EnableAutoConfiguration @RestController public class RefreshEurekaSampleApplication { @Bean public EurekaClient getClient() {
// Path: spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java // public class CloudEurekaClient extends DiscoveryClient { // // private static final Log log = LogFactory.getLog(CloudEurekaClient.class); // // private final AtomicLong cacheRefreshedCount = new AtomicLong(0); // // private ApplicationEventPublisher publisher; // // private Field eurekaTransportField; // // private ApplicationInfoManager applicationInfoManager; // // private AtomicReference<EurekaHttpClient> eurekaHttpClient = new AtomicReference<>(); // // public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, // ApplicationEventPublisher publisher) { // this(applicationInfoManager, config, null, publisher); // } // // public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, // AbstractDiscoveryClientOptionalArgs<?> args, ApplicationEventPublisher publisher) { // super(applicationInfoManager, config, args); // this.applicationInfoManager = applicationInfoManager; // this.publisher = publisher; // this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport"); // ReflectionUtils.makeAccessible(this.eurekaTransportField); // } // // public ApplicationInfoManager getApplicationInfoManager() { // return applicationInfoManager; // } // // public void cancelOverrideStatus(InstanceInfo info) { // getEurekaHttpClient().deleteStatusOverride(info.getAppName(), info.getId(), info); // } // // public InstanceInfo getInstanceInfo(String appname, String instanceId) { // EurekaHttpResponse<InstanceInfo> response = getEurekaHttpClient().getInstance(appname, instanceId); // HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusCode()); // if (httpStatus.is2xxSuccessful() && response.getEntity() != null) { // return response.getEntity(); // } // return null; // } // // EurekaHttpClient getEurekaHttpClient() { // if (this.eurekaHttpClient.get() == null) { // try { // Object eurekaTransport = this.eurekaTransportField.get(this); // Field registrationClientField = ReflectionUtils.findField(eurekaTransport.getClass(), // "registrationClient"); // ReflectionUtils.makeAccessible(registrationClientField); // this.eurekaHttpClient.compareAndSet(null, // (EurekaHttpClient) registrationClientField.get(eurekaTransport)); // } // catch (IllegalAccessException e) { // log.error("error getting EurekaHttpClient", e); // } // } // return this.eurekaHttpClient.get(); // } // // public void setStatus(InstanceStatus newStatus, InstanceInfo info) { // getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus, info); // } // // @Override // protected void onCacheRefreshed() { // super.onCacheRefreshed(); // // if (this.cacheRefreshedCount != null) { // might be called during construction and // // will be null // long newCount = this.cacheRefreshedCount.incrementAndGet(); // log.trace("onCacheRefreshed called with count: " + newCount); // this.publisher.publishEvent(new HeartbeatEvent(this, newCount)); // } // } // // } // Path: spring-cloud-netflix-eureka-client/src/test/java/org/springframework/cloud/netflix/eureka/sample/RefreshEurekaSampleApplication.java import com.netflix.discovery.EurekaClient; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.netflix.eureka.CloudEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.RestController; import static org.mockito.Mockito.mock; /* * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.sample; /** * @author Ryan Baxter */ @SpringBootConfiguration(proxyBeanMethods = false) @EnableAutoConfiguration @RestController public class RefreshEurekaSampleApplication { @Bean public EurekaClient getClient() {
return mock(CloudEurekaClient.class);
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/impl/CloseableBlockingQueue.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ClosedWatchServiceException.java // public class ClosedWatchServiceException extends IllegalStateException { // // }
import java.util.logging.Logger; import name.pachler.nio.file.ClosedWatchServiceException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.logging.Level;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ class CloseableBlockingQueue<T> implements BlockingQueue<T>{ Queue<T> q = new LinkedList<T>(); public synchronized boolean add(T e) { try { put(e); } catch (InterruptedException ex) { Logger.getLogger(CloseableBlockingQueue.class.getName()).log(Level.SEVERE, null, ex); } return true; } public synchronized int drainTo(Collection<? super T> clctn) { throw new UnsupportedOperationException("Not supported yet."); } public synchronized int drainTo(Collection<? super T> clctn, int maxNumElements) { throw new UnsupportedOperationException("Not supported yet."); } public synchronized boolean offer(T e) { throw new UnsupportedOperationException("Not supported yet."); } public synchronized boolean offer(T e, long l, TimeUnit tu) throws InterruptedException { throw new UnsupportedOperationException("Not supported yet."); } public synchronized T poll(long l, TimeUnit tu) throws InterruptedException { if(q == null)
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ClosedWatchServiceException.java // public class ClosedWatchServiceException extends IllegalStateException { // // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/CloseableBlockingQueue.java import java.util.logging.Logger; import name.pachler.nio.file.ClosedWatchServiceException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.logging.Level; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ class CloseableBlockingQueue<T> implements BlockingQueue<T>{ Queue<T> q = new LinkedList<T>(); public synchronized boolean add(T e) { try { put(e); } catch (InterruptedException ex) { Logger.getLogger(CloseableBlockingQueue.class.getName()).log(Level.SEVERE, null, ex); } return true; } public synchronized int drainTo(Collection<? super T> clctn) { throw new UnsupportedOperationException("Not supported yet."); } public synchronized int drainTo(Collection<? super T> clctn, int maxNumElements) { throw new UnsupportedOperationException("Not supported yet."); } public synchronized boolean offer(T e) { throw new UnsupportedOperationException("Not supported yet."); } public synchronized boolean offer(T e, long l, TimeUnit tu) throws InterruptedException { throw new UnsupportedOperationException("Not supported yet."); } public synchronized T poll(long l, TimeUnit tu) throws InterruptedException { if(q == null)
throw new ClosedWatchServiceException();
sworisbreathing/jpathwatch
jpathwatch-java/src/test/java/name/pachler/nio/file/impl/BSDTest.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/BSD.java // public static class kevent{ // static class IntStringMapping{ // int i; // String s; // IntStringMapping(int i, String s){ // this.i = i; // this.s = s; // } // } // // IntStringMapping [] flagsMapping = { // new IntStringMapping(BSD.EV_ADD, "EV_ADD"), // new IntStringMapping(BSD.EV_ENABLE, "EV_ENABLE"), // new IntStringMapping(BSD.EV_DISABLE, "EV_DISABLE"), // new IntStringMapping(BSD.EV_DELETE, "EV_DELETE"), // new IntStringMapping(BSD.EV_CLEAR, "EV_CLEAR"), // new IntStringMapping(BSD.EV_ONESHOT, "EV_ONESHOT"), // new IntStringMapping(BSD.EV_EOF, "EV_EOF"), // new IntStringMapping(BSD.EV_ERROR, "EV_ERROR"), // }; // // IntStringMapping [] vnodeNoteMapping = { // new IntStringMapping(BSD.NOTE_DELETE, "NOTE_DELETE"), // new IntStringMapping(BSD.NOTE_WRITE, "NOTE_WRITE"), // new IntStringMapping(BSD.NOTE_EXTEND, "NOTE_EXTEND"), // new IntStringMapping(BSD.NOTE_ATTRIB, "NOTE_ATTRIB"), // new IntStringMapping(BSD.NOTE_LINK, "NOTE_LINK"), // new IntStringMapping(BSD.NOTE_RENAME, "NOTE_RENAME"), // new IntStringMapping(BSD.NOTE_REVOKE, "NOTE_REVOKE"), // }; // IntStringMapping [] procNoteMapping = { // new IntStringMapping(BSD.NOTE_EXIT, "NOTE_EXIT"), // new IntStringMapping(BSD.NOTE_FORK, "NOTE_FORK"), // new IntStringMapping(BSD.NOTE_EXEC, "NOTE_EXEC"), // new IntStringMapping(BSD.NOTE_TRACK, "NOTE_TRACK"), // new IntStringMapping(BSD.NOTE_TRACKERR, "NOTE_TRACKERR"), // }; // /* IntStringMapping [] netdevNoteMapping = { // new IntStringMapping(BSD.NOTE_LINKUP, "NOTE_LINKUP"), // new IntStringMapping(BSD.NOTE_LINKDOWN, "NOTE_LINKDOWN"), // new IntStringMapping(BSD.NOTE_LINKINV, "NOTE_LINKINV"), // }; // */ // private long peer = createPeer(); // // private static native void initNative(); // private static native long createPeer(); // private static native void destroyPeer(long peer); // // static // { // initNative(); // } // // @Override // protected void finalize() throws Throwable { // try { // destroyPeer(peer); // peer = 0; // }finally{ // super.finalize(); // } // } // // // public native long get_ident(); // public native void set_ident(long ident); // // public native short get_filter(); // public native void set_filter(short filter); // // public native short get_flags(); // public native void set_flags(short flags); // // public native int get_fflags(); // public native void set_fflags(int fflags); // // public native long get_data(); // public native void set_data(long data); // // public native Object get_udata(); // public native void set_udata(Object udata); // // private String bitmaskToString(int value, IntStringMapping[] mapping){ // String bitmaskString = ""; // for(int i=0; i<mapping.length; ++i){ // if((value & mapping[i].i) != 0){ // if(bitmaskString.length()!=0) // bitmaskString += '|'; // bitmaskString += mapping[i].s; // } // } // return bitmaskString; // } // // @Override // public String toString(){ // String flags = bitmaskToString(get_flags(), flagsMapping); // String filter = "?"; // String fflags = "?"; // if(get_filter()==BSD.EVFILT_VNODE) // { // fflags = bitmaskToString(get_fflags(), vnodeNoteMapping); // filter = "EVFILT_VNODE"; // } // else if(get_filter()==BSD.EVFILT_PROC) // { // fflags = bitmaskToString(get_fflags(), procNoteMapping); // filter = "EVFILT_PROC"; // } // return "{ident="+get_ident()+";filter="+filter+";flags="+flags+";fflags="+fflags+";data="+get_data()+";udata="+get_udata()+"}"; // } // };
import name.pachler.nio.file.impl.BSD.kevent; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
int kqueueFD = BSD.kqueue(); assertFalse(kqueueFD == -1); // may not return error // clean up BSD.close(kqueueFD); } @Test public void testKqueueInThread() throws InterruptedException{ //int kqueueFD = BSD.kqueue(); System.out.println("kevent in thread"); Thread t = new Thread(new Runnable(){ public void run() { testKqueue(); } }); t.start(); t.join(); } /** * Test of kevent method, of class BSD. */ @Test public void testKevent() { if(!isBSD()) return; // only run this on BSD
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/BSD.java // public static class kevent{ // static class IntStringMapping{ // int i; // String s; // IntStringMapping(int i, String s){ // this.i = i; // this.s = s; // } // } // // IntStringMapping [] flagsMapping = { // new IntStringMapping(BSD.EV_ADD, "EV_ADD"), // new IntStringMapping(BSD.EV_ENABLE, "EV_ENABLE"), // new IntStringMapping(BSD.EV_DISABLE, "EV_DISABLE"), // new IntStringMapping(BSD.EV_DELETE, "EV_DELETE"), // new IntStringMapping(BSD.EV_CLEAR, "EV_CLEAR"), // new IntStringMapping(BSD.EV_ONESHOT, "EV_ONESHOT"), // new IntStringMapping(BSD.EV_EOF, "EV_EOF"), // new IntStringMapping(BSD.EV_ERROR, "EV_ERROR"), // }; // // IntStringMapping [] vnodeNoteMapping = { // new IntStringMapping(BSD.NOTE_DELETE, "NOTE_DELETE"), // new IntStringMapping(BSD.NOTE_WRITE, "NOTE_WRITE"), // new IntStringMapping(BSD.NOTE_EXTEND, "NOTE_EXTEND"), // new IntStringMapping(BSD.NOTE_ATTRIB, "NOTE_ATTRIB"), // new IntStringMapping(BSD.NOTE_LINK, "NOTE_LINK"), // new IntStringMapping(BSD.NOTE_RENAME, "NOTE_RENAME"), // new IntStringMapping(BSD.NOTE_REVOKE, "NOTE_REVOKE"), // }; // IntStringMapping [] procNoteMapping = { // new IntStringMapping(BSD.NOTE_EXIT, "NOTE_EXIT"), // new IntStringMapping(BSD.NOTE_FORK, "NOTE_FORK"), // new IntStringMapping(BSD.NOTE_EXEC, "NOTE_EXEC"), // new IntStringMapping(BSD.NOTE_TRACK, "NOTE_TRACK"), // new IntStringMapping(BSD.NOTE_TRACKERR, "NOTE_TRACKERR"), // }; // /* IntStringMapping [] netdevNoteMapping = { // new IntStringMapping(BSD.NOTE_LINKUP, "NOTE_LINKUP"), // new IntStringMapping(BSD.NOTE_LINKDOWN, "NOTE_LINKDOWN"), // new IntStringMapping(BSD.NOTE_LINKINV, "NOTE_LINKINV"), // }; // */ // private long peer = createPeer(); // // private static native void initNative(); // private static native long createPeer(); // private static native void destroyPeer(long peer); // // static // { // initNative(); // } // // @Override // protected void finalize() throws Throwable { // try { // destroyPeer(peer); // peer = 0; // }finally{ // super.finalize(); // } // } // // // public native long get_ident(); // public native void set_ident(long ident); // // public native short get_filter(); // public native void set_filter(short filter); // // public native short get_flags(); // public native void set_flags(short flags); // // public native int get_fflags(); // public native void set_fflags(int fflags); // // public native long get_data(); // public native void set_data(long data); // // public native Object get_udata(); // public native void set_udata(Object udata); // // private String bitmaskToString(int value, IntStringMapping[] mapping){ // String bitmaskString = ""; // for(int i=0; i<mapping.length; ++i){ // if((value & mapping[i].i) != 0){ // if(bitmaskString.length()!=0) // bitmaskString += '|'; // bitmaskString += mapping[i].s; // } // } // return bitmaskString; // } // // @Override // public String toString(){ // String flags = bitmaskToString(get_flags(), flagsMapping); // String filter = "?"; // String fflags = "?"; // if(get_filter()==BSD.EVFILT_VNODE) // { // fflags = bitmaskToString(get_fflags(), vnodeNoteMapping); // filter = "EVFILT_VNODE"; // } // else if(get_filter()==BSD.EVFILT_PROC) // { // fflags = bitmaskToString(get_fflags(), procNoteMapping); // filter = "EVFILT_PROC"; // } // return "{ident="+get_ident()+";filter="+filter+";flags="+flags+";fflags="+fflags+";data="+get_data()+";udata="+get_udata()+"}"; // } // }; // Path: jpathwatch-java/src/test/java/name/pachler/nio/file/impl/BSDTest.java import name.pachler.nio.file.impl.BSD.kevent; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; int kqueueFD = BSD.kqueue(); assertFalse(kqueueFD == -1); // may not return error // clean up BSD.close(kqueueFD); } @Test public void testKqueueInThread() throws InterruptedException{ //int kqueueFD = BSD.kqueue(); System.out.println("kevent in thread"); Thread t = new Thread(new Runnable(){ public void run() { testKqueue(); } }); t.start(); t.join(); } /** * Test of kevent method, of class BSD. */ @Test public void testKevent() { if(!isBSD()) return; // only run this on BSD
System.out.println("kevent");
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/Paths.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ext/Bootstrapper.java // public class Bootstrapper { // private static final int OSTYPE_UNKNOWN = 0; // private static final int OSTYPE_LINUX = 1; // private static final int OSTYPE_WINDOWS = 2; // private static final int OSTYPE_BSD = 3; // // private static boolean forcePolling = false; // private static long defaultPollingInterval = 2000; // by default, polling WatchService implementation poll every 2 seconds // // private static final int ostype; // static { // String osName = System.getProperty("os.name"); // if(osName.contains("Windows")) // ostype = OSTYPE_WINDOWS; // else if(osName.equals("Linux")) // ostype = OSTYPE_LINUX; // else if(osName.equals("Mac OS X") || osName.equals("FreeBSD")) // ostype = OSTYPE_BSD; // else // ostype = OSTYPE_UNKNOWN; // } // // /** // * Creates a new WatchService. This is a shortcut for calling // * <code>FileSystems.getDefault().newWatchService()</code> and // * is not source-compatible to JDK7 // * @return a new WatchService implementation instance. // * @see name.pachler.nio.file.FileSystem#newWatchService() // * @see name.pachler.nio.file.FileSystems#getDefault() // */ // public static WatchService newWatchService(){ // WatchService ws = null; // try { // if(!forcePolling){ // switch(ostype){ // case OSTYPE_LINUX: // ws = new LinuxPathWatchService(); // break; // case OSTYPE_WINDOWS: // ws = new WindowsPathWatchService(); // break; // case OSTYPE_BSD: // ws = new BSDPathWatchService(); // break; // } // } // } catch(Throwable t){ // Logger.getLogger(Bootstrapper.class.getName()).log(Level.WARNING, null, t); // } finally { // // if for whatever reason we don't have a // // WatchService, we'll create a polling one as fallback. // if(ws == null) // ws = new PollingPathWatchService(); // return ws; // } // } // // /** // * Creates a new Path instance for a given File. // * @param file that a new Path is created for // * @return a new Path() corresponding to the given File // */ // public static Path newPath(File file){ // return new PathImpl(file); // } // // /** // * Gets the File that corresponds to the given path. // * @param path Path for with to retreive the corresponding File // * @return The file which corresponds to the given Path instance. // */ // public static File pathToFile(Path path){ // return ((PathImpl)path).getFile(); // } // // /** // * @return whether polling is enforced. // */ // public static boolean isForcePollingEnabled(){ // return forcePolling; // } // // /** // * When force polling is enabled, the Bootstrapper's {@link #newWatchService()} // * method will only produce polling watch services. This feature is mostly // * useful for testing and debugging (and not not much else really). // * @param forcePollingEnabled true to enable force polling // */ // public static void setForcePollingEnabled(boolean forcePollingEnabled){ // forcePolling = forcePollingEnabled; // } // // /** // * <p>This method allows to set the default polling time interval for // * new WatchService implementations that use polling. Note that polling // * is only used on a few supported platforms when certain event kinds // * are used or on unsupported platforms (fallback implementation).</p> // * <p>The polling interval determines how often a thread that calls // * {@link WatchService#take() } will wake up to check if files in the // * watched directory have changed. Longer time intervals will make // * a polling service less accurate, but costs less in CPU and disk // * resources, while shorter time intervals lead to higher accuracy but // * more consumed resources (up to the point where polling takes longer than // * the set interval in which case the machine will become very slow).</p> // * @param pollInterval the polling time interval in milliseconds // */ // public static void setDefaultPollingInterval(long pollInterval){ // if(pollInterval <= 0) // throw new IllegalArgumentException("polling interval must be greater than zero"); // defaultPollingInterval = pollInterval; // } // // /** // * Retrieves the default polling interval. // * @see setDefaultPollingInterval // * @return the default polling interval, in milliseconds // */ // public static long getDefaultPollingInterval() { // return defaultPollingInterval; // } // }
import java.io.File; import java.net.URI; import name.pachler.nio.file.ext.Bootstrapper;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * Factory class for Path instances. * @author uwep */ public abstract class Paths { private Paths(){ } /** * Creates a new Path instance from the given file system path string. * @param path the path string * @return a new Path instance representing the path string */ public static Path get(String path){
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ext/Bootstrapper.java // public class Bootstrapper { // private static final int OSTYPE_UNKNOWN = 0; // private static final int OSTYPE_LINUX = 1; // private static final int OSTYPE_WINDOWS = 2; // private static final int OSTYPE_BSD = 3; // // private static boolean forcePolling = false; // private static long defaultPollingInterval = 2000; // by default, polling WatchService implementation poll every 2 seconds // // private static final int ostype; // static { // String osName = System.getProperty("os.name"); // if(osName.contains("Windows")) // ostype = OSTYPE_WINDOWS; // else if(osName.equals("Linux")) // ostype = OSTYPE_LINUX; // else if(osName.equals("Mac OS X") || osName.equals("FreeBSD")) // ostype = OSTYPE_BSD; // else // ostype = OSTYPE_UNKNOWN; // } // // /** // * Creates a new WatchService. This is a shortcut for calling // * <code>FileSystems.getDefault().newWatchService()</code> and // * is not source-compatible to JDK7 // * @return a new WatchService implementation instance. // * @see name.pachler.nio.file.FileSystem#newWatchService() // * @see name.pachler.nio.file.FileSystems#getDefault() // */ // public static WatchService newWatchService(){ // WatchService ws = null; // try { // if(!forcePolling){ // switch(ostype){ // case OSTYPE_LINUX: // ws = new LinuxPathWatchService(); // break; // case OSTYPE_WINDOWS: // ws = new WindowsPathWatchService(); // break; // case OSTYPE_BSD: // ws = new BSDPathWatchService(); // break; // } // } // } catch(Throwable t){ // Logger.getLogger(Bootstrapper.class.getName()).log(Level.WARNING, null, t); // } finally { // // if for whatever reason we don't have a // // WatchService, we'll create a polling one as fallback. // if(ws == null) // ws = new PollingPathWatchService(); // return ws; // } // } // // /** // * Creates a new Path instance for a given File. // * @param file that a new Path is created for // * @return a new Path() corresponding to the given File // */ // public static Path newPath(File file){ // return new PathImpl(file); // } // // /** // * Gets the File that corresponds to the given path. // * @param path Path for with to retreive the corresponding File // * @return The file which corresponds to the given Path instance. // */ // public static File pathToFile(Path path){ // return ((PathImpl)path).getFile(); // } // // /** // * @return whether polling is enforced. // */ // public static boolean isForcePollingEnabled(){ // return forcePolling; // } // // /** // * When force polling is enabled, the Bootstrapper's {@link #newWatchService()} // * method will only produce polling watch services. This feature is mostly // * useful for testing and debugging (and not not much else really). // * @param forcePollingEnabled true to enable force polling // */ // public static void setForcePollingEnabled(boolean forcePollingEnabled){ // forcePolling = forcePollingEnabled; // } // // /** // * <p>This method allows to set the default polling time interval for // * new WatchService implementations that use polling. Note that polling // * is only used on a few supported platforms when certain event kinds // * are used or on unsupported platforms (fallback implementation).</p> // * <p>The polling interval determines how often a thread that calls // * {@link WatchService#take() } will wake up to check if files in the // * watched directory have changed. Longer time intervals will make // * a polling service less accurate, but costs less in CPU and disk // * resources, while shorter time intervals lead to higher accuracy but // * more consumed resources (up to the point where polling takes longer than // * the set interval in which case the machine will become very slow).</p> // * @param pollInterval the polling time interval in milliseconds // */ // public static void setDefaultPollingInterval(long pollInterval){ // if(pollInterval <= 0) // throw new IllegalArgumentException("polling interval must be greater than zero"); // defaultPollingInterval = pollInterval; // } // // /** // * Retrieves the default polling interval. // * @see setDefaultPollingInterval // * @return the default polling interval, in milliseconds // */ // public static long getDefaultPollingInterval() { // return defaultPollingInterval; // } // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Paths.java import java.io.File; import java.net.URI; import name.pachler.nio.file.ext.Bootstrapper; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * Factory class for Path instances. * @author uwep */ public abstract class Paths { private Paths(){ } /** * Creates a new Path instance from the given file system path string. * @param path the path string * @return a new Path instance representing the path string */ public static Path get(String path){
return Bootstrapper.newPath(new File(path));
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/StandardWatchEventKind.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ext/ExtendedWatchEventKind.java // public class ExtendedWatchEventKind { // /** // * Indicates the old file name of a renamed file. The // * {@link WatchEvent}'s {@link WatchEvent#context} method will return // * a Path that indicates the previous name that the file had. // */ // public static WatchEvent.Kind<Path> ENTRY_RENAME_FROM = new PathWatchEventKind("ENTRY_RENAME_FROM"); // /** // * Indicates the new file name of a renamed file. The // * {@link WatchEvent}'s {@link WatchEvent#context} method will return // * a Path that indicates the new name of the file. // */ // public static WatchEvent.Kind<Path> ENTRY_RENAME_TO = new PathWatchEventKind("ENTRY_RENAME_TO"); // // /** // * Indicates that the given {@link WatchKey} has become invalid. This // * can happen for a number of reasons: // * <ul> // * <li>The key has been invalidated programmatically by calling // * {@link WatchKey#cancel}.</li> // * <li>The {@link WatchService} has been closed.</li> // * <li>The path that the key has been registered with has become // * unavailable, e.g because it was deleted or the file system on which // * it resides has been unmounted.</li> // * </ul> // * Note that not all operating systems will invalidate the WatchKey // * (and report KEY_INVALID) under the same circumstances. On most platforms, // * moving or renaming the directory that the key was registered with will // * invalidate it, however, on Windows it will not (only when it is // * deleted or unmounted). // */ // public static WatchEvent.Kind<Void> KEY_INVALID = new VoidWatchEventKind("KEY_INVALID"); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/VoidWatchEventKind.java // public class VoidWatchEventKind implements WatchEvent.Kind<Void> { // // public VoidWatchEventKind(String name) { // this.name = name; // } // private final String name; // // public String name() { // return name; // } // // public Class<Void> type() { // throw new UnsupportedOperationException("Not supported yet."); // } // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchEventKind.java // public class PathWatchEventKind implements WatchEvent.Kind<Path> { // // private final String name; // // public PathWatchEventKind(String name) { // this.name = name; // } // // public String name() { // return name; // } // // public Class<Path> type() { // return Path.class; // } // // @Override // public String toString() { // return name(); // } // }
import name.pachler.nio.file.ext.ExtendedWatchEventKind; import name.pachler.nio.file.impl.VoidWatchEventKind; import name.pachler.nio.file.impl.PathWatchEventKind;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * This class contains the standard watch event kinds, which are basically * flags that indicate which events a WatchService should report when a * Watchable is registered with a WatchService. * The kinds are also used to indicate the kind of event on events that * are reported back.</br> * Note that the event kinds defined in this class are supported on all platforms * @author count * @see Watchable#register * @see WatchEvent$Kind */ public class StandardWatchEventKind { /** * Indicates that a file has been created under the watched path. */ public static final WatchEvent.Kind<Path> ENTRY_CREATE = new PathWatchEventKind("ENTRY_CREATE"); /** * Indicates that a file has been deleted under the watched path. Note that * on file rename the old file name will be reported as deleted if no other * (extended) watch event kinds are specified. * @see ExtendedWatchEventKind */ public static final WatchEvent.Kind<Path> ENTRY_DELETE = new PathWatchEventKind("ENTRY_DELETE"); /** * Indicates that a file under the watched path has been modified. Note that * modification can never be byte-accurate, which means that you won't * receive a modification event for each byte written to a file. It is * higly implementation dependent how many modification events are produced. */ public static final WatchEvent.Kind<Path> ENTRY_MODIFY = new PathWatchEventKind("ENTRY_MODIFY"); /** * Indicates queue overflow in the WatchService. If the event queue * overflows (because, for example,the WatchService runs * out of space to store events because they occur faster than the client * code can retreives them from the designated watch keys), additional * events are dropped, and this event is reported. * Note that WatchKeys are always subscribed to this event, regardless * of whether it is specified to <code>register()</code> or not. * @see Watchable#register */
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ext/ExtendedWatchEventKind.java // public class ExtendedWatchEventKind { // /** // * Indicates the old file name of a renamed file. The // * {@link WatchEvent}'s {@link WatchEvent#context} method will return // * a Path that indicates the previous name that the file had. // */ // public static WatchEvent.Kind<Path> ENTRY_RENAME_FROM = new PathWatchEventKind("ENTRY_RENAME_FROM"); // /** // * Indicates the new file name of a renamed file. The // * {@link WatchEvent}'s {@link WatchEvent#context} method will return // * a Path that indicates the new name of the file. // */ // public static WatchEvent.Kind<Path> ENTRY_RENAME_TO = new PathWatchEventKind("ENTRY_RENAME_TO"); // // /** // * Indicates that the given {@link WatchKey} has become invalid. This // * can happen for a number of reasons: // * <ul> // * <li>The key has been invalidated programmatically by calling // * {@link WatchKey#cancel}.</li> // * <li>The {@link WatchService} has been closed.</li> // * <li>The path that the key has been registered with has become // * unavailable, e.g because it was deleted or the file system on which // * it resides has been unmounted.</li> // * </ul> // * Note that not all operating systems will invalidate the WatchKey // * (and report KEY_INVALID) under the same circumstances. On most platforms, // * moving or renaming the directory that the key was registered with will // * invalidate it, however, on Windows it will not (only when it is // * deleted or unmounted). // */ // public static WatchEvent.Kind<Void> KEY_INVALID = new VoidWatchEventKind("KEY_INVALID"); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/VoidWatchEventKind.java // public class VoidWatchEventKind implements WatchEvent.Kind<Void> { // // public VoidWatchEventKind(String name) { // this.name = name; // } // private final String name; // // public String name() { // return name; // } // // public Class<Void> type() { // throw new UnsupportedOperationException("Not supported yet."); // } // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchEventKind.java // public class PathWatchEventKind implements WatchEvent.Kind<Path> { // // private final String name; // // public PathWatchEventKind(String name) { // this.name = name; // } // // public String name() { // return name; // } // // public Class<Path> type() { // return Path.class; // } // // @Override // public String toString() { // return name(); // } // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/StandardWatchEventKind.java import name.pachler.nio.file.ext.ExtendedWatchEventKind; import name.pachler.nio.file.impl.VoidWatchEventKind; import name.pachler.nio.file.impl.PathWatchEventKind; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * This class contains the standard watch event kinds, which are basically * flags that indicate which events a WatchService should report when a * Watchable is registered with a WatchService. * The kinds are also used to indicate the kind of event on events that * are reported back.</br> * Note that the event kinds defined in this class are supported on all platforms * @author count * @see Watchable#register * @see WatchEvent$Kind */ public class StandardWatchEventKind { /** * Indicates that a file has been created under the watched path. */ public static final WatchEvent.Kind<Path> ENTRY_CREATE = new PathWatchEventKind("ENTRY_CREATE"); /** * Indicates that a file has been deleted under the watched path. Note that * on file rename the old file name will be reported as deleted if no other * (extended) watch event kinds are specified. * @see ExtendedWatchEventKind */ public static final WatchEvent.Kind<Path> ENTRY_DELETE = new PathWatchEventKind("ENTRY_DELETE"); /** * Indicates that a file under the watched path has been modified. Note that * modification can never be byte-accurate, which means that you won't * receive a modification event for each byte written to a file. It is * higly implementation dependent how many modification events are produced. */ public static final WatchEvent.Kind<Path> ENTRY_MODIFY = new PathWatchEventKind("ENTRY_MODIFY"); /** * Indicates queue overflow in the WatchService. If the event queue * overflows (because, for example,the WatchService runs * out of space to store events because they occur faster than the client * code can retreives them from the designated watch keys), additional * events are dropped, and this event is reported. * Note that WatchKeys are always subscribed to this event, regardless * of whether it is specified to <code>register()</code> or not. * @see Watchable#register */
public static final WatchEvent.Kind<Void> OVERFLOW = new VoidWatchEventKind("OVERFLOW");
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PollingPathWatchKey.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/StandardWatchEventKind.java // public class StandardWatchEventKind { // /** // * Indicates that a file has been created under the watched path. // */ // public static final WatchEvent.Kind<Path> ENTRY_CREATE = new PathWatchEventKind("ENTRY_CREATE"); // /** // * Indicates that a file has been deleted under the watched path. Note that // * on file rename the old file name will be reported as deleted if no other // * (extended) watch event kinds are specified. // * @see ExtendedWatchEventKind // */ // public static final WatchEvent.Kind<Path> ENTRY_DELETE = new PathWatchEventKind("ENTRY_DELETE"); // /** // * Indicates that a file under the watched path has been modified. Note that // * modification can never be byte-accurate, which means that you won't // * receive a modification event for each byte written to a file. It is // * higly implementation dependent how many modification events are produced. // */ // public static final WatchEvent.Kind<Path> ENTRY_MODIFY = new PathWatchEventKind("ENTRY_MODIFY"); // // /** // * Indicates queue overflow in the WatchService. If the event queue // * overflows (because, for example,the WatchService runs // * out of space to store events because they occur faster than the client // * code can retreives them from the designated watch keys), additional // * events are dropped, and this event is reported. // * Note that WatchKeys are always subscribed to this event, regardless // * of whether it is specified to <code>register()</code> or not. // * @see Watchable#register // */ // public static final WatchEvent.Kind<Void> OVERFLOW = new VoidWatchEventKind("OVERFLOW"); // }
import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import name.pachler.nio.file.Path; import name.pachler.nio.file.StandardWatchEventKind;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ class PollingPathWatchKey extends PathWatchKey{ private String[] fileNames; private long[] lastModifieds; private long[] lengths;
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/StandardWatchEventKind.java // public class StandardWatchEventKind { // /** // * Indicates that a file has been created under the watched path. // */ // public static final WatchEvent.Kind<Path> ENTRY_CREATE = new PathWatchEventKind("ENTRY_CREATE"); // /** // * Indicates that a file has been deleted under the watched path. Note that // * on file rename the old file name will be reported as deleted if no other // * (extended) watch event kinds are specified. // * @see ExtendedWatchEventKind // */ // public static final WatchEvent.Kind<Path> ENTRY_DELETE = new PathWatchEventKind("ENTRY_DELETE"); // /** // * Indicates that a file under the watched path has been modified. Note that // * modification can never be byte-accurate, which means that you won't // * receive a modification event for each byte written to a file. It is // * higly implementation dependent how many modification events are produced. // */ // public static final WatchEvent.Kind<Path> ENTRY_MODIFY = new PathWatchEventKind("ENTRY_MODIFY"); // // /** // * Indicates queue overflow in the WatchService. If the event queue // * overflows (because, for example,the WatchService runs // * out of space to store events because they occur faster than the client // * code can retreives them from the designated watch keys), additional // * events are dropped, and this event is reported. // * Note that WatchKeys are always subscribed to this event, regardless // * of whether it is specified to <code>register()</code> or not. // * @see Watchable#register // */ // public static final WatchEvent.Kind<Void> OVERFLOW = new VoidWatchEventKind("OVERFLOW"); // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PollingPathWatchKey.java import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import name.pachler.nio.file.Path; import name.pachler.nio.file.StandardWatchEventKind; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ class PollingPathWatchKey extends PathWatchKey{ private String[] fileNames; private long[] lastModifieds; private long[] lengths;
PollingPathWatchKey(PathWatchService service, Path path, int flags) {
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PollingPathWatchKey.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/StandardWatchEventKind.java // public class StandardWatchEventKind { // /** // * Indicates that a file has been created under the watched path. // */ // public static final WatchEvent.Kind<Path> ENTRY_CREATE = new PathWatchEventKind("ENTRY_CREATE"); // /** // * Indicates that a file has been deleted under the watched path. Note that // * on file rename the old file name will be reported as deleted if no other // * (extended) watch event kinds are specified. // * @see ExtendedWatchEventKind // */ // public static final WatchEvent.Kind<Path> ENTRY_DELETE = new PathWatchEventKind("ENTRY_DELETE"); // /** // * Indicates that a file under the watched path has been modified. Note that // * modification can never be byte-accurate, which means that you won't // * receive a modification event for each byte written to a file. It is // * higly implementation dependent how many modification events are produced. // */ // public static final WatchEvent.Kind<Path> ENTRY_MODIFY = new PathWatchEventKind("ENTRY_MODIFY"); // // /** // * Indicates queue overflow in the WatchService. If the event queue // * overflows (because, for example,the WatchService runs // * out of space to store events because they occur faster than the client // * code can retreives them from the designated watch keys), additional // * events are dropped, and this event is reported. // * Note that WatchKeys are always subscribed to this event, regardless // * of whether it is specified to <code>register()</code> or not. // * @see Watchable#register // */ // public static final WatchEvent.Kind<Void> OVERFLOW = new VoidWatchEventKind("OVERFLOW"); // }
import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import name.pachler.nio.file.Path; import name.pachler.nio.file.StandardWatchEventKind;
if(oldName == null){ ++oldIndex; continue; } } else comparison = 1; // if there's no old entry left, indicate // that the new one is 'larger', and will be picked up // below if(newIndex < newFileNames.length){ newName = newFileNames[newIndex]; if(newName == null){ ++newIndex; continue; } } else comparison = -1; // if there's no new entry left, indicate // that the old one is 'larger', and will be picked up // below // compare strings if we haven't come to a conclusion above if(comparison == 0) comparison = oldName.compareTo(newName); if(comparison < 0){ // this means that what is in old is not in new -> a file // has been removed, so we need a remove event if((flags & PathWatchService.FLAG_FILTER_ENTRY_DELETE)!=0){ Path p = new PathImpl(new File(oldName));
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/StandardWatchEventKind.java // public class StandardWatchEventKind { // /** // * Indicates that a file has been created under the watched path. // */ // public static final WatchEvent.Kind<Path> ENTRY_CREATE = new PathWatchEventKind("ENTRY_CREATE"); // /** // * Indicates that a file has been deleted under the watched path. Note that // * on file rename the old file name will be reported as deleted if no other // * (extended) watch event kinds are specified. // * @see ExtendedWatchEventKind // */ // public static final WatchEvent.Kind<Path> ENTRY_DELETE = new PathWatchEventKind("ENTRY_DELETE"); // /** // * Indicates that a file under the watched path has been modified. Note that // * modification can never be byte-accurate, which means that you won't // * receive a modification event for each byte written to a file. It is // * higly implementation dependent how many modification events are produced. // */ // public static final WatchEvent.Kind<Path> ENTRY_MODIFY = new PathWatchEventKind("ENTRY_MODIFY"); // // /** // * Indicates queue overflow in the WatchService. If the event queue // * overflows (because, for example,the WatchService runs // * out of space to store events because they occur faster than the client // * code can retreives them from the designated watch keys), additional // * events are dropped, and this event is reported. // * Note that WatchKeys are always subscribed to this event, regardless // * of whether it is specified to <code>register()</code> or not. // * @see Watchable#register // */ // public static final WatchEvent.Kind<Void> OVERFLOW = new VoidWatchEventKind("OVERFLOW"); // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PollingPathWatchKey.java import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import name.pachler.nio.file.Path; import name.pachler.nio.file.StandardWatchEventKind; if(oldName == null){ ++oldIndex; continue; } } else comparison = 1; // if there's no old entry left, indicate // that the new one is 'larger', and will be picked up // below if(newIndex < newFileNames.length){ newName = newFileNames[newIndex]; if(newName == null){ ++newIndex; continue; } } else comparison = -1; // if there's no new entry left, indicate // that the old one is 'larger', and will be picked up // below // compare strings if we haven't come to a conclusion above if(comparison == 0) comparison = oldName.compareTo(newName); if(comparison < 0){ // this means that what is in old is not in new -> a file // has been removed, so we need a remove event if((flags & PathWatchService.FLAG_FILTER_ENTRY_DELETE)!=0){ Path p = new PathImpl(new File(oldName));
PathWatchEvent e = new PathWatchEvent(StandardWatchEventKind.ENTRY_DELETE, p, 1);
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/FileSystems.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ext/Bootstrapper.java // public class Bootstrapper { // private static final int OSTYPE_UNKNOWN = 0; // private static final int OSTYPE_LINUX = 1; // private static final int OSTYPE_WINDOWS = 2; // private static final int OSTYPE_BSD = 3; // // private static boolean forcePolling = false; // private static long defaultPollingInterval = 2000; // by default, polling WatchService implementation poll every 2 seconds // // private static final int ostype; // static { // String osName = System.getProperty("os.name"); // if(osName.contains("Windows")) // ostype = OSTYPE_WINDOWS; // else if(osName.equals("Linux")) // ostype = OSTYPE_LINUX; // else if(osName.equals("Mac OS X") || osName.equals("FreeBSD")) // ostype = OSTYPE_BSD; // else // ostype = OSTYPE_UNKNOWN; // } // // /** // * Creates a new WatchService. This is a shortcut for calling // * <code>FileSystems.getDefault().newWatchService()</code> and // * is not source-compatible to JDK7 // * @return a new WatchService implementation instance. // * @see name.pachler.nio.file.FileSystem#newWatchService() // * @see name.pachler.nio.file.FileSystems#getDefault() // */ // public static WatchService newWatchService(){ // WatchService ws = null; // try { // if(!forcePolling){ // switch(ostype){ // case OSTYPE_LINUX: // ws = new LinuxPathWatchService(); // break; // case OSTYPE_WINDOWS: // ws = new WindowsPathWatchService(); // break; // case OSTYPE_BSD: // ws = new BSDPathWatchService(); // break; // } // } // } catch(Throwable t){ // Logger.getLogger(Bootstrapper.class.getName()).log(Level.WARNING, null, t); // } finally { // // if for whatever reason we don't have a // // WatchService, we'll create a polling one as fallback. // if(ws == null) // ws = new PollingPathWatchService(); // return ws; // } // } // // /** // * Creates a new Path instance for a given File. // * @param file that a new Path is created for // * @return a new Path() corresponding to the given File // */ // public static Path newPath(File file){ // return new PathImpl(file); // } // // /** // * Gets the File that corresponds to the given path. // * @param path Path for with to retreive the corresponding File // * @return The file which corresponds to the given Path instance. // */ // public static File pathToFile(Path path){ // return ((PathImpl)path).getFile(); // } // // /** // * @return whether polling is enforced. // */ // public static boolean isForcePollingEnabled(){ // return forcePolling; // } // // /** // * When force polling is enabled, the Bootstrapper's {@link #newWatchService()} // * method will only produce polling watch services. This feature is mostly // * useful for testing and debugging (and not not much else really). // * @param forcePollingEnabled true to enable force polling // */ // public static void setForcePollingEnabled(boolean forcePollingEnabled){ // forcePolling = forcePollingEnabled; // } // // /** // * <p>This method allows to set the default polling time interval for // * new WatchService implementations that use polling. Note that polling // * is only used on a few supported platforms when certain event kinds // * are used or on unsupported platforms (fallback implementation).</p> // * <p>The polling interval determines how often a thread that calls // * {@link WatchService#take() } will wake up to check if files in the // * watched directory have changed. Longer time intervals will make // * a polling service less accurate, but costs less in CPU and disk // * resources, while shorter time intervals lead to higher accuracy but // * more consumed resources (up to the point where polling takes longer than // * the set interval in which case the machine will become very slow).</p> // * @param pollInterval the polling time interval in milliseconds // */ // public static void setDefaultPollingInterval(long pollInterval){ // if(pollInterval <= 0) // throw new IllegalArgumentException("polling interval must be greater than zero"); // defaultPollingInterval = pollInterval; // } // // /** // * Retrieves the default polling interval. // * @see setDefaultPollingInterval // * @return the default polling interval, in milliseconds // */ // public static long getDefaultPollingInterval() { // return defaultPollingInterval; // } // }
import name.pachler.nio.file.ext.Bootstrapper;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * Provides static method to get the default FileSystem object. It is used * to acquire a WatchService via the provided FileSystem instance. * Note that this * class solely exists in jpathwatch to maintain JDK7 source compatibility, * but only offers small subset of the functionality implemented in JDK7. * @author count */ public abstract class FileSystems { private static FileSystem defaultfs = new FileSystem(){ @Override public WatchService newWatchService() {
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/ext/Bootstrapper.java // public class Bootstrapper { // private static final int OSTYPE_UNKNOWN = 0; // private static final int OSTYPE_LINUX = 1; // private static final int OSTYPE_WINDOWS = 2; // private static final int OSTYPE_BSD = 3; // // private static boolean forcePolling = false; // private static long defaultPollingInterval = 2000; // by default, polling WatchService implementation poll every 2 seconds // // private static final int ostype; // static { // String osName = System.getProperty("os.name"); // if(osName.contains("Windows")) // ostype = OSTYPE_WINDOWS; // else if(osName.equals("Linux")) // ostype = OSTYPE_LINUX; // else if(osName.equals("Mac OS X") || osName.equals("FreeBSD")) // ostype = OSTYPE_BSD; // else // ostype = OSTYPE_UNKNOWN; // } // // /** // * Creates a new WatchService. This is a shortcut for calling // * <code>FileSystems.getDefault().newWatchService()</code> and // * is not source-compatible to JDK7 // * @return a new WatchService implementation instance. // * @see name.pachler.nio.file.FileSystem#newWatchService() // * @see name.pachler.nio.file.FileSystems#getDefault() // */ // public static WatchService newWatchService(){ // WatchService ws = null; // try { // if(!forcePolling){ // switch(ostype){ // case OSTYPE_LINUX: // ws = new LinuxPathWatchService(); // break; // case OSTYPE_WINDOWS: // ws = new WindowsPathWatchService(); // break; // case OSTYPE_BSD: // ws = new BSDPathWatchService(); // break; // } // } // } catch(Throwable t){ // Logger.getLogger(Bootstrapper.class.getName()).log(Level.WARNING, null, t); // } finally { // // if for whatever reason we don't have a // // WatchService, we'll create a polling one as fallback. // if(ws == null) // ws = new PollingPathWatchService(); // return ws; // } // } // // /** // * Creates a new Path instance for a given File. // * @param file that a new Path is created for // * @return a new Path() corresponding to the given File // */ // public static Path newPath(File file){ // return new PathImpl(file); // } // // /** // * Gets the File that corresponds to the given path. // * @param path Path for with to retreive the corresponding File // * @return The file which corresponds to the given Path instance. // */ // public static File pathToFile(Path path){ // return ((PathImpl)path).getFile(); // } // // /** // * @return whether polling is enforced. // */ // public static boolean isForcePollingEnabled(){ // return forcePolling; // } // // /** // * When force polling is enabled, the Bootstrapper's {@link #newWatchService()} // * method will only produce polling watch services. This feature is mostly // * useful for testing and debugging (and not not much else really). // * @param forcePollingEnabled true to enable force polling // */ // public static void setForcePollingEnabled(boolean forcePollingEnabled){ // forcePolling = forcePollingEnabled; // } // // /** // * <p>This method allows to set the default polling time interval for // * new WatchService implementations that use polling. Note that polling // * is only used on a few supported platforms when certain event kinds // * are used or on unsupported platforms (fallback implementation).</p> // * <p>The polling interval determines how often a thread that calls // * {@link WatchService#take() } will wake up to check if files in the // * watched directory have changed. Longer time intervals will make // * a polling service less accurate, but costs less in CPU and disk // * resources, while shorter time intervals lead to higher accuracy but // * more consumed resources (up to the point where polling takes longer than // * the set interval in which case the machine will become very slow).</p> // * @param pollInterval the polling time interval in milliseconds // */ // public static void setDefaultPollingInterval(long pollInterval){ // if(pollInterval <= 0) // throw new IllegalArgumentException("polling interval must be greater than zero"); // defaultPollingInterval = pollInterval; // } // // /** // * Retrieves the default polling interval. // * @see setDefaultPollingInterval // * @return the default polling interval, in milliseconds // */ // public static long getDefaultPollingInterval() { // return defaultPollingInterval; // } // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/FileSystems.java import name.pachler.nio.file.ext.Bootstrapper; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * Provides static method to get the default FileSystem object. It is used * to acquire a WatchService via the provided FileSystem instance. * Note that this * class solely exists in jpathwatch to maintain JDK7 source compatibility, * but only offers small subset of the functionality implemented in JDK7. * @author count */ public abstract class FileSystems { private static FileSystem defaultfs = new FileSystem(){ @Override public WatchService newWatchService() {
return Bootstrapper.newWatchService();
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchEvent.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public abstract class WatchEvent<T> { // /** // * Instances of this class act as tags to identify different kinds of // * events (like file creation or deletion) // * @param <T> The context this kind is intended for. In jpathwatch, only // * Path and Void are used as context types. // */ // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // /** // * A modifier can be specified to {@link Watchable#register register} to // * change the way changes to a watchable are reported. jpathwatch // * defines a set of modifiers in the {@link ExtendedWatchEventModifier} // * class. // * @param <T> The context type for the modifier. // * @see ExtendedWatchEventModifier // */ // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // // protected WatchEvent() // {} // // /** // * @return the context of this event, which is usually a reference to the // * object that has changed. In the case of WatchEvents for Path, the // * context will be a <code>Path</code> to the file that this event // * refers to, relative to the watched <code>Path</code> // */ // public abstract T context(); // /** // * The number of times this event occurred, if it is cumulative. It // * is not specified how events cumulate, so use this value for informational // * purposes only. // * @return the number of times this event has occurred, in case events of // * this kind have been aggregated into one WatchEvent instance. // */ // public abstract int count(); // // /** // * @return the kind of event that occurred. This will indicate what // * actually happened, for instance, StandardWatchEventKind#ENTRY_CREATE // * indicates that a file has been created. // */ // public abstract WatchEvent.Kind<T> kind(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // }
import name.pachler.nio.file.Path; import name.pachler.nio.file.WatchEvent; import name.pachler.nio.file.WatchEvent.Kind;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ public class PathWatchEvent extends WatchEvent<Path> { private int count; private Path path;
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public abstract class WatchEvent<T> { // /** // * Instances of this class act as tags to identify different kinds of // * events (like file creation or deletion) // * @param <T> The context this kind is intended for. In jpathwatch, only // * Path and Void are used as context types. // */ // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // /** // * A modifier can be specified to {@link Watchable#register register} to // * change the way changes to a watchable are reported. jpathwatch // * defines a set of modifiers in the {@link ExtendedWatchEventModifier} // * class. // * @param <T> The context type for the modifier. // * @see ExtendedWatchEventModifier // */ // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // // protected WatchEvent() // {} // // /** // * @return the context of this event, which is usually a reference to the // * object that has changed. In the case of WatchEvents for Path, the // * context will be a <code>Path</code> to the file that this event // * refers to, relative to the watched <code>Path</code> // */ // public abstract T context(); // /** // * The number of times this event occurred, if it is cumulative. It // * is not specified how events cumulate, so use this value for informational // * purposes only. // * @return the number of times this event has occurred, in case events of // * this kind have been aggregated into one WatchEvent instance. // */ // public abstract int count(); // // /** // * @return the kind of event that occurred. This will indicate what // * actually happened, for instance, StandardWatchEventKind#ENTRY_CREATE // * indicates that a file has been created. // */ // public abstract WatchEvent.Kind<T> kind(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchEvent.java import name.pachler.nio.file.Path; import name.pachler.nio.file.WatchEvent; import name.pachler.nio.file.WatchEvent.Kind; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ public class PathWatchEvent extends WatchEvent<Path> { private int count; private Path path;
private Kind<Path> kind;
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchKey.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public abstract class WatchEvent<T> { // /** // * Instances of this class act as tags to identify different kinds of // * events (like file creation or deletion) // * @param <T> The context this kind is intended for. In jpathwatch, only // * Path and Void are used as context types. // */ // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // /** // * A modifier can be specified to {@link Watchable#register register} to // * change the way changes to a watchable are reported. jpathwatch // * defines a set of modifiers in the {@link ExtendedWatchEventModifier} // * class. // * @param <T> The context type for the modifier. // * @see ExtendedWatchEventModifier // */ // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // // protected WatchEvent() // {} // // /** // * @return the context of this event, which is usually a reference to the // * object that has changed. In the case of WatchEvents for Path, the // * context will be a <code>Path</code> to the file that this event // * refers to, relative to the watched <code>Path</code> // */ // public abstract T context(); // /** // * The number of times this event occurred, if it is cumulative. It // * is not specified how events cumulate, so use this value for informational // * purposes only. // * @return the number of times this event has occurred, in case events of // * this kind have been aggregated into one WatchEvent instance. // */ // public abstract int count(); // // /** // * @return the kind of event that occurred. This will indicate what // * actually happened, for instance, StandardWatchEventKind#ENTRY_CREATE // * indicates that a file has been created. // */ // public abstract WatchEvent.Kind<T> kind(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchKey.java // public abstract class WatchKey { // protected WatchKey() // {} // /** // * This cancels the registration with the WatchService that this WatchKey // * was registered with. This means that no new events will be delivered to this // * key any more. Events that are pending can still be retreived with // * pollEvents(), and if the WatchKey is still marked as signalled a call to // * WatchService's poll() or take() functions will still return it. // */ // public abstract void cancel(); // // /** // * @return if this watch key is valid. A watch key is valid if // * <ul> // * <li>It has not been canceled</li> // * <li>The WatchService is not yet closed</li> // * </ul> // */ // public abstract boolean isValid(); // // /** // * Returns the events that have occurred for this WatchKey. Just calling // * this method will not reset the signalled state of this key; you'll have // * to call #reset() to indicate to the WatchService that the the client is // * ready to receive more events and that the key can be re-queued. // * After the WatchService has determined that events have occurred for a // * registered Watchable represented by a given WatchKey, it will return that // * key when the client calls it's WatchService#take() or WatchService#poll() // * methods. // * @return a list of events that have occurred since the last time that // * #pollEvents() was called. // */ // public abstract List<WatchEvent<?>> pollEvents(); // // /** // * Resets this {@link WatchKey} (marks it as non-signalled) so that it's // * corresponding {@link WatchService} can report it again via it's // * {@link WatchService#poll} and {@link WatchService#take} methods. // * // * @return <code>true</code> if the key could be reset, <code>false</code> // * otherwise (typically if the corresponding {@link WatchService} has been closed // * or if the the key was not signalled). // */ // public abstract boolean reset(); // }
import name.pachler.nio.file.Path; import java.util.List; import java.util.Vector; import name.pachler.nio.file.WatchEvent; import name.pachler.nio.file.WatchKey;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ public class PathWatchKey extends WatchKey { private int flags; private PathWatchService service;
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public abstract class WatchEvent<T> { // /** // * Instances of this class act as tags to identify different kinds of // * events (like file creation or deletion) // * @param <T> The context this kind is intended for. In jpathwatch, only // * Path and Void are used as context types. // */ // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // /** // * A modifier can be specified to {@link Watchable#register register} to // * change the way changes to a watchable are reported. jpathwatch // * defines a set of modifiers in the {@link ExtendedWatchEventModifier} // * class. // * @param <T> The context type for the modifier. // * @see ExtendedWatchEventModifier // */ // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // // protected WatchEvent() // {} // // /** // * @return the context of this event, which is usually a reference to the // * object that has changed. In the case of WatchEvents for Path, the // * context will be a <code>Path</code> to the file that this event // * refers to, relative to the watched <code>Path</code> // */ // public abstract T context(); // /** // * The number of times this event occurred, if it is cumulative. It // * is not specified how events cumulate, so use this value for informational // * purposes only. // * @return the number of times this event has occurred, in case events of // * this kind have been aggregated into one WatchEvent instance. // */ // public abstract int count(); // // /** // * @return the kind of event that occurred. This will indicate what // * actually happened, for instance, StandardWatchEventKind#ENTRY_CREATE // * indicates that a file has been created. // */ // public abstract WatchEvent.Kind<T> kind(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchKey.java // public abstract class WatchKey { // protected WatchKey() // {} // /** // * This cancels the registration with the WatchService that this WatchKey // * was registered with. This means that no new events will be delivered to this // * key any more. Events that are pending can still be retreived with // * pollEvents(), and if the WatchKey is still marked as signalled a call to // * WatchService's poll() or take() functions will still return it. // */ // public abstract void cancel(); // // /** // * @return if this watch key is valid. A watch key is valid if // * <ul> // * <li>It has not been canceled</li> // * <li>The WatchService is not yet closed</li> // * </ul> // */ // public abstract boolean isValid(); // // /** // * Returns the events that have occurred for this WatchKey. Just calling // * this method will not reset the signalled state of this key; you'll have // * to call #reset() to indicate to the WatchService that the the client is // * ready to receive more events and that the key can be re-queued. // * After the WatchService has determined that events have occurred for a // * registered Watchable represented by a given WatchKey, it will return that // * key when the client calls it's WatchService#take() or WatchService#poll() // * methods. // * @return a list of events that have occurred since the last time that // * #pollEvents() was called. // */ // public abstract List<WatchEvent<?>> pollEvents(); // // /** // * Resets this {@link WatchKey} (marks it as non-signalled) so that it's // * corresponding {@link WatchService} can report it again via it's // * {@link WatchService#poll} and {@link WatchService#take} methods. // * // * @return <code>true</code> if the key could be reset, <code>false</code> // * otherwise (typically if the corresponding {@link WatchService} has been closed // * or if the the key was not signalled). // */ // public abstract boolean reset(); // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchKey.java import name.pachler.nio.file.Path; import java.util.List; import java.util.Vector; import name.pachler.nio.file.WatchEvent; import name.pachler.nio.file.WatchKey; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ public class PathWatchKey extends WatchKey { private int flags; private PathWatchService service;
private Vector<WatchEvent<?>> eventQueue = new Vector<WatchEvent<?>>();
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchKey.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public abstract class WatchEvent<T> { // /** // * Instances of this class act as tags to identify different kinds of // * events (like file creation or deletion) // * @param <T> The context this kind is intended for. In jpathwatch, only // * Path and Void are used as context types. // */ // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // /** // * A modifier can be specified to {@link Watchable#register register} to // * change the way changes to a watchable are reported. jpathwatch // * defines a set of modifiers in the {@link ExtendedWatchEventModifier} // * class. // * @param <T> The context type for the modifier. // * @see ExtendedWatchEventModifier // */ // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // // protected WatchEvent() // {} // // /** // * @return the context of this event, which is usually a reference to the // * object that has changed. In the case of WatchEvents for Path, the // * context will be a <code>Path</code> to the file that this event // * refers to, relative to the watched <code>Path</code> // */ // public abstract T context(); // /** // * The number of times this event occurred, if it is cumulative. It // * is not specified how events cumulate, so use this value for informational // * purposes only. // * @return the number of times this event has occurred, in case events of // * this kind have been aggregated into one WatchEvent instance. // */ // public abstract int count(); // // /** // * @return the kind of event that occurred. This will indicate what // * actually happened, for instance, StandardWatchEventKind#ENTRY_CREATE // * indicates that a file has been created. // */ // public abstract WatchEvent.Kind<T> kind(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchKey.java // public abstract class WatchKey { // protected WatchKey() // {} // /** // * This cancels the registration with the WatchService that this WatchKey // * was registered with. This means that no new events will be delivered to this // * key any more. Events that are pending can still be retreived with // * pollEvents(), and if the WatchKey is still marked as signalled a call to // * WatchService's poll() or take() functions will still return it. // */ // public abstract void cancel(); // // /** // * @return if this watch key is valid. A watch key is valid if // * <ul> // * <li>It has not been canceled</li> // * <li>The WatchService is not yet closed</li> // * </ul> // */ // public abstract boolean isValid(); // // /** // * Returns the events that have occurred for this WatchKey. Just calling // * this method will not reset the signalled state of this key; you'll have // * to call #reset() to indicate to the WatchService that the the client is // * ready to receive more events and that the key can be re-queued. // * After the WatchService has determined that events have occurred for a // * registered Watchable represented by a given WatchKey, it will return that // * key when the client calls it's WatchService#take() or WatchService#poll() // * methods. // * @return a list of events that have occurred since the last time that // * #pollEvents() was called. // */ // public abstract List<WatchEvent<?>> pollEvents(); // // /** // * Resets this {@link WatchKey} (marks it as non-signalled) so that it's // * corresponding {@link WatchService} can report it again via it's // * {@link WatchService#poll} and {@link WatchService#take} methods. // * // * @return <code>true</code> if the key could be reset, <code>false</code> // * otherwise (typically if the corresponding {@link WatchService} has been closed // * or if the the key was not signalled). // */ // public abstract boolean reset(); // }
import name.pachler.nio.file.Path; import java.util.List; import java.util.Vector; import name.pachler.nio.file.WatchEvent; import name.pachler.nio.file.WatchKey;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ public class PathWatchKey extends WatchKey { private int flags; private PathWatchService service; private Vector<WatchEvent<?>> eventQueue = new Vector<WatchEvent<?>>();
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java // public abstract class Path implements Watchable { // // protected Path(){ // } // // @Override // public abstract boolean equals(Object obj); // // @Override // public abstract int hashCode(); // // public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException; // // public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException; // // public abstract Path resolve(Path other); // // @Override // public abstract String toString(); // // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public abstract class WatchEvent<T> { // /** // * Instances of this class act as tags to identify different kinds of // * events (like file creation or deletion) // * @param <T> The context this kind is intended for. In jpathwatch, only // * Path and Void are used as context types. // */ // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // /** // * A modifier can be specified to {@link Watchable#register register} to // * change the way changes to a watchable are reported. jpathwatch // * defines a set of modifiers in the {@link ExtendedWatchEventModifier} // * class. // * @param <T> The context type for the modifier. // * @see ExtendedWatchEventModifier // */ // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // // protected WatchEvent() // {} // // /** // * @return the context of this event, which is usually a reference to the // * object that has changed. In the case of WatchEvents for Path, the // * context will be a <code>Path</code> to the file that this event // * refers to, relative to the watched <code>Path</code> // */ // public abstract T context(); // /** // * The number of times this event occurred, if it is cumulative. It // * is not specified how events cumulate, so use this value for informational // * purposes only. // * @return the number of times this event has occurred, in case events of // * this kind have been aggregated into one WatchEvent instance. // */ // public abstract int count(); // // /** // * @return the kind of event that occurred. This will indicate what // * actually happened, for instance, StandardWatchEventKind#ENTRY_CREATE // * indicates that a file has been created. // */ // public abstract WatchEvent.Kind<T> kind(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchKey.java // public abstract class WatchKey { // protected WatchKey() // {} // /** // * This cancels the registration with the WatchService that this WatchKey // * was registered with. This means that no new events will be delivered to this // * key any more. Events that are pending can still be retreived with // * pollEvents(), and if the WatchKey is still marked as signalled a call to // * WatchService's poll() or take() functions will still return it. // */ // public abstract void cancel(); // // /** // * @return if this watch key is valid. A watch key is valid if // * <ul> // * <li>It has not been canceled</li> // * <li>The WatchService is not yet closed</li> // * </ul> // */ // public abstract boolean isValid(); // // /** // * Returns the events that have occurred for this WatchKey. Just calling // * this method will not reset the signalled state of this key; you'll have // * to call #reset() to indicate to the WatchService that the the client is // * ready to receive more events and that the key can be re-queued. // * After the WatchService has determined that events have occurred for a // * registered Watchable represented by a given WatchKey, it will return that // * key when the client calls it's WatchService#take() or WatchService#poll() // * methods. // * @return a list of events that have occurred since the last time that // * #pollEvents() was called. // */ // public abstract List<WatchEvent<?>> pollEvents(); // // /** // * Resets this {@link WatchKey} (marks it as non-signalled) so that it's // * corresponding {@link WatchService} can report it again via it's // * {@link WatchService#poll} and {@link WatchService#take} methods. // * // * @return <code>true</code> if the key could be reset, <code>false</code> // * otherwise (typically if the corresponding {@link WatchService} has been closed // * or if the the key was not signalled). // */ // public abstract boolean reset(); // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchKey.java import name.pachler.nio.file.Path; import java.util.List; import java.util.Vector; import name.pachler.nio.file.WatchEvent; import name.pachler.nio.file.WatchKey; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file.impl; /** * * @author count */ public class PathWatchKey extends WatchKey { private int flags; private PathWatchService service; private Vector<WatchEvent<?>> eventQueue = new Vector<WatchEvent<?>>();
private final Path path;
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // }
import java.io.IOException; import name.pachler.nio.file.WatchEvent.Kind; import name.pachler.nio.file.WatchEvent.Modifier;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * This class represents an abstract Path object that a WatchService can * operate on.<br/> * Note that Path is a new way of representing file system paths in JDK7 and * is included here to provide source level compatibility. This implementation * only uses it as a wrapper for java.io.File.</br> * To create a new Path instance, either use the Bootstrapper.newPath() * or Paths. * @author count */ public abstract class Path implements Watchable { protected Path(){ } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode();
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java import java.io.IOException; import name.pachler.nio.file.WatchEvent.Kind; import name.pachler.nio.file.WatchEvent.Modifier; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * This class represents an abstract Path object that a WatchService can * operate on.<br/> * Note that Path is a new way of representing file system paths in JDK7 and * is included here to provide source level compatibility. This implementation * only uses it as a wrapper for java.io.File.</br> * To create a new Path instance, either use the Bootstrapper.newPath() * or Paths. * @author count */ public abstract class Path implements Watchable { protected Path(){ } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode();
public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException;
sworisbreathing/jpathwatch
jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // }
import java.io.IOException; import name.pachler.nio.file.WatchEvent.Kind; import name.pachler.nio.file.WatchEvent.Modifier;
/* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * This class represents an abstract Path object that a WatchService can * operate on.<br/> * Note that Path is a new way of representing file system paths in JDK7 and * is included here to provide source level compatibility. This implementation * only uses it as a wrapper for java.io.File.</br> * To create a new Path instance, either use the Bootstrapper.newPath() * or Paths. * @author count */ public abstract class Path implements Watchable { protected Path(){ } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException;
// Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Kind<T> // { // /** // * @return the name of this modifier // */ // String name(); // /** // * @return the type of the WatchEvent's context value. // */ // Class<T> type(); // } // // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/WatchEvent.java // public static interface Modifier<T> // { // /** // * The modifier's name should be used for informative purposes // * only (like error reporting). // * @return the modifier's name // */ // String name(); // } // Path: jpathwatch-java/src/main/java/name/pachler/nio/file/Path.java import java.io.IOException; import name.pachler.nio.file.WatchEvent.Kind; import name.pachler.nio.file.WatchEvent.Modifier; /* * Copyright 2008-2011 Uwe Pachler * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. This particular file is * subject to the "Classpath" exception as provided in the LICENSE file * that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package name.pachler.nio.file; /** * This class represents an abstract Path object that a WatchService can * operate on.<br/> * Note that Path is a new way of representing file system paths in JDK7 and * is included here to provide source level compatibility. This implementation * only uses it as a wrapper for java.io.File.</br> * To create a new Path instance, either use the Bootstrapper.newPath() * or Paths. * @author count */ public abstract class Path implements Watchable { protected Path(){ } @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); public abstract WatchKey register(WatchService watcher, Kind<?>... events) throws IOException;
public abstract WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException;
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/cloudfunctions/CloudFunctionsFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import com.oracle.svm.core.annotate.AutomaticFeature; import com.oracle.svm.core.configure.ResourcesRegistry; import java.io.IOException; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.file.Path; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.function.Consumer; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature; import org.graalvm.nativeimage.hosted.RuntimeReflection;
/* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.cloudfunctions; /** * A feature which registers reflective usages of the Cloud Functions library. */ @AutomaticFeature final class CloudFunctionsFeature implements Feature { private static final String FUNCTION_INVOKER_CLASS = "com.google.cloud.functions.invoker.runner.Invoker"; private static final List<String> FUNCTIONS_CLASSES = Arrays.asList( "com.google.cloud.functions.HttpFunction", "com.google.cloud.functions.RawBackgroundFunction", "com.google.cloud.functions.BackgroundFunction"); @Override public void beforeAnalysis(BeforeAnalysisAccess access) { Class<?> invokerClass = access.findClassByName(FUNCTION_INVOKER_CLASS); if (invokerClass != null) { // JCommander libraries
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/cloudfunctions/CloudFunctionsFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import com.oracle.svm.core.annotate.AutomaticFeature; import com.oracle.svm.core.configure.ResourcesRegistry; import java.io.IOException; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.file.Path; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.function.Consumer; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature; import org.graalvm.nativeimage.hosted.RuntimeReflection; /* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.cloudfunctions; /** * A feature which registers reflective usages of the Cloud Functions library. */ @AutomaticFeature final class CloudFunctionsFeature implements Feature { private static final String FUNCTION_INVOKER_CLASS = "com.google.cloud.functions.invoker.runner.Invoker"; private static final List<String> FUNCTIONS_CLASSES = Arrays.asList( "com.google.cloud.functions.HttpFunction", "com.google.cloud.functions.RawBackgroundFunction", "com.google.cloud.functions.BackgroundFunction"); @Override public void beforeAnalysis(BeforeAnalysisAccess access) { Class<?> invokerClass = access.findClassByName(FUNCTION_INVOKER_CLASS); if (invokerClass != null) { // JCommander libraries
registerClassForReflection(
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/cloudfunctions/CloudFunctionsFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import com.oracle.svm.core.annotate.AutomaticFeature; import com.oracle.svm.core.configure.ResourcesRegistry; import java.io.IOException; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.file.Path; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.function.Consumer; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature; import org.graalvm.nativeimage.hosted.RuntimeReflection;
resourcesRegistry.addResources( "\\QMETA-INF/services/org.eclipse.jetty.http.HttpFieldPreEncoder\\E"); resourcesRegistry.addResources("\\Qorg/eclipse/jetty/http/encoding.properties\\E"); resourcesRegistry.addResources("\\Qorg/eclipse/jetty/http/mime.properties\\E"); resourcesRegistry.addResources("\\Qorg/eclipse/jetty/version/build.properties\\E"); resourcesRegistry.addResourceBundles("javax.servlet.LocalStrings"); resourcesRegistry.addResourceBundles("javax.servlet.http.LocalStrings"); // Register user-implemented Function classes List<Class<?>> functionClasses = FUNCTIONS_CLASSES.stream() .map(name -> access.findClassByName(name)) .collect(Collectors.toList()); scanJarClasspath(access, clazz -> { boolean isFunctionSubtype = functionClasses.stream() .anyMatch(function -> function.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())); if (isFunctionSubtype) { RuntimeReflection.register(clazz); RuntimeReflection.register(clazz.getDeclaredConstructors()); RuntimeReflection.register(clazz.getDeclaredMethods()); // This part is to register the parameterized class of BackgroundFunctions // for reflection; i.e. register type T in BackgroundFunction<T> for (Type type : clazz.getGenericInterfaces()) { if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) type; for (Type argument : paramType.getActualTypeArguments()) {
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/cloudfunctions/CloudFunctionsFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import com.oracle.svm.core.annotate.AutomaticFeature; import com.oracle.svm.core.configure.ResourcesRegistry; import java.io.IOException; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.file.Path; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.function.Consumer; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature; import org.graalvm.nativeimage.hosted.RuntimeReflection; resourcesRegistry.addResources( "\\QMETA-INF/services/org.eclipse.jetty.http.HttpFieldPreEncoder\\E"); resourcesRegistry.addResources("\\Qorg/eclipse/jetty/http/encoding.properties\\E"); resourcesRegistry.addResources("\\Qorg/eclipse/jetty/http/mime.properties\\E"); resourcesRegistry.addResources("\\Qorg/eclipse/jetty/version/build.properties\\E"); resourcesRegistry.addResourceBundles("javax.servlet.LocalStrings"); resourcesRegistry.addResourceBundles("javax.servlet.http.LocalStrings"); // Register user-implemented Function classes List<Class<?>> functionClasses = FUNCTIONS_CLASSES.stream() .map(name -> access.findClassByName(name)) .collect(Collectors.toList()); scanJarClasspath(access, clazz -> { boolean isFunctionSubtype = functionClasses.stream() .anyMatch(function -> function.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())); if (isFunctionSubtype) { RuntimeReflection.register(clazz); RuntimeReflection.register(clazz.getDeclaredConstructors()); RuntimeReflection.register(clazz.getDeclaredMethods()); // This part is to register the parameterized class of BackgroundFunctions // for reflection; i.e. register type T in BackgroundFunction<T> for (Type type : clazz.getGenericInterfaces()) { if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) type; for (Type argument : paramType.getActualTypeArguments()) {
registerClassHierarchyForReflection(access, argument.getTypeName());
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature;
/* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the grpc-netty-shaded dependency. */ @AutomaticFeature final class GrpcNettyFeature implements Feature { private static final String GRPC_NETTY_SHADED_CLASS = "io.grpc.netty.shaded.io.grpc.netty.NettyServer"; private static final String GOOGLE_AUTH_CLASS = "com.google.auth.oauth2.ServiceAccountCredentials"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadGoogleAuthClasses(access); loadGrpcNettyClasses(access); loadMiscClasses(access); } private static void loadGoogleAuthClasses(BeforeAnalysisAccess access) { // For com.google.auth:google-auth-library-oauth2-http Class<?> authClass = access.findClassByName(GOOGLE_AUTH_CLASS); if (authClass != null) {
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature; /* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the grpc-netty-shaded dependency. */ @AutomaticFeature final class GrpcNettyFeature implements Feature { private static final String GRPC_NETTY_SHADED_CLASS = "io.grpc.netty.shaded.io.grpc.netty.NettyServer"; private static final String GOOGLE_AUTH_CLASS = "com.google.auth.oauth2.ServiceAccountCredentials"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadGoogleAuthClasses(access); loadGrpcNettyClasses(access); loadMiscClasses(access); } private static void loadGoogleAuthClasses(BeforeAnalysisAccess access) { // For com.google.auth:google-auth-library-oauth2-http Class<?> authClass = access.findClassByName(GOOGLE_AUTH_CLASS); if (authClass != null) {
registerClassHierarchyForReflection(
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature;
/* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the grpc-netty-shaded dependency. */ @AutomaticFeature final class GrpcNettyFeature implements Feature { private static final String GRPC_NETTY_SHADED_CLASS = "io.grpc.netty.shaded.io.grpc.netty.NettyServer"; private static final String GOOGLE_AUTH_CLASS = "com.google.auth.oauth2.ServiceAccountCredentials"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadGoogleAuthClasses(access); loadGrpcNettyClasses(access); loadMiscClasses(access); } private static void loadGoogleAuthClasses(BeforeAnalysisAccess access) { // For com.google.auth:google-auth-library-oauth2-http Class<?> authClass = access.findClassByName(GOOGLE_AUTH_CLASS); if (authClass != null) { registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountCredentials"); registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountJwtAccessCredentials"); } } private static void loadGrpcNettyClasses(BeforeAnalysisAccess access) { // For io.grpc:grpc-netty-shaded Class<?> nettyShadedClass = access.findClassByName(GRPC_NETTY_SHADED_CLASS); if (nettyShadedClass != null) { // Misc. classes used by grpc-netty-shaded
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature; /* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the grpc-netty-shaded dependency. */ @AutomaticFeature final class GrpcNettyFeature implements Feature { private static final String GRPC_NETTY_SHADED_CLASS = "io.grpc.netty.shaded.io.grpc.netty.NettyServer"; private static final String GOOGLE_AUTH_CLASS = "com.google.auth.oauth2.ServiceAccountCredentials"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadGoogleAuthClasses(access); loadGrpcNettyClasses(access); loadMiscClasses(access); } private static void loadGoogleAuthClasses(BeforeAnalysisAccess access) { // For com.google.auth:google-auth-library-oauth2-http Class<?> authClass = access.findClassByName(GOOGLE_AUTH_CLASS); if (authClass != null) { registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountCredentials"); registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountJwtAccessCredentials"); } } private static void loadGrpcNettyClasses(BeforeAnalysisAccess access) { // For io.grpc:grpc-netty-shaded Class<?> nettyShadedClass = access.findClassByName(GRPC_NETTY_SHADED_CLASS); if (nettyShadedClass != null) { // Misc. classes used by grpc-netty-shaded
registerForReflectiveInstantiation(
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature;
/* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the grpc-netty-shaded dependency. */ @AutomaticFeature final class GrpcNettyFeature implements Feature { private static final String GRPC_NETTY_SHADED_CLASS = "io.grpc.netty.shaded.io.grpc.netty.NettyServer"; private static final String GOOGLE_AUTH_CLASS = "com.google.auth.oauth2.ServiceAccountCredentials"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadGoogleAuthClasses(access); loadGrpcNettyClasses(access); loadMiscClasses(access); } private static void loadGoogleAuthClasses(BeforeAnalysisAccess access) { // For com.google.auth:google-auth-library-oauth2-http Class<?> authClass = access.findClassByName(GOOGLE_AUTH_CLASS); if (authClass != null) { registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountCredentials"); registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountJwtAccessCredentials"); } } private static void loadGrpcNettyClasses(BeforeAnalysisAccess access) { // For io.grpc:grpc-netty-shaded Class<?> nettyShadedClass = access.findClassByName(GRPC_NETTY_SHADED_CLASS); if (nettyShadedClass != null) { // Misc. classes used by grpc-netty-shaded registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel");
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature; /* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the grpc-netty-shaded dependency. */ @AutomaticFeature final class GrpcNettyFeature implements Feature { private static final String GRPC_NETTY_SHADED_CLASS = "io.grpc.netty.shaded.io.grpc.netty.NettyServer"; private static final String GOOGLE_AUTH_CLASS = "com.google.auth.oauth2.ServiceAccountCredentials"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadGoogleAuthClasses(access); loadGrpcNettyClasses(access); loadMiscClasses(access); } private static void loadGoogleAuthClasses(BeforeAnalysisAccess access) { // For com.google.auth:google-auth-library-oauth2-http Class<?> authClass = access.findClassByName(GOOGLE_AUTH_CLASS); if (authClass != null) { registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountCredentials"); registerClassHierarchyForReflection( access, "com.google.auth.oauth2.ServiceAccountJwtAccessCredentials"); } } private static void loadGrpcNettyClasses(BeforeAnalysisAccess access) { // For io.grpc:grpc-netty-shaded Class<?> nettyShadedClass = access.findClassByName(GRPC_NETTY_SHADED_CLASS); if (nettyShadedClass != null) { // Misc. classes used by grpc-netty-shaded registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel");
registerClassForReflection(
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature;
} } private static void loadGrpcNettyClasses(BeforeAnalysisAccess access) { // For io.grpc:grpc-netty-shaded Class<?> nettyShadedClass = access.findClassByName(GRPC_NETTY_SHADED_CLASS); if (nettyShadedClass != null) { // Misc. classes used by grpc-netty-shaded registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.util.internal.NativeLibraryUtil"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.util.ReferenceCountUtil"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.buffer.AbstractByteBufAllocator"); // Epoll Libraries registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.channel.epoll.Epoll"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollChannelOption"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoopGroup"); registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollServerSocketChannel"); registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollSocketChannel"); // Unsafe field accesses
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassHierarchyForReflection(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // registerClassForReflection(access, className); // for (Class<?> nestedClass : clazz.getDeclaredClasses()) { // if (!Modifier.isPrivate(nestedClass.getModifiers())) { // registerClassHierarchyForReflection(access, nestedClass.getName()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflection."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForUnsafeFieldAccess( // FeatureAccess access, String className, String... fields) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // for (String fieldName : fields) { // try { // RuntimeReflection.register(clazz.getDeclaredField(fieldName)); // } catch (NoSuchFieldException ex) { // LOGGER.warning("Failed to register field " + fieldName + " for class " + className); // LOGGER.warning(ex.getMessage()); // } // } // } else { // LOGGER.warning( // "Failed to find " + className // + " on the classpath for unsafe fields access registration."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GrpcNettyFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassHierarchyForReflection; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForUnsafeFieldAccess; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature; } } private static void loadGrpcNettyClasses(BeforeAnalysisAccess access) { // For io.grpc:grpc-netty-shaded Class<?> nettyShadedClass = access.findClassByName(GRPC_NETTY_SHADED_CLASS); if (nettyShadedClass != null) { // Misc. classes used by grpc-netty-shaded registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.util.internal.NativeLibraryUtil"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.util.ReferenceCountUtil"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.buffer.AbstractByteBufAllocator"); // Epoll Libraries registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.channel.epoll.Epoll"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollChannelOption"); registerClassForReflection( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoopGroup"); registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollServerSocketChannel"); registerForReflectiveInstantiation( access, "io.grpc.netty.shaded.io.netty.channel.epoll.EpollSocketChannel"); // Unsafe field accesses
registerForUnsafeFieldAccess(
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/OpenCensusFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature;
/* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Registers reflection usage in OpenCensus libraries. */ @AutomaticFeature final class OpenCensusFeature implements Feature { private static final String OPEN_CENSUS_CLASS = "io.opencensus.impl.tags.TagsComponentImpl"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { if (access.findClassByName(OPEN_CENSUS_CLASS) != null) {
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerForReflectiveInstantiation(FeatureAccess access, String className) { // Class<?> clazz = access.findClassByName(className); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.registerForReflectiveInstantiation(clazz); // } else { // LOGGER.warning( // "Failed to find " + className + " on the classpath for reflective instantiation."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/OpenCensusFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerForReflectiveInstantiation; import com.oracle.svm.core.annotate.AutomaticFeature; import org.graalvm.nativeimage.hosted.Feature; /* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Registers reflection usage in OpenCensus libraries. */ @AutomaticFeature final class OpenCensusFeature implements Feature { private static final String OPEN_CENSUS_CLASS = "io.opencensus.impl.tags.TagsComponentImpl"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { if (access.findClassByName(OPEN_CENSUS_CLASS) != null) {
registerForReflectiveInstantiation(
GoogleCloudPlatform/native-image-support-java
native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GoogleJsonClientFeature.java
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // }
import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import com.oracle.svm.core.annotate.AutomaticFeature; import com.oracle.svm.core.configure.ResourcesRegistry; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature;
/* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the Google JSON Client. */ @AutomaticFeature final class GoogleJsonClientFeature implements Feature { private static final String GOOGLE_API_CLIENT_CLASS = "com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient"; private static final String GOOGLE_API_CLIENT_REQUEST_CLASS = "com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest"; private static final String GENERIC_JSON_CLASS = "com.google.api.client.json.GenericJson"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadApiClient(access); loadHttpClient(access); loadMiscClasses(access); } private void loadApiClient(BeforeAnalysisAccess access) { // For com.google.api-client:google-api-client Class<?> googleApiClientClass = access.findClassByName(GOOGLE_API_CLIENT_CLASS); if (googleApiClientClass != null) { // All reachable instances of the AbstractGoogleJsonClient must be registered. access.registerSubtypeReachabilityHandler(
// Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/NativeImageUtils.java // public static void registerClassForReflection(FeatureAccess access, String name) { // Class<?> clazz = access.findClassByName(name); // if (clazz != null) { // RuntimeReflection.register(clazz); // RuntimeReflection.register(clazz.getDeclaredConstructors()); // RuntimeReflection.register(clazz.getDeclaredFields()); // RuntimeReflection.register(clazz.getDeclaredMethods()); // } else { // LOGGER.warning( // "Failed to find " + name + " on the classpath for reflection."); // } // } // Path: native-image-support/src/main/java/com/google/cloud/nativeimage/features/core/GoogleJsonClientFeature.java import static com.google.cloud.nativeimage.features.NativeImageUtils.registerClassForReflection; import com.oracle.svm.core.annotate.AutomaticFeature; import com.oracle.svm.core.configure.ResourcesRegistry; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature; /* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.nativeimage.features.core; /** * Configures Native Image settings for the Google JSON Client. */ @AutomaticFeature final class GoogleJsonClientFeature implements Feature { private static final String GOOGLE_API_CLIENT_CLASS = "com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient"; private static final String GOOGLE_API_CLIENT_REQUEST_CLASS = "com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest"; private static final String GENERIC_JSON_CLASS = "com.google.api.client.json.GenericJson"; @Override public void beforeAnalysis(BeforeAnalysisAccess access) { loadApiClient(access); loadHttpClient(access); loadMiscClasses(access); } private void loadApiClient(BeforeAnalysisAccess access) { // For com.google.api-client:google-api-client Class<?> googleApiClientClass = access.findClassByName(GOOGLE_API_CLIENT_CLASS); if (googleApiClientClass != null) { // All reachable instances of the AbstractGoogleJsonClient must be registered. access.registerSubtypeReachabilityHandler(
(duringAccess, subtype) -> registerClassForReflection(access, subtype.getName()),
nfl/glitr
src/test/groovy/com/nfl/glitr/registry/type/TestInput.java
// Path: src/test/groovy/com/nfl/glitr/data/mutation/Bitrate.java // public class Bitrate implements Playable { // // private String id; // private Integer kbps; // private String url; // private Integer[] frames; // private Float gradeAverage; // private Double grade; // private Long durationNanos; // private Boolean valid; // private LocalDate createdDate; // private Instant modifiedDateTime; // // // public Integer getKbps() { // return kbps; // } // // public String getUrl() { // return url; // } // // public Long getDurationNanos() { // return durationNanos; // } // // public Integer[] getFrames() { // return frames; // } // // public Double getGrade() { // return grade; // } // // public Float getGradeAverage() { // return gradeAverage; // } // // public Boolean getValid() { // return valid; // } // // public LocalDate getCreatedDate() { // return createdDate; // } // // public Instant getModifiedDateTime() { // return modifiedDateTime; // } // // @Override // public String getId() { // return id; // } // }
import com.nfl.glitr.data.mutation.Bitrate;
package com.nfl.glitr.registry.type; public class TestInput { private String id; private String url;
// Path: src/test/groovy/com/nfl/glitr/data/mutation/Bitrate.java // public class Bitrate implements Playable { // // private String id; // private Integer kbps; // private String url; // private Integer[] frames; // private Float gradeAverage; // private Double grade; // private Long durationNanos; // private Boolean valid; // private LocalDate createdDate; // private Instant modifiedDateTime; // // // public Integer getKbps() { // return kbps; // } // // public String getUrl() { // return url; // } // // public Long getDurationNanos() { // return durationNanos; // } // // public Integer[] getFrames() { // return frames; // } // // public Double getGrade() { // return grade; // } // // public Float getGradeAverage() { // return gradeAverage; // } // // public Boolean getValid() { // return valid; // } // // public LocalDate getCreatedDate() { // return createdDate; // } // // public Instant getModifiedDateTime() { // return modifiedDateTime; // } // // @Override // public String getId() { // return id; // } // } // Path: src/test/groovy/com/nfl/glitr/registry/type/TestInput.java import com.nfl.glitr.data.mutation.Bitrate; package com.nfl.glitr.registry.type; public class TestInput { private String id; private String url;
private Bitrate bitrate;
nfl/glitr
src/main/java/com/nfl/glitr/calculator/QueryComplexityCalculator.java
// Path: src/main/java/com/nfl/glitr/exception/GlitrException.java // public class GlitrException extends RuntimeException { // // public GlitrException(String message) { // super(message); // } // // public GlitrException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/nfl/glitr/registry/schema/GlitrFieldDefinition.java // public class GlitrFieldDefinition extends FieldDefinition { // // private Set<GlitrMetaDefinition> metaDefinitions = new HashSet<>(); // // // public GlitrFieldDefinition(String name, Type type) { // super(name, type); // } // // public GlitrFieldDefinition(String name, Set<GlitrMetaDefinition> metaDefinitions) { // super(name, null); // this.metaDefinitions = metaDefinitions; // } // // public GlitrFieldDefinition(String name, Type type, Set<GlitrMetaDefinition> metaDefinitions) { // super(name, type); // this.metaDefinitions = metaDefinitions; // } // // public Set<GlitrMetaDefinition> getMetaDefinitions() { // return metaDefinitions; // } // // public void setMetaDefinitions(Set<GlitrMetaDefinition> metaDefinitions) { // this.metaDefinitions = metaDefinitions; // } // // public void addMetaDefinitions(GlitrMetaDefinition metaDefinition) { // if (this.metaDefinitions == null) { // this.metaDefinitions = new HashSet<>(); // } // this.metaDefinitions.add(metaDefinition); // } // } // // Path: src/main/java/com/nfl/glitr/registry/schema/GlitrMetaDefinition.java // public class GlitrMetaDefinition { // // private String name; // private Object value; // // // public GlitrMetaDefinition(String name, Object value) { // this.name = name; // this.value = value; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // // if (o == null || getClass() != o.getClass()) return false; // // GlitrMetaDefinition that = (GlitrMetaDefinition) o; // // return new EqualsBuilder() // .append(name, that.name) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(name) // .toHashCode(); // } // } // // Path: src/main/java/com/nfl/glitr/registry/schema/GraphQLConnectionList.java // public class GraphQLConnectionList extends GraphQLList { // public GraphQLConnectionList(GraphQLType wrappedType) { // super(wrappedType); // } // } // // Path: src/main/java/com/nfl/glitr/util/NodeUtil.java // public static final String COMPLEXITY_FORMULA_KEY = "complexity_formula"; // // Path: src/main/java/com/nfl/glitr/util/NodeUtil.java // public static final String COMPLEXITY_IGNORE_KEY = "complexity_ignore";
import com.nfl.glitr.exception.GlitrException; import com.nfl.glitr.registry.schema.GlitrFieldDefinition; import com.nfl.glitr.registry.schema.GlitrMetaDefinition; import com.nfl.glitr.registry.schema.GraphQLConnectionList; import graphql.language.*; import graphql.parser.InvalidSyntaxException; import graphql.parser.Parser; import graphql.parser.antlr.GraphqlLexer; import graphql.schema.*; import net.objecthunter.exp4j.Expression; import net.objecthunter.exp4j.ExpressionBuilder; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonToken; import org.antlr.v4.runtime.InputMismatchException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_FORMULA_KEY; import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_IGNORE_KEY; import static org.apache.commons.lang3.StringUtils.defaultString;
} public QueryComplexityCalculator(int maxCharacterLimit, int maxDepthLimit, int maxScoreLimit, int defaultMultiplier) { this.maxCharacterLimit = maxCharacterLimit; this.maxDepthLimit = maxDepthLimit; this.maxScoreLimit = maxScoreLimit; this.defaultMultiplier = defaultMultiplier; this.documentParser = new Parser(); } public QueryComplexityCalculator(int maxCharacterLimit, int maxDepthLimit, int maxScoreLimit, int defaultMultiplier, Parser documentParser) { this.maxCharacterLimit = maxCharacterLimit; this.maxDepthLimit = maxDepthLimit; this.maxScoreLimit = maxScoreLimit; this.defaultMultiplier = defaultMultiplier; this.documentParser = documentParser; } public QueryComplexityCalculator withSchema(GraphQLSchema schema) { this.schema = schema; return this; } /** * @param query - graphql query string * @param variables graphQL query variables * We want to validate the query or fail fast. */ public void validate(String query, Map<String, Object> variables) { if (characterLimitExceeded(query)) {
// Path: src/main/java/com/nfl/glitr/exception/GlitrException.java // public class GlitrException extends RuntimeException { // // public GlitrException(String message) { // super(message); // } // // public GlitrException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/nfl/glitr/registry/schema/GlitrFieldDefinition.java // public class GlitrFieldDefinition extends FieldDefinition { // // private Set<GlitrMetaDefinition> metaDefinitions = new HashSet<>(); // // // public GlitrFieldDefinition(String name, Type type) { // super(name, type); // } // // public GlitrFieldDefinition(String name, Set<GlitrMetaDefinition> metaDefinitions) { // super(name, null); // this.metaDefinitions = metaDefinitions; // } // // public GlitrFieldDefinition(String name, Type type, Set<GlitrMetaDefinition> metaDefinitions) { // super(name, type); // this.metaDefinitions = metaDefinitions; // } // // public Set<GlitrMetaDefinition> getMetaDefinitions() { // return metaDefinitions; // } // // public void setMetaDefinitions(Set<GlitrMetaDefinition> metaDefinitions) { // this.metaDefinitions = metaDefinitions; // } // // public void addMetaDefinitions(GlitrMetaDefinition metaDefinition) { // if (this.metaDefinitions == null) { // this.metaDefinitions = new HashSet<>(); // } // this.metaDefinitions.add(metaDefinition); // } // } // // Path: src/main/java/com/nfl/glitr/registry/schema/GlitrMetaDefinition.java // public class GlitrMetaDefinition { // // private String name; // private Object value; // // // public GlitrMetaDefinition(String name, Object value) { // this.name = name; // this.value = value; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // // if (o == null || getClass() != o.getClass()) return false; // // GlitrMetaDefinition that = (GlitrMetaDefinition) o; // // return new EqualsBuilder() // .append(name, that.name) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(name) // .toHashCode(); // } // } // // Path: src/main/java/com/nfl/glitr/registry/schema/GraphQLConnectionList.java // public class GraphQLConnectionList extends GraphQLList { // public GraphQLConnectionList(GraphQLType wrappedType) { // super(wrappedType); // } // } // // Path: src/main/java/com/nfl/glitr/util/NodeUtil.java // public static final String COMPLEXITY_FORMULA_KEY = "complexity_formula"; // // Path: src/main/java/com/nfl/glitr/util/NodeUtil.java // public static final String COMPLEXITY_IGNORE_KEY = "complexity_ignore"; // Path: src/main/java/com/nfl/glitr/calculator/QueryComplexityCalculator.java import com.nfl.glitr.exception.GlitrException; import com.nfl.glitr.registry.schema.GlitrFieldDefinition; import com.nfl.glitr.registry.schema.GlitrMetaDefinition; import com.nfl.glitr.registry.schema.GraphQLConnectionList; import graphql.language.*; import graphql.parser.InvalidSyntaxException; import graphql.parser.Parser; import graphql.parser.antlr.GraphqlLexer; import graphql.schema.*; import net.objecthunter.exp4j.Expression; import net.objecthunter.exp4j.ExpressionBuilder; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonToken; import org.antlr.v4.runtime.InputMismatchException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_FORMULA_KEY; import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_IGNORE_KEY; import static org.apache.commons.lang3.StringUtils.defaultString; } public QueryComplexityCalculator(int maxCharacterLimit, int maxDepthLimit, int maxScoreLimit, int defaultMultiplier) { this.maxCharacterLimit = maxCharacterLimit; this.maxDepthLimit = maxDepthLimit; this.maxScoreLimit = maxScoreLimit; this.defaultMultiplier = defaultMultiplier; this.documentParser = new Parser(); } public QueryComplexityCalculator(int maxCharacterLimit, int maxDepthLimit, int maxScoreLimit, int defaultMultiplier, Parser documentParser) { this.maxCharacterLimit = maxCharacterLimit; this.maxDepthLimit = maxDepthLimit; this.maxScoreLimit = maxScoreLimit; this.defaultMultiplier = defaultMultiplier; this.documentParser = documentParser; } public QueryComplexityCalculator withSchema(GraphQLSchema schema) { this.schema = schema; return this; } /** * @param query - graphql query string * @param variables graphQL query variables * We want to validate the query or fail fast. */ public void validate(String query, Map<String, Object> variables) { if (characterLimitExceeded(query)) {
throw new GlitrException(String.format("query length has exceeded the maximum of %d characters.", maxCharacterLimit));